/// <summary>
        /// Initializes a new instance of the <see cref="PortalSettings"/> class.
        ///   The PortalSettings Constructor encapsulates all of the logic
        ///   necessary to obtain configuration settings necessary to get
        ///   custom setting for a different portal than current (EditPortal.aspx.cs)<br/>
        ///   These Portal Settings are stored within a SQL database, and are
        ///   fetched below by calling the "GetPortalSettings" stored procedure.<br/>
        ///   This overload it is used
        /// </summary>
        /// <param name="portalId">
        /// The portal id.
        /// </param>
        /// <remarks>
        /// </remarks>
        private PortalSettings(int portalId)
        {
            this.ActivePage = new PageSettings();
            this.DesktopPages = new List<PageStripDetails>();
            this.ShowPages = true;
            this.MobilePages = new ArrayList();

            // Create Instance of Connection and Command Object
            using (var connection = Config.SqlConnectionString)
            using (var command = new SqlCommand("rb_GetPortalSettingsPortalID", connection))
            {
                // Mark the Command as a SPROC
                command.CommandType = CommandType.StoredProcedure;

                // Add Parameters to SPROC
                var parameterPortalId = new SqlParameter(StringsAtPortalId, SqlDbType.Int) { Value = portalId };
                command.Parameters.Add(parameterPortalId);

                // Open the database connection and execute the command
                connection.Open();
                var result = command.ExecuteReader(CommandBehavior.CloseConnection); // by Manu CloseConnection

                try
                {
                    if (result.Read())
                    {
                        this.PortalID = Int32.Parse(result["PortalID"].ToString());
                        this.PortalName = result["PortalName"].ToString();
                        this.PortalAlias = result["PortalAlias"].ToString();

                        // jes1111 - this.PortalTitle = ConfigurationSettings.AppSettings["PortalTitlePrefix"] + result["PortalName"].ToString();
                        this.PortalTitle = String.Concat(Config.PortalTitlePrefix, result["PortalName"].ToString());
                        this.PortalPath = result["PortalPath"].ToString();
                        this.ActivePage.PageID = 0;

                        // added Thierry (tiptopweb) used for dropdown for layout and theme
                        this.ActivePage.PortalPath = this.PortalPath;
                        this.ActiveModule = 0;
                    }
                    else
                    {
                        throw new Exception(
                            "The portal you requested cannot be found. PortalID: " + portalId,
                            new HttpException(404, "Portal not found"));
                    }
                }
                finally
                {
                    result.Close(); // by Manu, fixed bug 807858
                    connection.Close();
                }
            }

            // Go to get custom settings
            this.CustomSettings = GetPortalCustomSettings(portalId, GetPortalBaseSettings(this.PortalPath));
            this.CurrentLayout = this.CustomSettings["SITESETTINGS_PAGE_LAYOUT"].ToString();

            // Initialize Theme
            var themeManager = new ThemeManager(this.PortalPath);

            // Default
            themeManager.Load(this.CustomSettings["SITESETTINGS_THEME"].ToString());
            this.CurrentThemeDefault = themeManager.CurrentTheme;

            // Alternate
            themeManager.Load(this.CustomSettings["SITESETTINGS_ALT_THEME"].ToString());
            this.CurrentThemeAlt = themeManager.CurrentTheme;
        }
        /// <summary>
        /// Gets the current theme.
        /// </summary>
        /// <param name="requiredTheme">
        /// The required theme.
        /// </param>
        /// <returns>
        /// The theme.
        /// </returns>
        /// <remarks>
        /// </remarks>
        public Theme GetCurrentTheme(string requiredTheme)
        {
            switch (requiredTheme)
            {
                case "Alt":

                    // look for an alternate custom theme
                    if (this.ActivePage.CustomSettings["CustomThemeAlt"] != null &&
                        this.ActivePage.CustomSettings["CustomThemeAlt"].ToString().Length > 0)
                    {
                        var customTheme = this.ActivePage.CustomSettings["CustomThemeAlt"].ToString().Trim();
                        var themeManager = new ThemeManager(this.PortalPath);
                        themeManager.Load(customTheme);
                        return themeManager.CurrentTheme;
                    }

                    // no custom theme
                    return this.CurrentThemeAlt;
                default:

                    // look for an custom theme
                    if (this.ActivePage.CustomSettings[StringsCustomTheme] != null &&
                        this.ActivePage.CustomSettings[StringsCustomTheme].ToString().Length > 0)
                    {
                        var customTheme = this.ActivePage.CustomSettings[StringsCustomTheme].ToString().Trim();
                        var themeManager = new ThemeManager(this.PortalPath);
                        themeManager.Load(customTheme);
                        return themeManager.CurrentTheme;
                    }

                    // no custom theme
                    return this.CurrentThemeDefault;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PortalSettings"/> class.
        ///   The PortalSettings Constructor encapsulates all of the logic
        ///   necessary to obtain configuration settings necessary to render
        ///   a Portal Page view for a given request.<br/>
        ///   These Portal Settings are stored within a SQL database, and are
        ///   fetched below by calling the "GetPortalSettings" stored procedure.<br/>
        ///   This stored procedure returns values as SPROC output parameters,
        ///   and using three result sets.
        /// </summary>
        /// <param name="pageId">
        /// The page id.
        /// </param>
        /// <param name="portalAlias">
        /// The portal alias.
        /// </param>
        /// <remarks>
        /// </remarks>
        private PortalSettings(int pageId, string portalAlias)
        {
            this.ActivePage = new PageSettings();
            this.DesktopPages = new List<PageStripDetails>();
            this.ShowPages = true;
            this.MobilePages = new ArrayList();

            // Create Instance of Connection and Command Object
            using (var connection = Config.SqlConnectionString)
            using (var command = new SqlCommand("rb_GetPortalSettings", connection))
            {
                // Mark the Command as a SPROC
                command.CommandType = CommandType.StoredProcedure;

                // Add Parameters to SPROC
                var parameterPortalAlias = new SqlParameter("@PortalAlias", SqlDbType.NVarChar, 128)
                    {
                        Value = portalAlias // Specify the Portal Alias Dynamically
                    };
                command.Parameters.Add(parameterPortalAlias);
                var parameterPageId = new SqlParameter(StringsAtPageId, SqlDbType.Int, 4) { Value = pageId };
                command.Parameters.Add(parameterPageId);
                var parameterPortalLanguage = new SqlParameter("@PortalLanguage", SqlDbType.NVarChar, 12)
                    {
                       Value = this.PortalContentLanguage.Name
                    };
                command.Parameters.Add(parameterPortalLanguage);

                // Add out parameters to Sproc
                var parameterPortalId = new SqlParameter(StringsAtPortalId, SqlDbType.Int, 4)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterPortalId);
                var parameterPortalName = new SqlParameter("@PortalName", SqlDbType.NVarChar, 128)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterPortalName);
                var parameterPortalPath = new SqlParameter("@PortalPath", SqlDbType.NVarChar, 128)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterPortalPath);
                var parameterEditButton = new SqlParameter("@AlwaysShowEditButton", SqlDbType.Bit, 1)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterEditButton);
                var parameterPageName = new SqlParameter("@PageName", SqlDbType.NVarChar, 50)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterPageName);
                var parameterPageOrder = new SqlParameter("@PageOrder", SqlDbType.Int, 4)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterPageOrder);
                var parameterParentPageId = new SqlParameter("@ParentPageID", SqlDbType.Int, 4)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterParentPageId);
                var parameterMobilePageName = new SqlParameter("@MobilePageName", SqlDbType.NVarChar, 50)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterMobilePageName);
                var parameterAuthRoles = new SqlParameter("@AuthRoles", SqlDbType.NVarChar, 512)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterAuthRoles);
                var parameterShowMobile = new SqlParameter("@ShowMobile", SqlDbType.Bit, 1)
                    {
                       Direction = ParameterDirection.Output
                    };
                command.Parameters.Add(parameterShowMobile);
                SqlDataReader result;

                try
                {
                    // Open the database connection and execute the command
                    // try // jes1111
                    // {
                    connection.Open();
                    result = command.ExecuteReader(CommandBehavior.CloseConnection);
                    this.CurrentLayout = "Default";

                    // Read the first resultset -- Desktop Page Information
                    while (result.Read())
                    {
                        var tabDetails = new PageStripDetails
                            {
                                PageID = (int)result["PageID"],
                                ParentPageID = Int32.Parse("0" + result["ParentPageID"]),
                                PageName = (string)result["PageName"],
                                PageOrder = (int)result["PageOrder"],
                                PageLayout = this.CurrentLayout,
                                AuthorizedRoles = (string)result["AuthorizedRoles"]
                            };
                        this.PortalAlias = portalAlias;

                        // Update the AuthorizedRoles Variable
                        this.DesktopPages.Add(tabDetails);
                    }

                    if (this.DesktopPages.Count == 0)
                    {
                        return; // Abort load

                        // throw new Exception("The portal you requested has no Pages. PortalAlias: '" + portalAlias + "'", new HttpException(404, "Portal not found"));
                    }

                    // Read the second result --  Mobile Page Information
                    result.NextResult();

                    while (result.Read())
                    {
                        var tabDetails = new PageStripDetails
                            {
                                PageID = (int)result["PageID"],
                                PageName = (string)result["MobilePageName"],
                                PageLayout = this.CurrentLayout,
                                AuthorizedRoles = (string)result["AuthorizedRoles"]
                            };
                        this.MobilePages.Add(tabDetails);
                    }

                    // Read the third result --  Module Page Information
                    result.NextResult();

                    while (result.Read())
                    {
                        var m = new ModuleSettings
                            {
                                ModuleID = (int)result["ModuleID"],
                                ModuleDefID = (int)result["ModuleDefID"],
                                GuidID = (Guid)result["GeneralModDefID"],
                                PageID = (int)result["TabID"],
                                PaneName = (string)result["PaneName"],
                                ModuleTitle = (string)result["ModuleTitle"]
                            };
                        var value = result["AuthorizedEditRoles"];
                        m.AuthorizedEditRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["AuthorizedViewRoles"];
                        m.AuthorizedViewRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["AuthorizedAddRoles"];
                        m.AuthorizedAddRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["AuthorizedDeleteRoles"];
                        m.AuthorizedDeleteRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["AuthorizedPropertiesRoles"];
                        m.AuthorizedPropertiesRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;

                        // [email protected] (19/08/2004) Add support for move & delete module roles
                        value = result["AuthorizedMoveModuleRoles"];
                        m.AuthorizedMoveModuleRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["AuthorizedDeleteModuleRoles"];
                        m.AuthorizedDeleteModuleRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;

                        // Change by [email protected]
                        // Date: 6/2/2003
                        value = result["AuthorizedPublishingRoles"];
                        m.AuthorizedPublishingRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["SupportWorkflow"];
                        m.SupportWorkflow = !Convert.IsDBNull(value) ? (bool)value : false;

                        // Date: 27/2/2003
                        value = result["AuthorizedApproveRoles"];
                        m.AuthorizedApproveRoles = !Convert.IsDBNull(value) ? (string)value : string.Empty;
                        value = result["WorkflowState"];
                        m.WorkflowStatus = !Convert.IsDBNull(value)
                                               ? (WorkflowState)(0 + (byte)value)
                                               : WorkflowState.Original;

                        // End Change [email protected]
                        // Start Change [email protected]
                        try
                        {
                            value = result["SupportCollapsable"];
                        }
                        catch
                        {
                            value = DBNull.Value;
                        }

                        m.SupportCollapsable = DBNull.Value != value ? (bool)value : false;

                        // End Change  [email protected]
                        // Start Change [email protected]
                        try
                        {
                            value = result["ShowEveryWhere"];
                        }
                        catch
                        {
                            value = DBNull.Value;
                        }

                        m.ShowEveryWhere = DBNull.Value != value ? (bool)value : false;

                        // End Change  [email protected]
                        m.CacheTime = int.Parse(result["CacheTime"].ToString());
                        m.ModuleOrder = int.Parse(result["ModuleOrder"].ToString());
                        value = result["ShowMobile"];
                        m.ShowMobile = !Convert.IsDBNull(value) ? (bool)value : false;
                        m.DesktopSrc = result["DesktopSrc"].ToString();
                        m.MobileSrc = result["MobileSrc"].ToString();
                        m.Admin = bool.Parse(result["Admin"].ToString());
                        this.ActivePage.Modules.Add(m);
                    }

                    // Now read Portal out params
                    result.NextResult();
                    this.PortalID = (int)parameterPortalId.Value;
                    this.PortalName = (string)parameterPortalName.Value;

                    // jes1111 - this.PortalTitle = ConfigurationSettings.AppSettings["PortalTitlePrefix"] + this.PortalName;
                    this.PortalTitle = String.Concat(Config.PortalTitlePrefix, this.PortalName);

                    // jes1111 - this.PortalPath = Settings.Path.WebPathCombine(ConfigurationSettings.AppSettings["PortalsDirectory"], (string) parameterPortalPath.Value);
                    this.PortalPath = Path.WebPathCombine(Config.PortalsDirectory, (string)parameterPortalPath.Value);

                    // jes1111 - this.PortalSecurePath = ConfigurationSettings.AppSettings["PortalSecureDirectory"]; // added Thierry (tiptopweb) 12 Apr 2003
                    this.PortalSecurePath = Config.PortalSecureDirectory;
                    this.ActivePage.PageID = pageId;
                    this.ActivePage.PageLayout = this.CurrentLayout;
                    this.ActivePage.ParentPageID = Int32.Parse("0" + parameterParentPageId.Value);
                    this.ActivePage.PageOrder = (int)parameterPageOrder.Value;
                    this.ActivePage.MobilePageName = (string)parameterMobilePageName.Value;
                    this.ActivePage.AuthorizedRoles = (string)parameterAuthRoles.Value;
                    this.ActivePage.PageName = (string)parameterPageName.Value;
                    this.ActivePage.ShowMobile = (bool)parameterShowMobile.Value;
                    this.ActivePage.PortalPath = this.PortalPath; // [email protected] for page custom layout
                    result.Close(); // by Manu, fixed bug 807858

                    // }
                    // catch (Exception ex)
                    // {
                    // HttpContext.Current.Response.Write("Failed rb_GetPortalSettings for " + pageID.ToString() + ", " + portalAlias + ":<br/>"+ex.Message);
                    // HttpContext.Current.Response.End();
                    // //Response.Redirect("~/app_support/ErrorNoPortal.aspx",true);
                    // }
                }
                catch (SqlException sqex)
                {
                    var requestUri = HttpContext.Current.Request.Url;

                        throw new DatabaseUnreachableException("This may be a new db", sqex);

                    return;
                }
                finally
                {
                    // by Manu fix close bug #2
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }

            // Provide a valid tab id if it is missing

            // 11-10-2011
            // Changed to go to the first page that the user logged has permission to see

            //if (this.ActivePage.PageID == 0)
            //{
            //    this.ActivePage.PageID = ((PageStripDetails)this.DesktopPages[0]).PageID;
            //}

            // Go to get custom settings
            if (!Directory.Exists(Path.ApplicationPhysicalPath + this.PortalFullPath))
            {
                var portals = new PortalsDB();
                portals.CreatePortalPath(this.PortalAlias);
            }

            this.CustomSettings = GetPortalCustomSettings(this.PortalID, GetPortalBaseSettings(this.PortalPath));

            // Initialize Theme
            var themeManager = new ThemeManager(this.PortalPath);

            // Default
            themeManager.Load(this.CustomSettings["SITESETTINGS_THEME"].ToString());
            this.CurrentThemeDefault = themeManager.CurrentTheme;

            // Alternate
            if (this.CustomSettings["SITESETTINGS_ALT_THEME"].ToString() == this.CurrentThemeDefault.Name)
            {
                this.CurrentThemeAlt = this.CurrentThemeDefault;
            }
            else
            {
                themeManager.Load(this.CustomSettings["SITESETTINGS_ALT_THEME"].ToString());
                this.CurrentThemeAlt = themeManager.CurrentTheme;
            }

            // themeManager.Save(this.CustomSettings["SITESETTINGS_THEME"].ToString());
            // Set layout
            this.CurrentLayout = this.CustomSettings["SITESETTINGS_PAGE_LAYOUT"].ToString();

            // Jes1111
            // Generate DesktopPagesXml
            // jes1111 - if (bool.Parse(ConfigurationSettings.AppSettings["PortalSettingDesktopPagesXml"]))
            // if (Config.PortalSettingDesktopPagesXml)
            // this.DesktopPagesXml = GetDesktopPagesXml();
        }
        /// <summary>
        /// Theme definition and images
        /// </summary>
        /// <returns>
        /// The theme.
        /// </returns>
        /// <remarks>
        /// </remarks>
        public Theme GetCurrentTheme()
        {
            // look for an custom theme
            if (this.ActivePage.CustomSettings[StringsCustomTheme] != null &&
                this.ActivePage.CustomSettings[StringsCustomTheme].ToString().Length > 0)
            {
                var customTheme = this.ActivePage.CustomSettings[StringsCustomTheme].ToString().Trim();
                var themeManager = new ThemeManager(this.PortalPath);
                themeManager.Load(customTheme);
                return themeManager.CurrentTheme;
            }

            // no custom theme
            return this.CurrentThemeDefault;
        }
        /// <summary>
        /// Sets the CurrentTheme - allowing custom Theme per module
        /// </summary>
        protected virtual void SetupTheme()
        {
            // changed: Jes1111 - 2004-08-05 - supports custom theme per module
            // (better to do this in OnLoad than in RenderChildren, which is too late)
            var themeName = this.Settings.ContainsKey("MODULESETTINGS_THEME") && Int32.Parse(this.Settings["MODULESETTINGS_THEME"].ToString()) == (int)ThemeList.Alt
                                ? "Alt"
                                : "Default";

            // end: Jes1111

            // added: Jes1111 - 2004-08-05 - supports custom theme per module
            if (this.PortalSettings.CustomSettings.ContainsKey("SITESETTINGS_ALLOW_MODULE_CUSTOM_THEMES") &&
                this.PortalSettings.CustomSettings["SITESETTINGS_ALLOW_MODULE_CUSTOM_THEMES"].ToString().Length != 0 &&
                bool.Parse(this.PortalSettings.CustomSettings["SITESETTINGS_ALLOW_MODULE_CUSTOM_THEMES"].ToString()) &&
                this.Settings.ContainsKey("MODULESETTINGS_MODULE_THEME") &&
                this.Settings["MODULESETTINGS_MODULE_THEME"].ToString().Trim().Length > 0)
            {
                // substitute custom theme for this module
                var tm = new ThemeManager(this.PortalSettings.PortalPath);
                tm.Load(this.Settings["MODULESETTINGS_MODULE_THEME"].ToString());
                this.CurrentTheme = tm.CurrentTheme;

                // get CSS file, add ModuleID to each line and add resulting string to CssImportList
                try
                {
                    var cssHelper = new CssHelper();
                    var selectorPrefix = string.Concat("#mID", this.ModuleID);
                    var cssFileName = this.Page.Server.MapPath(this.CurrentTheme.CssFile);
                    this.Page.RegisterCssImport(
                        this.ModuleID.ToString(), cssHelper.ParseCss(cssFileName, selectorPrefix));
                }
                catch (Exception ex)
                {
                    var error =
                        string.Format(
                            "Failed to load custom theme '{0}' for ModuleID {1}. Continuing with default tab theme. Message was: {2}",
                            this.CurrentTheme.CssFile,
                            this.ModuleID,
                            ex.Message);
                    ErrorHandler.Publish(LogLevel.Error, error);
                    this.CurrentTheme = this.PortalSettings.GetCurrentTheme(themeName);
                }
            }
            else
            {
                // original behaviour unchanged
                this.CurrentTheme = this.PortalSettings.GetCurrentTheme(themeName);
            }

            // end change: Jes1111
        }