//
        // GET: /Module/
        public JsonResult AddModule(string title, string moduleType, string paneLocation, string viewPermission, string pageId, string ModuleId)
        {
            // All new modules go to the end of the content pane
            var m = new ModuleItem();
            m.Title = title;
            m.ModuleDefID = Int32.Parse(moduleType);
            m.Order = 999;

            // save to database
            var mod = new ModulesDB();
            var modId = Int32.Parse(ModuleId);

            m.ID = mod.AddModule(
                Int32.Parse(pageId),
                m.Order,
                paneLocation,
                m.Title,
                m.ModuleDefID,
                0,
                PortalSecurity.GetEditPermissions(modId),
                viewPermission,
                PortalSecurity.GetAddPermissions(modId),
                PortalSecurity.GetDeletePermissions(modId),
                PortalSecurity.GetPropertiesPermissions(modId),
                PortalSecurity.GetMoveModulePermissions(modId),
                PortalSecurity.GetDeleteModulePermissions(modId),
                false,
                PortalSecurity.GetPublishPermissions(modId),
                false,
                false,
                false);

            // End Change [email protected]

            //// reload the portalSettings from the database

            //this.Context.Items["PortalSettings"] = new PortalSettings(this.PageID, this.PortalSettings.PortalAlias);
            //this.PortalSettings = (PortalSettings)this.Context.Items["PortalSettings"];

            // reorder the modules in the content pane
            //var modules = GetModules("ContentPane", Int32.Parse(pageId), Int32.Parse(portalId));
            //this.OrderModules(modules);

            //// resave the order
            //foreach (ModuleItem item in modules) {
            //    mod.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
            //}

            //// Redirect to the same page to pick up changes
            ////this.Response.Redirect(this.AppendModuleID(this.Request.RawUrl, m.ID));
            var list = GetModules(paneLocation, Int32.Parse(pageId));

            StringBuilder ls = new StringBuilder();
            foreach (ModuleItem md in list)
            {
                ls.AppendFormat("<option value=\"{0}\">{1}</option>", md.ID, md.Title);
            }

            return Json(new { value = ls.ToString() });
        }
Beispiel #2
0
        /// <summary>
        /// Handles OnDelete
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected override void OnDelete(EventArgs e)
        {
            base.OnDelete(e);

            ModulesDB modules = new ModulesDB();
            // TODO add userEmail and useRecycler
            modules.DeleteModule(_moduleID);

            _moduleID = 0;

            RedirectBackToReferringPage();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleDefId"></param>
        /// <param name="pageId"></param>
        /// <param name="title"></param>
        /// <param name="alsoIfExists"></param>
        /// <returns></returns>
        public static int AddModuleToPage(int moduleDefId, int pageId, string title, bool alsoIfExists)
        {
            var module = default(rb_Modules);
            using (var context = new AppleseedDBContext()) {
                module = context.rb_Modules.Where(d => d.TabID == pageId && d.ModuleDefID == moduleDefId).FirstOrDefault();
            }

            if (module == default(rb_Modules) || alsoIfExists) {
                var sdb = new ModulesDB();
                return  sdb.AddModule(pageId, 0, "ContentPane", title, moduleDefId, 0, "Admins", "All Users", "Admins", "Admins", "Admins", "Admins", "Admins", false, string.Empty, true, false, false);
            } else {
                return module.ModuleID;
            }
        }
        /// <summary>
        /// The BindData helper method is used to bind the list of
        /// module definitions for this portal to an asp:datalist server control
        /// </summary>
        protected void BindData()
        {
            // Get the portal's defs from the database
            SqlDataReader dr = new ModulesDB().GetCurrentModuleDefinitions(this.PortalSettings.PortalID);

            DataTable userTable = new DataTable();
            userTable.Columns.Add(new DataColumn("FriendlyName", typeof (string)));
            userTable.Columns.Add(new DataColumn("ModuleDefID", typeof (string)));

            DataTable adminTable = new DataTable();
            adminTable.Columns.Add(new DataColumn("FriendlyName", typeof (string)));
            adminTable.Columns.Add(new DataColumn("ModuleDefID", typeof (string)));

            DataRow drow;
            while (dr.Read())
            {
                if (bool.Parse(dr["Admin"].ToString()))
                {
                    drow = adminTable.NewRow();
                    drow["ModuleDefID"] = dr["ModuleDefID"];
                    string aux = dr["FriendlyName"].ToString();
                    if (aux.StartsWith("Admin"))
                    {
                        aux = aux.Substring(5);
                        while (aux[0] == ' ' || aux[0] == '-') aux = aux.Substring(1);
                    }
                    drow["FriendlyName"] = aux;
                    adminTable.Rows.Add(drow);
                }
                else
                {
                    drow = userTable.NewRow();
                    drow["ModuleDefID"] = dr["ModuleDefID"];
                    drow["FriendlyName"] = dr["FriendlyName"];
                    userTable.Rows.Add(drow);
                }
            }
            userModules.DataSource = userTable;
            userModules.DataBind();
            adminModules.DataSource = adminTable;
            adminModules.DataBind();
            dr.Close();
        }
        public ActionResult SaveTitle(string id, string value)
        {
            try {
                var parse = id.Split('_');
                int moduleId = Int32.Parse(parse[1]);
                // Si el usuario tiene permiso para modificar
                if (PortalSecurity.HasEditPermissions(moduleId)) {
                    var modules = new Appleseed.Framework.Site.Data.ModulesDB();

                    modules.UpdateModuleTitle(moduleId, value);

                    return Json(new { result = true });

                }
                return Json(new { result = false });
            } catch (Exception) {
                return Json(new { result = false });
            }
        }
Beispiel #6
0
        public ActionResult SaveTitle(string id, string value)
        {
            try {
                var parse    = id.Split('_');
                int moduleId = Int32.Parse(parse[1]);
                // Si el usuario tiene permiso para modificar
                if (PortalSecurity.HasEditPermissions(moduleId))
                {
                    var modules = new Appleseed.Framework.Site.Data.ModulesDB();

                    modules.UpdateModuleTitle(moduleId, value);



                    return(Json(new { result = true }));
                }
                return(Json(new { result = false }));
            } catch (Exception) {
                return(Json(new { result = false }));
            }
        }
        /// <summary>
        /// Delete a Module definition
        /// </summary>
        /// <param name="e">
        /// The <see cref="T:System.EventArgs"/> instance containing the event data.
        /// </param>
        protected override void OnDelete(EventArgs e)
        {
            try
            {
                var modules = new ModulesDB();
                modules.DeleteModuleDefinition(new Guid(this.ModuleGuid.Text));

                // Redirect back to the portal admin page
                this.RedirectBackToReferringPage();
            }
            catch (ThreadAbortException)
            {
                // normal with redirect
            }
            catch (Exception ex)
            {
                this.lblErrorDetail.Text = General.GetString(
                    "MODULE_DEFINITIONS_DELETE_ERROR", "An error occurred deleting module.", this);
                this.lblErrorDetail.Visible = true;
                ErrorHandler.Publish(LogLevel.Error, this.lblErrorDetail.Text, ex);
            }
        }
Beispiel #8
0
        private ArrayList GetModules(string pane, int pageId)
        {
            var paneModules = new ArrayList();
            var modules     = new Appleseed.Framework.Site.Data.ModulesDB();

            foreach (ModuleSettings _module in modules.getModulesSettingsInPage(pageId, pane))
            {
                if (_module.PaneName.ToLower() == pane.ToLower() &&
                    pageId == _module.PageID)
                {
                    var m = new ModuleItem();
                    m.Title       = _module.ModuleTitle;
                    m.ID          = _module.ModuleID;
                    m.ModuleDefID = _module.ModuleDefID;
                    m.Order       = _module.ModuleOrder;
                    paneModules.Add(m);
                }
            }

            InsertionSort(paneModules, ModuleItem.Compare);


            return(paneModules);
        }
        public JsonResult DeleteBtn_Click(string pane, string pageId, string selectedIndex)
        {
            var modules = this.GetModules(pane, Int32.Parse(pageId));
            var index = Int32.Parse(selectedIndex);

            var m = (ModuleItem)modules[index];
            if (m.ID > -1)
            {
                // [email protected] (20/08/2004) Add role control for delete module
                if (PortalSecurity.IsInRoles(PortalSecurity.GetDeleteModulePermissions(m.ID)))
                {
                    // must delete from database too
                    var moddb = new ModulesDB();

                    // TODO add userEmail and useRecycler
                    moddb.DeleteModule(m.ID);

                    // reorder the modules in the pane
                    modules = this.GetModules(pane, Int32.Parse(pageId));
                    var list = this.OrderModules(modules);

                    // resave the order
                    foreach (ModuleItem item in modules)
                    {
                        moddb.UpdateModuleOrder(item.ID, item.Order, pane);
                    }

                    StringBuilder ls = new StringBuilder();
                    foreach (ModuleItem md in list)
                    {
                        ls.AppendFormat("<option value=\"{0}\">{1}</option>", md.ID, md.Title);
                    }
                    return Json(new { error = false, value = ls.ToString() });

                }
                else
                {
                    return Json(new { error = true });
                }
            }
            return Json(new { error = true });
        }
        private ArrayList GetModules(string pane, int pageId)
        {
            var paneModules = new ArrayList();
            var modules = new Appleseed.Framework.Site.Data.ModulesDB();

            foreach (ModuleSettings _module in modules.getModulesSettingsInPage(pageId, pane))
            {
                if (_module.PaneName.ToLower() == pane.ToLower() &&
                    pageId == _module.PageID)
                {
                    var m = new ModuleItem();
                    m.Title = _module.ModuleTitle;
                    m.ID = _module.ModuleID;
                    m.ModuleDefID = _module.ModuleDefID;
                    m.Order = _module.ModuleOrder;
                    paneModules.Add(m);
                }
            }

            InsertionSort(paneModules, ModuleItem.Compare);

            return paneModules;
        }
        /// <summary>
        /// The UpDownClick server event handler on this page is
        ///   used to move a portal module up or down on a tab's layout pane
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        private void UpDownClick(object sender, EventArgs e)
        {
            // string cmd = ((ModuleButton)sender).CommandName;
            // string pane = ((ModuleButton)sender).CommandArgument;
            var cmd = ((ModuleButton)sender).Attributes["direction"];
            var pane = ((ModuleButton)sender).Attributes["pane"];

            var modules = this.GetModules(pane);

            // Determine the delta to apply in the order number for the module
            // within the list.  +3 moves down one item; -3 moves up one item
            var delta = cmd == "down" ? 3 : -3;

            foreach (var item in modules.Where(item => item.ID == this.ModuleID))
            {
                item.Order += delta;
            }

            // reorder the modules in the content pane
            OrderModules(modules);

            // resave the order
            var admin = new ModulesDB();
            foreach (var item in modules)
            {
                admin.UpdateModuleOrder(item.ID, item.Order, pane);
            }

            // Redirect to the same page to pick up changes
            this.Page.Response.Redirect(AppendModuleId(this.Page.Request.RawUrl, this.ModuleID));
        }
        /// <summary>
        /// This method override the security cookie for allow
        ///   to access property pages of selected module in tab.
        ///   [email protected] (2004/07/23)
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void SetSecurityAccess()
        {
            HttpCookie cookie;
            DateTime time;
            TimeSpan span;
            var guidsInUse = string.Empty;
            Guid guid;

            var mdb = new ModulesDB();

            //foreach (ListItem li in this.topPane.Items)
            //{
            //    guid = mdb.GetModuleGuid(int.Parse(li.Value));
            //    if (guid != Guid.Empty)
            //    {
            //        guidsInUse += guid.ToString().ToUpper() + "@";
            //    }
            //}

            //foreach (ListItem li in this.leftPane.Items)
            //{
            //    guid = mdb.GetModuleGuid(int.Parse(li.Value));
            //    if (guid != Guid.Empty)
            //    {
            //        guidsInUse += guid.ToString().ToUpper() + "@";
            //    }
            //}

            //foreach (ListItem li in this.contentPane.Items)
            //{
            //    guid = mdb.GetModuleGuid(int.Parse(li.Value));
            //    if (guid != Guid.Empty)
            //    {
            //        guidsInUse += guid.ToString().ToUpper() + "@";
            //    }
            //}

            //foreach (ListItem li in this.rightPane.Items)
            //{
            //    guid = mdb.GetModuleGuid(int.Parse(li.Value));
            //    if (guid != Guid.Empty)
            //    {
            //        guidsInUse += guid.ToString().ToUpper() + "@";
            //    }
            //}

            //foreach (ListItem li in this.bottomPane.Items)
            //{
            //    guid = mdb.GetModuleGuid(int.Parse(li.Value));
            //    if (guid != Guid.Empty)
            //    {
            //        guidsInUse += guid.ToString().ToUpper() + "@";
            //    }
            //}

            cookie = new HttpCookie("AppleseedSecurity", guidsInUse);
            time = DateTime.Now;
            span = new TimeSpan(0, 2, 0, 0, 0); // 120 minutes to expire
            cookie.Expires = time.Add(span);
            base.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// The BindData helper method is used to update the tab's
        ///   layout panes with the current configuration information
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void BindData()
        {
            var page = this.PortalSettings.ActivePage;

            // Populate Page Names, etc.
            this.tabName.Text = page.PageName;
            this.mobilePageName.Text = page.MobilePageName;
            this.showMobile.Checked = page.ShowMobile;

            // Populate the "ParentPage" Data
            var t = new PagesDB();
            var items = t.GetPagesParent(this.PortalSettings.PortalID, this.PageID);
            this.parentPage.DataSource = items;
            this.parentPage.DataBind();

            if (this.parentPage.Items.FindByValue(page.ParentPageID.ToString()) != null)
            {
                // parentPage.Items.FindByValue( tab.ParentPageID.ToString() ).Selected = true;
                this.parentPage.SelectedValue = page.ParentPageID.ToString();
            }

            // Translate
            if (this.parentPage.Items.FindByText(" ROOT_LEVEL") != null)
            {
                this.parentPage.Items.FindByText(" ROOT_LEVEL").Text = General.GetString(
                    "ROOT_LEVEL", "Root Level", this.parentPage);
            }

            // Populate checkbox list with all security roles for this portal
            // and "check" the ones already configured for this tab
            var users = new UsersDB();
            var roles = users.GetPortalRoles(this.PortalSettings.PortalAlias);

            // Clear existing items in checkboxlist
            this.authRoles.Items.Clear();

            foreach (var role in roles)
            {
                var item = new ListItem();
                item.Text = role.Name;
                item.Value = role.Id.ToString();

                if (page.AuthorizedRoles.LastIndexOf(item.Text) > -1)
                {
                    item.Selected = true;
                }

                this.authRoles.Items.Add(item);
            }

            // Populate the "Add Module" Data
            var m = new ModulesDB();
            var modules = new SortedList<string, string>();
            var drCurrentModuleDefinitions = m.GetCurrentModuleDefinitions(this.PortalSettings.PortalID);
            //if (PortalSecurity.IsInRoles("Admins") || !bool.Parse(drCurrentModuleDefinitions["Admin"].ToString()))
            //{
            var htmlId = "0";
            try {
                while (drCurrentModuleDefinitions.Read()) {
                    if ((!modules.ContainsKey(drCurrentModuleDefinitions["FriendlyName"].ToString())) &&
                        (PortalSecurity.IsInRoles("Admins") || !bool.Parse(drCurrentModuleDefinitions["Admin"].ToString()))) {
                        modules.Add(
                            // moduleType.Items.Add(
                            // new ListItem(drCurrentModuleDefinitions["FriendlyName"].ToString(),
                            // drCurrentModuleDefinitions["ModuleDefID"].ToString()));
                            drCurrentModuleDefinitions["FriendlyName"].ToString(),
                            drCurrentModuleDefinitions["ModuleDefID"].ToString());
                        if (drCurrentModuleDefinitions["FriendlyName"].ToString().Equals("HTML Content"))
                            htmlId = drCurrentModuleDefinitions["ModuleDefID"].ToString();
                    }
                }
            }
            finally {
                drCurrentModuleDefinitions.Close();
            }
            //}

            // Dictionary<string, string> actions = ModelServices.GetMVCActionModules();
            // foreach (string key in actions.Keys) {
            // modules.Add(key, actions[key]);
            // }
            this.moduleType.DataSource = modules;
            this.moduleType.DataBind();
            this.moduleType.SelectedValue = htmlId;

            // Now it's the load is by ajax 1/september/2011
            // Populate Top Pane Module Data
            //this.topList = this.GetModules("TopPane");
            //this.topPane.DataBind();

            //// Populate Left Hand Pane Module Data
            //this.leftList = this.GetModules("LeftPane");
            //this.leftPane.DataBind();

            //// Populate Content Pane Module Data
            //this.contentList = this.GetModules("ContentPane");
            //this.contentPane.DataBind();

            //// Populate Right Hand Module Data
            //this.rightList = this.GetModules("RightPane");
            //this.rightPane.DataBind();

            //// Populate Bottom Module Data
            //this.bottomList = this.GetModules("BottomPane");
            //this.bottomPane.DataBind();
        }
        /// <summary>
        /// The RightLeft_Click server event handler on this page is
        ///   used to move a portal module between layout panes on
        ///   the tab page
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="T:System.Web.UI.ImageClickEventArgs"/> instance containing the event data.
        /// </param>
        /// <remarks>
        /// </remarks>
        protected void RightLeft_Click(object sender, ImageClickEventArgs e)
        {
            var sourcePane = ((ImageButton)sender).Attributes["sourcepane"];
            var targetPane = ((ImageButton)sender).Attributes["targetpane"];
            var sourceBox = (ListBox)this.Page.FindControl(sourcePane);
            if (sourceBox == null)
            {
                sourceBox = (ListBox)this.Page.Master.FindControl("Content").FindControl(sourcePane);
            }

            var targetBox = (ListBox)this.Page.FindControl(targetPane);
            if (targetBox == null)
            {
                targetBox = (ListBox)this.Page.Master.FindControl("Content").FindControl(targetPane);
            }

            if (sourceBox.SelectedIndex != -1)
            {
                // get source arraylist
                var sourceList = this.GetModules(sourcePane);

                // get a reference to the module to move
                // and assign a high order number to send it to the end of the target list
                var m = (ModuleItem)sourceList[sourceBox.SelectedIndex];

                if (PortalSecurity.IsInRoles(PortalSecurity.GetMoveModulePermissions(m.ID)))
                {
                    // add it to the database
                    var admin = new ModulesDB();
                    admin.UpdateModuleOrder(m.ID, 99, targetPane);

                    // delete it from the source list
                    sourceList.RemoveAt(sourceBox.SelectedIndex);

                    // reload the portalSettings from the database
                    HttpContext.Current.Items["PortalSettings"] = PortalSettings.GetPortalSettings(
                        this.PageID, this.PortalSettings.PortalAlias);
                    this.PortalSettings = (PortalSettings)this.Context.Items["PortalSettings"];

                    // reorder the modules in the source pane
                    sourceList = this.GetModules(sourcePane);
                    this.OrderModules(sourceList);

                    // resave the order
                    foreach (ModuleItem item in sourceList)
                    {
                        admin.UpdateModuleOrder(item.ID, item.Order, sourcePane);
                    }

                    // reorder the modules in the target pane
                    var targetList = this.GetModules(targetPane);
                    this.OrderModules(targetList);

                    // resave the order
                    foreach (ModuleItem item in targetList)
                    {
                        admin.UpdateModuleOrder(item.ID, item.Order, targetPane);
                    }

                    // Redirect to the same page to pick up changes
                    this.Response.Redirect(this.AppendModuleID(this.Request.RawUrl, m.ID));
                }
                else
                {
                    this.msgError.Visible = true;
                }
            }
        }
Beispiel #15
0
        /// <summary>
        /// Binds the control and all its child controls to the specified data source.
        /// </summary>
        public override void DataBind()
        {
            if (HttpContext.Current != null)
            {
                //Init data
                ArrayList list = new ArrayList();

                // Obtain PortalSettings from Current Context
                PortalSettings PortalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"];

                string homeLink = "<a";
                string menuLink;

                // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                if (CssClass.Length != 0)
                    homeLink = homeLink + " class=\"" + CssClass + "\"";

                homeLink = homeLink + " href='" + HttpUrlBuilder.BuildUrl() + "'>" +
                           General.GetString("Appleseed", "HOME") + "</a>";

                // If user logged in, customize welcome message
                if (HttpContext.Current.Request.IsAuthenticated == true)
                {
                    if (ShowWelcome)
                    {
                        list.Add(General.GetString("HEADER_WELCOME", "Welcome", this) + "&#160;" +
                                 PortalSettings.CurrentUser.Identity.Name + "!");
                    }

                    if (ShowHome)
                    {
                        list.Add(homeLink);
                    }

                    if (ShowHelp)
                    {
                        list.Add(GetHelpLink());
                    }

                    // Added by Mario Endara <*****@*****.**> (2004/11/06)
                    // Find Tab module to see if the user has add/edit rights
                    ModulesDB modules = new ModulesDB();
                    Guid TabGuid = new Guid("{1C575D94-70FC-4A83-80C3-2087F726CBB3}");
                    // Added by Xu Yiming <*****@*****.**> (2004/12/6)
                    // Modify for support Multi or zero Pages Modules in a single portal.
                    bool HasEditPermissionsOnTabs = false;
                    int TabModuleID = 0;

            //					SqlDataReader result = modules.FindModulesByGuid(PortalSettings.PortalID, TabGuid);
            //					while(result.Read())
            //					{
            //						TabModuleID=(int)result["ModuleId"];

                    foreach (ModuleItem m in modules.FindModuleItemsByGuid(PortalSettings.PortalID, TabGuid))
                    {
                        HasEditPermissionsOnTabs = PortalSecurity.HasEditPermissions(m.ID);
                        if (HasEditPermissionsOnTabs)
                        {
                            TabModuleID = m.ID;
                            break;
                        }
                    }

                    // If user logged in and has Edit permission in the Tab module, reach tab management just one click
                    if ((ShowTabMan) && (HasEditPermissionsOnTabs))
                    {
                        // added by Mario Endara 2004/08/06 so PageLayout can return to this page
                        // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                        menuLink = "<a";
                        if (CssClass.Length != 0)
                            menuLink = menuLink + " class=\"" + CssClass + "\"";

                        // added mID by Mario Endara <*****@*****.**> to support security check (2004/11/09)
                        var url = HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Pages/PageLayout.aspx?PageID=") +
                                   PortalSettings.ActivePage.PageID + "&amp;mID=" + TabModuleID.ToString() +
                                   "&amp;Alias=" + PortalSettings.PortalAlias + "&amp;lang=" + PortalSettings.PortalUILanguage +
                                   "&amp;returntabid=" + PortalSettings.ActivePage.PageID;
                        menuLink = menuLink + " href='" + url + "' onclick=\"openInModal('" + url + "','" + General.GetString("HEADER_MANAGE_TAB", "Edit This Page", null) + "');return false;\");>" +
                                   General.GetString("HEADER_MANAGE_TAB", "Edit This Page", null) + "</a>";
                        list.Add(menuLink);
                    }

                    if (ShowDragNDrop && HasEditPermissionsOnTabs) {

                        menuLink = "<a";
                        if (CssClass.Length != 0)
                            menuLink = menuLink + " class=\"" + CssClass + "\"";

                        menuLink = menuLink + " href='javascript:DnD();'>" + General.GetString("DRAGNDROP", "DragNDrop", null) + "</a>";
                        list.Add(menuLink);
                    }

                    if (ShowEditProfile)
                    {
                        // 19/08/2004 Jonathan Fong
                        // www.gt.com.au
                        if ( Context.User.Identity.AuthenticationType == "LDAP" ) {
                            // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                            menuLink = "<a";
                            if ( CssClass.Length != 0 )
                                menuLink = menuLink + " class=\"" + CssClass + "\"";

                            menuLink = menuLink + " href='" +
                                       HttpUrlBuilder.BuildUrl( "~/DesktopModules/CoreModules/Register/Register.aspx") +
                                       "'>" + "Profile" + "</a>";
                            list.Add( menuLink );
                        }
                        // If user is form add edit user link
                        else if ( !( HttpContext.Current.User is WindowsPrincipal ) ) {
                            // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                            menuLink = "<a";
                            if ( CssClass.Length != 0 )
                                menuLink = menuLink + " class=\"" + CssClass + "\"";

                            menuLink = menuLink + " href='" +
                                       HttpUrlBuilder.BuildUrl( "~/DesktopModules/CoreModules/Register/Register.aspx") +
                                       "'>" +
                                       General.GetString( "HEADER_EDIT_PROFILE", "Edit profile", this ) + "</a>";
                            list.Add( menuLink );
                        }
                    }

                    // if authentication mode is Cookie, provide a logoff link
                    if (Context.User.Identity.AuthenticationType == "Forms" ||
                        Context.User.Identity.AuthenticationType == "LDAP")
                    {
                        if (ShowLogOff)
                        {
                            // Corrections when ShowSecureLogon is true. [email protected] (05/07/2004)
                            string href = HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logoff.aspx");
                            if (ShowSecureLogon && Context.Request.IsSecureConnection)
                            {
                                string auxref = Context.Request.Url.AbsoluteUri;
                                auxref = auxref.Substring(0, auxref.IndexOf(Context.Request.Url.PathAndQuery));
                                href = auxref + href;
                                href = href.Replace("https", "http");
                            }
                            // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                            menuLink = "<a";
                            if (CssClass.Length != 0)
                                menuLink = menuLink + " class=\"" + CssClass + "\"";

                            menuLink = menuLink + " href='" + href + "'>" +
                                       General.GetString("HEADER_LOGOFF", "Logoff", null) + "</a>";

                            list.Add(menuLink);
                        }
                    }
                }
                else
                {
                    if (ShowHome)
                    {
                        list.Add(homeLink);
                    }

                    if (ShowHelp)
                    {
                        list.Add(GetHelpLink());
                    }

                    // if not authenticated and ShowLogon is true, provide a logon link

                    if (ShowLogon)
                    {
                        // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                        menuLink = "<a";
                        if (CssClass.Length != 0)
                            menuLink = menuLink + " class=\"" + CssClass + "\"";

                        menuLink += string.Concat(" id=\"", this.ClientID, "_logon_link" , "\"");
                        menuLink = menuLink + " href='" + HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx") +
                                   "'>" + General.GetString("LOGON", "Logon", null) + "</a>";
                        list.Add(menuLink);
                    }

                    var allowNewRegistration = false;
                    if (PortalSettings.CustomSettings["SITESETTINGS_ALLOW_NEW_REGISTRATION"] != null)
                        if (bool.Parse(PortalSettings.CustomSettings["SITESETTINGS_ALLOW_NEW_REGISTRATION"].ToString()))
                            allowNewRegistration = true;

                    if (ShowRegister && allowNewRegistration) {

                        menuLink = "<a";
                        if (CssClass.Length != 0)
                            menuLink = menuLink + " class=\"" + CssClass + "\"";

                        menuLink = menuLink + " href='" + HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Register/Register.aspx") +
                                   "'>" + General.GetString("REGISTER", "Register", null) + "</a>";
                        list.Add(menuLink);
                    }

                    // Thierry (Tiptopweb) 5 May 2003 : Secure Logon to Secure Directory
                    if (ShowSecureLogon)
                    {
                        // Added localized support. [email protected] (05/07/2004)
                        // added Class support by Mario Endara <*****@*****.**> 2004/10/04
                        menuLink = "<a";
                        if (CssClass.Length != 0)
                            menuLink = menuLink + " class=\"" + CssClass + "\"";

                        menuLink = menuLink + " href='" + PortalSettings.PortalSecurePath + "/Logon.aspx'>" +
                                   General.GetString("LOGON", "Logon", null) + "</a>";
                        list.Add(menuLink);
                    }
                }

                LanguageSwitcher ls = new LanguageSwitcher();
                Appleseed.Framework.Web.UI.WebControls.LanguageCultureCollection lcc = Appleseed.Framework.Localization.LanguageSwitcher.GetLanguageCultureList();
                if ((ShowLanguages)  && (lcc.Count > 1))
                {
                    var mb = new StringBuilder();

                    mb.Append("<a");
                    if (CssClass.Length != 0)
                        mb.AppendFormat(" class=\"{0}\"", CssClass);

                    mb.AppendFormat("id = \"popUpLang\" >");

                    if ((ShowLangString) || (ShowLanguages)){
                        string aux = General.GetString("LANGUAGE", "Language", null);
                        mb.AppendFormat("{0}", aux);
                    }
                    if (ShowFlags){
                        CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                        string dir = HttpUrlBuilder.BuildUrl("~/aspnet_client/flags/flags_"+cultureInfo.ToString() +".gif");
                        mb.AppendFormat("<img src=\"{0}\" alt=\"\" style=\"left:13px;position:relative\"/>",dir);
                    }
                    mb.Append("</a>");
                    list.Add(mb);
                }

                innerDataSource = list;
            }
            base.DataBind();
            if (ShowLogon && DialogLogon)
            {
                //this new list control won't appear in the list, since it has no DataItem. However we need it for "holding" the Signin Control.
                var newItem = new DataListItem(this.Controls.Count, ListItemType.Item);
                this.Controls.Add(newItem);

                var logonDialogPlaceHolder = new PlaceHolder();
                newItem.Controls.Add(logonDialogPlaceHolder);

                if (_logonControl == null) //we ask this in case someone call the Databind more than once.
                {
                    _logonControl = Page.LoadControl(DialogLogonControlPath);
                    _logonControl.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
                }
                logonDialogPlaceHolder.Controls.Add(_logonControl);
            }
        }
        /// <summary>
        /// Productses the specified tab.
        /// </summary>
        /// <param name="tab">
        /// The tab.
        /// </param>
        /// <returns>
        /// The products.
        /// </returns>
        private bool products(int tab)
        {
            if (!this.AutoShopDetect)
            {
                return false;
            }

            if (!CurrentCache.Exists(Key.TabNavigationSettings(tab, "Shop")))
            {
                var PortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"];
                var exists = new ModulesDB().ExistModuleProductsInPage(tab, PortalSettings.PortalID);
                CurrentCache.Insert(Key.TabNavigationSettings(tab, "Shop"), exists);
            }

            return (bool)CurrentCache.Get(Key.TabNavigationSettings(tab, "Shop"));
        }
        public JsonResult Clone(int id, int parentId)
        {
            try
            {
                var generalModuleDef = Guid.Parse("F9F9C3A4-6E16-43B4-B540-984DDB5F1CD2");
                object[] queryargs = { generalModuleDef, PortalSettings.PortalID };

                int moduleDefinition;

                try
                {
                    moduleDefinition =
                        new rb_ModuleDefinitions().All(where: "GeneralModDefID = @0 and PortalID = @1", args: queryargs).Single().ModuleDefID;
                }
                catch(Exception e)
                {
                    // Shortcut module doesn't exist in current Portal

                    var modules = new ModulesDB();

                    modules.UpdateModuleDefinitions(
                            generalModuleDef,
                            PortalSettings.PortalID,
                            true);

                    moduleDefinition =
                        new rb_ModuleSettings().All(where: "GeneralModDefID = @0 and PortalID = @1", args: queryargs).Single().ModuleDefID;

                }

                var db = new PagesDB();

                PortalPages = db.GetPagesFlat(PortalSettings.PortalID);
                var t = new PageItem
                            {
                                Name = General.GetString("TAB_NAME", "New Page Name"),
                                ID = -1,
                                Order = 990000
                            };

                PortalPages.Add(t);

                var tabs = new PagesDB();
                t.ID = tabs.AddPage(PortalSettings.PortalID, t.Name, t.Order);

                db.UpdatePageParent(t.ID, parentId, PortalSettings.PortalID);

                OrderPages();
                //JsonResult treeData = GetTreeData();

                // Coping Modules

                var pagesModules = new rb_Modules().All(where: "TabID = @0", args: id);

                foreach (var module in pagesModules)
                {
                    var m = new ModuleItem();
                    m.Title = module.ModuleTitle;
                    m.ModuleDefID = moduleDefinition;
                    m.Order = module.ModuleOrder;

                    // save to database
                    var mod = new ModulesDB();

                    m.ID = mod.AddModule(
                        t.ID,
                        m.Order,
                        module.PaneName,
                        module.ModuleTitle,
                        m.ModuleDefID,
                        0,
                        module.AuthorizedEditRoles,
                        module.AuthorizedViewRoles,
                        module.AuthorizedAddRoles,
                        module.AuthorizedDeleteRoles,
                        module.AuthorizedPropertiesRoles,
                        module.AuthorizedMoveModuleRoles,
                        module.AuthorizedDeleteModuleRoles,
                        false,
                        PortalSecurity.GetDeleteModulePermissions(module.ModuleID),
                        false,
                        false,
                        false);

                    var settings = new rb_ModuleSettings();
                    settings.Insert(new { ModuleID = m.ID, SettingName = "LinkedModule", SettingValue = module.ModuleID });

                }

                return Json(new {pageId = t.ID});
            }
            catch(Exception e)
            {
                ErrorHandler.Publish(LogLevel.Error, e);
                Response.StatusCode = 500;
                return Json("");
            }
        }
 public JsonResult RemoveModule(int id)
 {
     string errorMessage = General.GetString("MODULE_DELETE_FAILED", "You don't have permission to delete this module", this);
     try
     {
         if (PortalSecurity.IsInRoles(PortalSecurity.GetDeleteModulePermissions(id)))
         {
             // must delete from database too
             var moddb = new ModulesDB();
             moddb.DeleteModule(id);
             return Json(new {error = false});
         }
         else
         {
             return Json(new { error = true, errorMess = errorMessage });
         }
     }
     catch (SqlException)
     {
         return Json(new { error = true, errorMess = errorMessage });
     }
 }
        public JsonResult edit(int id)
        {
            ModulesDB modules = new ModulesDB();
            Guid TabGuid = new Guid("{1C575D94-70FC-4A83-80C3-2087F726CBB3}");
            int TabModuleID = 0;
            foreach (ModuleItem m in modules.FindModuleItemsByGuid(PortalSettings.PortalID, TabGuid)) {
                bool HasEditPermissionsOnTabs = PortalSecurity.HasEditPermissions(m.ID);
                if (HasEditPermissionsOnTabs) {
                    TabModuleID = m.ID;
                    break;
                }
            }

            string dir = HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Pages/PageLayout.aspx?PageID="+ id.ToString() +
                    "&mID=" + TabModuleID + "&Alias=" + this.PortalSettings.PortalAlias + "&returntabid=" +
                    this.PortalSettings.ActiveModule);
            return Json(new { url = dir});
        }
        /// <summary>
        /// Handles the Click event of the DeleteModuleButton control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        private void DeleteModuleButtonClick(object sender, EventArgs e)
        {
            var admin = new ModulesDB();

            // admin.DeleteModule(this.ModuleID);
            // TODO - add userEmail and useRecycler
            admin.DeleteModule(this.ModuleID);

            // Redirect to the same page to pick up changes
            this.Page.Response.Redirect(this.Page.Request.RawUrl);
        }
        /// <summary>
        /// Handles OnInit event
        /// </summary>
        /// <param name="e">
        /// An <see cref="T:System.EventArgs"></see> that contains the event data.
        /// </param>
        protected override void OnInit(EventArgs e)
        {
            var modules = new ModulesDB();

            // Calculate security defID
            if (this.Request.Params["defID"] != null)
            {
                this.defId = new Guid(this.Request.Params["defID"]);
            }

            if (this.defId.Equals(Guid.Empty))
            {
                this.ChangeInstallMode(EditMode.Installer);

                // new module definition
                this.InstallerFileName.Text = @"DesktopModules/[ModuleFolder]/install.xml";
                this.FriendlyName.Text = string.Empty;
                this.DesktopSrc.Text = string.Empty;
                this.MobileSrc.Text = string.Empty;
            }
            else
            {
                // Obtain the module definition to edit from the database
                var dr = modules.GetSingleModuleDefinition(this.defId);

                // Read in first row from database
                var friendlyName = dr.FriendlyName;
                this.FriendlyName.Text = friendlyName;
                var desktopSrc = dr.DesktopSource;
                this.DesktopSrc.Text = desktopSrc;
                this.MobileSrc.Text = dr.MobileSource;
                this.lblGUID.Text = dr.GeneralModDefID.ToString();

                if (this.DesktopSrc.Text.Contains(".aspx") || this.DesktopSrc.Text.Contains(".ascx"))
                {
                    this.ChangeInstallMode(EditMode.Manually);
                }
                else
                {
                    this.FriendlyNameMVC.Text = friendlyName;

                    this.ChangeInstallMode(EditMode.MVC);
                    var items = ModelServices.GetMVCActionModules();
                    foreach (var item in this.GetPortableAreaModules())
                    {
                        items.Add(item.Text, item.Value);
                    }

                    this.ddlAction.DataSource = items;
                    this.ddlAction.DataBind();

                    var val = this.ddlAction.Items[0].Value;
                    foreach (var item in
                        this.ddlAction.Items.Cast<ListItem>().Where(
                            item => item.Text.Contains(desktopSrc.Replace("/", "\\"))))
                    {
                        val = item.Value;
                        break;
                    }

                    this.ddlAction.SelectedValue = val;
                }
            }

            // Populate checkbox list with all portals
            // and "check" the ones already configured for this tab
            var portals = modules.GetModuleInUse(this.defId).ToArray();

            // Clear existing items in checkbox list
            this.PortalsName.Items.Clear();
            this.PortalsName.Items.AddRange(portals);

            this.btnUseInstaller.Click += this.btnUseInstaller_Click;
            this.btnDescription.Click += this.btnDescription_Click;
            this.chbMVCAction.Click += this.chbMVCAction_Click;
            this.chbPortableAreas.Click += this.chbPortableAreas_Click;
            this.selectAllButton.Click += this.selectAllButton_Click;
            this.selectNoneButton.Click += this.selectNoneButton_Click;

            base.OnInit(e);
        }
        /// <summary>
        /// Creates the portal.
        /// </summary>
        /// <param name="templateID">The template ID.</param>
        /// <param name="templateAlias">The template alias.</param>
        /// <param name="portalAlias">The portal alias.</param>
        /// <param name="portalName">Name of the portal.</param>
        /// <param name="portalPath">The portal path.</param>
        /// <returns></returns>
        private int CreatePortal(int templateID, string templateAlias, string portalAlias, string portalName,
            string portalPath)
        {
            int newPortalID;

            PortalsDB portals = new PortalsDB();
            PagesDB tabs = new PagesDB();
            ModulesDB modules = new ModulesDB();
            UsersDB users = new UsersDB();

            // create an Array to stores modules ID and GUID for finding them later
            ArrayList templateModules = new ArrayList();
            moduleTemplate module;
            // create an Array to stores tabs ID for finding them later
            ArrayList templateTabs = new ArrayList();
            tabTemplate tab;

            // Create a new portal
            newPortalID = portals.AddPortal(portalAlias, portalName, portalPath);

            // Open the connection to the PortalTemplates Database
            SqlConnection myConnection = GetConnection();
            SqlConnection my2ndConnection = GetConnection();
            SqlConnection my3rdConnection = GetConnection();
            myConnection.Open();
            my2ndConnection.Open();
            my3rdConnection.Open();

            // get module definitions and save them in the new portal
            SqlDataReader myReader = GetTemplateModuleDefinitions(templateID, myConnection);

            // Always call Read before accessing data.
            while (myReader.Read()) {
                module.id = (int)myReader["ModuleDefID"];
                module.GuidID = GetGeneralModuleDefinitionByName(myReader["FriendlyName"].ToString(), my2ndConnection);
                try {
                    // save module definitions in the new portal
                    modules.UpdateModuleDefinitions(module.GuidID, newPortalID, true);
                    // Save the modules into a list for finding them later
                    templateModules.Add(module);
                } catch {
                    // tried to add a Module thas doesn´t exists in this implementation of the portal
                }
            }

            myReader.Close();

            // TODO: Is this still valid? Admin user will be created the first time the portal is accessed
            //if (!Config.UseSingleUserBase)
            //{
            //    // TODO: multiple portals still not supported
            //    Guid userID;

            //    // Create the "admin" User for the new portal
            //    string AdminEmail = "*****@*****.**";
            //    userID = users.AddUser("admin", AdminEmail, "admin", newPortalID);

            //    // Create a new row in a many to many table (userroles)
            //    // giving the "admins" role to the "admin" user
            //    users.AddUserRole("admin", userID);
            //}

            // Get all the Tabs in the Template Portal, store IDs in a list for finding them later
            // and create the Tabs in the new Portal
            myReader = GetTabsByPortal(templateID, myConnection);

            // Always call Read before accessing data.
            while (myReader.Read()) {
                // Save the tabs into a list for finding them later
                tab.oldID = (int)myReader["PageID"];
                tab.newID =
                    tabs.AddPage(newPortalID, myReader["PageName"].ToString(),
                                 Int32.Parse(myReader["PageOrder"].ToString()));
                templateTabs.Add(tab);
            }
            myReader.Close();

            //Clear SiteMaps Cache
            AppleseedSiteMapProvider.ClearAllAppleseedSiteMapCaches();

            // now I have to get them again to set up the ParentID for each Tab
            myReader = GetTabsByPortal(templateID, myConnection);

            // Always call Read before accessing data.
            while (myReader.Read()) {
                // Find the news TabID and ParentTabID
                IEnumerator myEnumerator = templateTabs.GetEnumerator();
                int newTabID = -1;
                int newParentTabID = -1;

                while (myEnumerator.MoveNext() && (newTabID == -1 || newParentTabID == -1)) {
                    tab = (tabTemplate)myEnumerator.Current;
                    if (tab.oldID == (int)myReader["PageID"])
                        newTabID = tab.newID;
                    if (tab.oldID == Int32.Parse("0" + myReader["ParentPageID"]))
                        newParentTabID = tab.newID;
                }

                if (newParentTabID == -1)
                    newParentTabID = 0;

                // Update the Tab in the new portal
                tabs.UpdatePage(newPortalID, newTabID, newParentTabID, myReader["PageName"].ToString(),
                                Int32.Parse(myReader["PageOrder"].ToString()), myReader["AuthorizedRoles"].ToString(),
                                myReader["MobilePageName"].ToString(), (bool)myReader["ShowMobile"]);

                // Finally use GetPortalSettings to access each Tab and its Modules in the Template Portal
                // and create them in the new Portal
                SqlDataReader result;

                try {
                    result = GetPageModules(Int32.Parse(myReader["PageID"].ToString()), my2ndConnection);

                    object myValue;

                    while (result.Read()) {
                        ModuleSettings m = new ModuleSettings();
                        m.ModuleID = (int)result["ModuleID"];
                        m.ModuleDefID = (int)result["ModuleDefID"];
                        m.PageID = newTabID;
                        m.PaneName = (string)result["PaneName"];
                        m.ModuleTitle = (string)result["ModuleTitle"];

                        myValue = result["AuthorizedEditRoles"];
                        m.AuthorizedEditRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedViewRoles"];
                        m.AuthorizedViewRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedAddRoles"];
                        m.AuthorizedAddRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedDeleteRoles"];
                        m.AuthorizedDeleteRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedPropertiesRoles"];
                        m.AuthorizedPropertiesRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedMoveModuleRoles"];
                        m.AuthorizedMoveModuleRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedDeleteModuleRoles"];
                        m.AuthorizedDeleteModuleRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["AuthorizedPublishingRoles"];
                        m.AuthorizedPublishingRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["SupportWorkflow"];
                        m.SupportWorkflow = !Convert.IsDBNull(myValue) ? (bool)myValue : false;

                        myValue = result["AuthorizedApproveRoles"];
                        m.AuthorizedApproveRoles = !Convert.IsDBNull(myValue) ? (string)myValue : string.Empty;

                        myValue = result["WorkflowState"];
                        m.WorkflowStatus = !Convert.IsDBNull(myValue)
                                               ? (WorkflowState)(0 + (byte)myValue)
                                               : WorkflowState.Original;

                        try {
                            myValue = result["SupportCollapsable"];
                        } catch {
                            myValue = DBNull.Value;
                        }
                        m.SupportCollapsable = DBNull.Value != myValue ? (bool)myValue : false;

                        try {
                            myValue = result["ShowEveryWhere"];
                        } catch {
                            myValue = DBNull.Value;
                        }
                        m.ShowEveryWhere = DBNull.Value != myValue ? (bool)myValue : false;

                        m.CacheTime = int.Parse(result["CacheTime"].ToString());
                        m.ModuleOrder = int.Parse(result["ModuleOrder"].ToString());

                        myValue = result["ShowMobile"];
                        m.ShowMobile = !Convert.IsDBNull(myValue) ? (bool)myValue : false;

                        // Find the new ModuleDefID assigned to the module in the new portal
                        myEnumerator = templateModules.GetEnumerator();
                        int newModuleDefID = 0;

                        while (myEnumerator.MoveNext() && newModuleDefID == 0) {
                            module = (moduleTemplate)myEnumerator.Current;
                            if (module.id == m.ModuleDefID)
                                newModuleDefID = modules.GetModuleDefinitionByGuid(newPortalID, module.GuidID);
                        }

                        if (newModuleDefID > 0) {
                            // add the module to the new tab
                            int newModuleID = modules.AddModule(newTabID, m.ModuleOrder, m.PaneName, m.ModuleTitle,
                                                                newModuleDefID, m.CacheTime, m.AuthorizedEditRoles,
                                                                m.AuthorizedViewRoles,
                                                                m.AuthorizedAddRoles, m.AuthorizedDeleteRoles,
                                                                m.AuthorizedPropertiesRoles,
                                                                m.AuthorizedMoveModuleRoles,
                                                                m.AuthorizedDeleteModuleRoles,
                                                                m.ShowMobile, m.AuthorizedPublishingRoles,
                                                                m.SupportWorkflow,
                                                                m.ShowEveryWhere, m.SupportCollapsable);
                            // At the end, get all ModuleSettings and save them in the new module
                            SqlDataReader dr = GetModuleSettings(m.ModuleID, my3rdConnection);

                            while (dr.Read()) {
                                Framework.Site.Configuration.ModuleSettings.UpdateModuleSetting(newModuleID, dr["SettingName"].ToString(),
                                                                   dr["SettingValue"].ToString());
                            }
                            dr.Close();
                        }
                    }

                    result.Close();
                } catch {
                    // Error? ignore Tab ...
                }
            }
            myReader.Close();

            // Set the CustomSettings of the New Portal based in the Template Portal
            myReader = GetPortalCustomSettings(templateID, myConnection);

            // Always call Read before accessing data.
            while (myReader.Read()) {
                PortalSettings.UpdatePortalSetting(newPortalID, myReader["SettingName"].ToString(),
                                                   myReader["SettingValue"].ToString());
            }

            myReader.Close();

            // close the conections
            myConnection.Close();
            myConnection.Dispose();
            my2ndConnection.Close();
            my2ndConnection.Dispose();
            my3rdConnection.Close();
            my3rdConnection.Dispose();

            // Create paths
            portals.CreatePortalPath(portalPath);

            return newPortalID;
        }
        /// <summary>
        /// OnUpdate installs or refresh module definition on db
        /// </summary>
        /// <param name="e">
        /// The <see cref="T:System.EventArgs"/> instance containing the event data.
        /// </param>
        protected override void OnUpdate(EventArgs e)
        {
            if (this.Page.IsValid)
            {
                try
                {
                    if (this.chbMVCAction.Visible || this.chbPortableAreas.Visible)
                    {
                        // Es un módulo clásico
                        if (!this.btnUseInstaller.Visible)
                        {
                            ModuleInstall.InstallGroup(
                                this.Server.MapPath(Path.ApplicationRoot + "/" + this.InstallerFileName.Text),
                                this.lblGUID.Text == string.Empty);
                        }
                        else
                        {
                            ModuleInstall.Install(
                                this.FriendlyName.Text,
                                this.DesktopSrc.Text,
                                this.MobileSrc.Text,
                                this.lblGUID.Text == string.Empty);
                        }

                        // Update the module definition
                    }
                    else
                    {
                        // Es una acción MVC
                        var path = this.ddlAction.SelectedValue;

                        path = path.Substring(path.IndexOf("Areas"));
                        path = path.Replace("\\", "/");
                        path = path.Replace(".aspx", string.Empty);
                        path = path.Replace(".ascx", string.Empty);

                        var name = this.FriendlyNameMVC.Text;

                        this.defId = ModelServices.AddMVCActionModule(name, path);
                    }

                    var modules = new ModulesDB();

                    for (var i = 0; i < this.PortalsName.Items.Count; i++)
                    {
                        modules.UpdateModuleDefinitions(
                            this.defId,
                            Convert.ToInt32(this.PortalsName.Items[i].Value),
                            this.PortalsName.Items[i].Selected);
                    }

                    // Redirect back to the portal admin page
                    this.RedirectBackToReferringPage();
                }
                catch (ThreadAbortException)
                {
                    // normal with redirect
                }
                catch (Exception ex)
                {
                    this.lblErrorDetail.Text =
                        string.Format("{0}<br />", General.GetString("MODULE_DEFINITIONS_INSTALLING", "An error occurred installing.", this));
                    this.lblErrorDetail.Text += ex.Message + "<br />";
                    if (!this.btnUseInstaller.Visible)
                    {
                        this.lblErrorDetail.Text += string.Format(
                            " Installer: {0}",
                            this.Server.MapPath(
                                string.Format("{0}/{1}", Path.ApplicationRoot, this.InstallerFileName.Text)));
                    }
                    else
                    {
                        this.lblErrorDetail.Text += string.Format(
                            " Module: '{0}' - Source: '{1}' - Mobile: '{2}'",
                            this.FriendlyName.Text,
                            this.DesktopSrc.Text,
                            this.MobileSrc.Text);
                    }

                    this.lblErrorDetail.Visible = true;

                    ErrorHandler.Publish(LogLevel.Error, this.lblErrorDetail.Text, ex);
                }
            }
        }
 /// <summary>
 /// Gives the friendly name.
 /// </summary>
 /// <param name="guid">
 /// The GUID.
 /// </param>
 /// <returns>
 /// The friendly name
 /// </returns>
 private static string GiveMeFriendlyName(Guid guid)
 {
     var auxDr = new ModulesDB().GetSingleModuleDefinition(guid);
     return auxDr.FriendlyName;
 }
        /// <summary>
        /// The DeleteBtn_Click server event handler on this page is
        ///   used to delete a portal module from the page
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="T:System.Web.UI.ImageClickEventArgs"/> instance containing the event data.
        /// </param>
        /// <remarks>
        /// </remarks>
        protected void DeleteBtn_Click(object sender, ImageClickEventArgs e)
        {
            var pane = ((ImageButton)sender).CommandArgument;
            var _listbox = (ListBox)this.Page.FindControl(pane);
            if (_listbox == null)
            {
                _listbox = (ListBox)this.Page.Master.FindControl("Content").FindControl(pane);
            }

            var modules = this.GetModules(pane);

            if (_listbox.SelectedIndex != -1)
            {
                var m = (ModuleItem)modules[_listbox.SelectedIndex];
                if (m.ID > -1)
                {
                    // [email protected] (20/08/2004) Add role control for delete module
                    if (PortalSecurity.IsInRoles(PortalSecurity.GetDeleteModulePermissions(m.ID)))
                    {
                        // must delete from database too
                        var moddb = new ModulesDB();

                        // TODO add userEmail and useRecycler
                        moddb.DeleteModule(m.ID);
                    }
                    else
                    {
                        this.msgError.Visible = true;
                        return;
                    }
                }
            }

            // Redirect to the same page to pick up changes
            this.Response.Redirect(this.Request.RawUrl);
        }
        public JsonResult RightLeft_Click(string sourcePane, string targetPane, string pageId, string selectedIndex)
        {
            // get source arraylist
            var sourceList = this.GetModules(sourcePane, Int32.Parse(pageId));

            var index = Int32.Parse(selectedIndex);
            // get a reference to the module to move
            // and assign a high order number to send it to the end of the target list
            var m = (ModuleItem)sourceList[index];

            if (PortalSecurity.IsInRoles(PortalSecurity.GetMoveModulePermissions(m.ID)))
            {
                // add it to the database
                var admin = new ModulesDB();
                admin.UpdateModuleOrder(m.ID, 99, targetPane);

                // delete it from the source list
                sourceList.RemoveAt(index);

                // reorder the modules in the source pane
                sourceList = this.GetModules(sourcePane, Int32.Parse(pageId));
                var list = this.OrderModules(sourceList);

                // resave the order
                foreach (ModuleItem item in sourceList)
                {
                    admin.UpdateModuleOrder(item.ID, item.Order, sourcePane);
                }

                // reorder the modules in the target pane
                var targetList = this.GetModules(targetPane, Int32.Parse(pageId));
                var list2 = this.OrderModules(targetList);

                // resave the order
                foreach (ModuleItem item in targetList)
                {
                    admin.UpdateModuleOrder(item.ID, item.Order, targetPane);
                }

                StringBuilder ls = new StringBuilder();
                foreach (ModuleItem md in list)
                {
                    ls.AppendFormat("<option value=\"{0}\">{1}</option>", md.ID, md.Title);
                }

                StringBuilder sb = new StringBuilder();
                foreach (ModuleItem md in list2)
                {
                    sb.AppendFormat("<option value=\"{0}\">{1}</option>", md.ID, md.Title);
                }

                return Json(new { error = false, source = ls.ToString(), target = sb.ToString() });

            }
            else
            {
                return Json(new { error = true });
            }
        }
        /// <summary>
        /// The UpDown_Click server event handler on this page is
        ///   used to move a portal module up or down on a tab's layout pane
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="T:System.Web.UI.ImageClickEventArgs"/> instance containing the event data.
        /// </param>
        /// <remarks>
        /// </remarks>
        protected void UpDown_Click(object sender, ImageClickEventArgs e)
        {
            var cmd = ((ImageButton)sender).CommandName;
            var pane = ((ImageButton)sender).CommandArgument;
            var _listbox = (ListBox)this.Page.FindControl(pane);
            if (_listbox == null)
            {
                _listbox = (ListBox)this.Page.Master.FindControl("Content").FindControl(pane);
            }

            var modules = this.GetModules(pane);

            if (_listbox.SelectedIndex != -1)
            {
                int delta;
                var selection = -1;

                // Determine the delta to apply in the order number for the module
                // within the list.  +3 moves down one item; -3 moves up one item
                if (cmd == "down")
                {
                    delta = 3;
                    if (_listbox.SelectedIndex < _listbox.Items.Count - 1)
                    {
                        selection = _listbox.SelectedIndex + 1;
                    }
                }
                else
                {
                    delta = -3;
                    if (_listbox.SelectedIndex > 0)
                    {
                        selection = _listbox.SelectedIndex - 1;
                    }
                }

                ModuleItem m;
                m = (ModuleItem)modules[_listbox.SelectedIndex];

                if (PortalSecurity.IsInRoles(PortalSecurity.GetMoveModulePermissions(m.ID)))
                {
                    m.Order += delta;

                    // reorder the modules in the content pane
                    this.OrderModules(modules);

                    // resave the order
                    var admin = new ModulesDB();
                    foreach (ModuleItem item in modules)
                    {
                        admin.UpdateModuleOrder(item.ID, item.Order, pane);
                    }

                    // Redirect to the same page to pick up changes
                    this.Response.Redirect(this.AppendModuleID(this.Request.RawUrl, m.ID));
                }
                else
                {
                    this.msgError.Visible = true;
                    return;
                }
            }
        }
        /// <summary>
        /// The ApplyChanges_Click server event handler on this page is used
        ///   to save the module settings into the portal configuration system.
        /// </summary>
        /// <param name="e">
        /// </param>
        protected override void OnUpdate(EventArgs e)
        {
            base.OnUpdate(e);
            var useNTLM = HttpContext.Current.User is WindowsPrincipal;

            // add by Jonathan Fong 22/07/2004 to support LDAP
            // jes1111 - useNTLM |= ConfigurationSettings.AppSettings["LDAPLogin"] != null ? true : false;
            useNTLM |= Config.LDAPLogin.Length != 0 ? true : false;

            var m = this.GetModule();
            if (m == null)
            {
                return;
            }

            // Construct Authorized User Roles string

            // Edit Roles
            var editRoles = this.authEditRoles.Items.Cast<ListItem>().Where(editItem => editItem.Selected).Aggregate(string.Empty, (current, editItem) => current + editItem.Text + ";");

            // View Roles
            var viewRoles = this.authViewRoles.Items.Cast<ListItem>().Where(viewItem => viewItem.Selected).Aggregate(string.Empty, (current, viewItem) => current + viewItem.Text + ";");

            // Add Roles
            var addRoles = this.authAddRoles.Items.Cast<ListItem>().Where(addItem => addItem.Selected).Aggregate(string.Empty, (current, addItem) => current + addItem.Text + ";");

            // Delete Roles
            var deleteRoles = this.authDeleteRoles.Items.Cast<ListItem>().Where(deleteItem => deleteItem.Selected).Aggregate(string.Empty, (current, deleteItem) => current + deleteItem.Text + ";");

            // Move Module Roles
            var moveModuleRoles = this.authMoveModuleRoles.Items.Cast<ListItem>().Where(li => li.Selected).Aggregate(string.Empty, (current, li) => current + (li.Text + ";"));

            // Delete Module Roles
            var deleteModuleRoles = this.authDeleteModuleRoles.Items.Cast<ListItem>().Where(li => li.Selected).Aggregate(string.Empty, (current, li) => current + (li.Text + ";"));

            // Properties Roles
            var propertiesRoles = this.authPropertiesRoles.Items.Cast<ListItem>().Where(propertiesItem => propertiesItem.Selected).Aggregate(string.Empty, (current, propertiesItem) => current + propertiesItem.Text + ";");

            // Change by [email protected]
            // Date: 6/2/2003
            // Publishing Roles
            var publishingRoles = this.authPublishingRoles.Items.Cast<ListItem>().Where(propertiesItem => propertiesItem.Selected).Aggregate(string.Empty, (current, propertiesItem) => current + propertiesItem.Text + ";");

            // End Change [email protected]
            // Change by [email protected]
            // Date: 27/2/2003
            var approvalRoles = this.authApproveRoles.Items.Cast<ListItem>().Where(propertiesItem => propertiesItem.Selected).Aggregate(string.Empty, (current, propertiesItem) => current + propertiesItem.Text + ";");

            // End Change [email protected]

            // update module
            var modules = new ModulesDB();
            modules.UpdateModule(
                Int32.Parse(this.tabDropDownList.SelectedItem.Value),
                this.ModuleID,
                m.ModuleOrder,
                m.PaneName,
                this.moduleTitle.Text,
                Int32.Parse(this.cacheTime.Text),
                editRoles,
                viewRoles,
                addRoles,
                deleteRoles,
                propertiesRoles,
                moveModuleRoles,
                deleteModuleRoles,
                this.ShowMobile.Checked,
                publishingRoles,
                this.enableWorkflowSupport.Checked,
                approvalRoles,
                this.showEveryWhere.Checked,
                this.allowCollapsable.Checked);

            if (Request.QueryString.GetValues("ModalChangeMaster") != null) {
                if(Request.QueryString.GetValues("camefromEditPage") != null)
                    this.RedirectBackToReferringPage();
                else
                    Response.Write("<script type=\"text/javascript\">window.parent.location = window.parent.location.href;</script>");
            }
        }
        protected void AddModuleToPane_Click(object sender, EventArgs e)
        {
            // All new modules go to the end of the content pane
            var m = new ModuleItem();
            m.Title = this.moduleTitle.Text;
            m.ModuleDefID = Int32.Parse(this.moduleType.SelectedItem.Value);
            m.Order = 999;

            // save to database
            var mod = new ModulesDB();

            // Change by [email protected]
            // Date: 6/2/2003
            // Original:             m.ID = _mod.AddModule(tabID, m.Order, "ContentPane", m.Title, m.ModuleDefID, 0, "Admins", "All Users", "Admins", "Admins", "Admins", false);
            // Changed by Mario Endara <*****@*****.**> (2004/11/09)
            // The new module inherits security from Pages module (current ModuleID)
            // so who can edit the tab properties/content can edit the module properties/content (except view that remains =)
            m.ID = mod.AddModule(
                this.PageID,
                m.Order,
                this.paneLocation.SelectedItem.Value,
                m.Title,
                m.ModuleDefID,
                0,
                PortalSecurity.GetEditPermissions(this.ModuleID),
                this.viewPermissions.SelectedItem.Value,
                PortalSecurity.GetAddPermissions(this.ModuleID),
                PortalSecurity.GetDeletePermissions(this.ModuleID),
                PortalSecurity.GetPropertiesPermissions(this.ModuleID),
                PortalSecurity.GetMoveModulePermissions(this.ModuleID),
                PortalSecurity.GetDeleteModulePermissions(this.ModuleID),
                false,
                PortalSecurity.GetPublishPermissions(this.ModuleID),
                false,
                false,
                false);

            // End Change [email protected]

            // reload the portalSettings from the database
            this.Context.Items["PortalSettings"] = PortalSettings.GetPortalSettings(this.PageID, this.PortalSettings.PortalAlias);
            this.PortalSettings = (PortalSettings)this.Context.Items["PortalSettings"];

            // reorder the modules in the content pane
            var modules = this.GetModules("ContentPane");
            this.OrderModules(modules);

            // resave the order
            foreach (ModuleItem item in modules)
            {
                mod.UpdateModuleOrder(item.ID, item.Order, "ContentPane");
            }

            // Redirect to the same page to pick up changes
            this.Response.Redirect(this.AppendModuleID(this.Request.RawUrl, m.ID));
        }
        public JsonResult UpDown_Click(string cmd, string pane, string pageId, string selectedIndex, string length)
        {
            var modules = this.GetModules(pane, Int32.Parse(pageId));
            int delta;
            var selection = -1;
            var index = Int32.Parse(selectedIndex);

            // Determine the delta to apply in the order number for the module
            // within the list.  +3 moves down one item; -3 moves up one item
            if (cmd == "down")
            {
                delta = 3;
                if (index < Int32.Parse(length) - 1)
                {
                    selection = index + 1;
                }
            }
            else
            {
                delta = -3;
                if (index > 0)
                {
                    selection = index - 1;
                }
            }

            ModuleItem m;
            m = (ModuleItem)modules[index];

            if (PortalSecurity.IsInRoles(PortalSecurity.GetMoveModulePermissions(m.ID)))
            {
                m.Order += delta;

                // reorder the modules in the content pane
                var list = this.OrderModules(modules);

                // resave the order
                var admin = new ModulesDB();
                foreach (ModuleItem item in modules)
                {
                    admin.UpdateModuleOrder(item.ID, item.Order, pane);
                }

                StringBuilder ls = new StringBuilder();
                foreach (ModuleItem md in list)
                {
                    ls.AppendFormat("<option value=\"{0}\">{1}</option>", md.ID, md.Title);
                }
                return Json(new { value = ls.ToString() });

            }
            else
            {
                return Json(new { value = "error" });
            }
        }
        /// <summary>
        /// Installs module
        /// </summary>
        /// <param name="friendlyName">
        /// Name of the friendly.
        /// </param>
        /// <param name="desktopSource">
        /// The desktop source.
        /// </param>
        /// <param name="mobileSource">
        /// The mobile source.
        /// </param>
        /// <param name="install">
        /// if set to <c>true</c> [install].
        /// </param>
        public static void Install(string friendlyName, string desktopSource, string mobileSource, bool install)
        {
            ErrorHandler.Publish(
                LogLevel.Info, string.Format("Installing DesktopModule '{0}' from '{1}'", friendlyName, desktopSource));
            if (!string.IsNullOrEmpty(mobileSource))
            {
                ErrorHandler.Publish(
                    LogLevel.Info, string.Format("Installing MobileModule '{0}' from '{1}'", friendlyName, mobileSource));
            }

            var controlFullPath = Path.ApplicationRoot + "/" + desktopSource;

            // if ascx User Control based Module-> Instantiate the module
            if (controlFullPath.ToLowerInvariant().Trim().EndsWith(".ascx"))
            {
                var page = new Page();

                var control = page.LoadControl(controlFullPath);
                if (!(control is PortalModuleControl))
                {
                    throw new Exception(string.Format("Module '{0}' is not a PortalModule Control", control.GetType().FullName));
                }

                var portalModule = (PortalModuleControl)control;

                // Check mobile module
                if (!string.IsNullOrEmpty(mobileSource) && mobileSource.ToLower().EndsWith(".ascx"))
                {
                    // TODO: Check mobile module
                    // TODO: MobilePortalModuleControl mobileModule = (MobilePortalModuleControl) page.LoadControl(Appleseed.Framework.Settings.Path.ApplicationRoot + "/" + mobileSource);
                    if (!File.Exists(HttpContext.Current.Server.MapPath(Path.ApplicationRoot + "/" + mobileSource)))
                    {
                        throw new FileNotFoundException("Mobile Control not found");
                    }
                }

                // Get Module ID
                var defId = portalModule.GuidID;

                var baseType = portalModule.GetType().BaseType;

                // Get Assembly name
                if (baseType != null)
                {
                    var assemblyName = baseType.Assembly.CodeBase;
                    assemblyName = assemblyName.Substring(assemblyName.LastIndexOf('/') + 1); // Get name only

                    // Get Module Class name
                    var className = baseType.FullName;

                    // Now we add the definition to module list
                    var modules = new ModulesDB();

                    if (install)
                    {
                        // Install as new module

                        // Call Install
                        try
                        {
                            ErrorHandler.Publish(LogLevel.Debug, string.Format("Installing '{0}' as new module.", friendlyName));
                            portalModule.Install(null);
                        }
                        catch (Exception ex)
                        {
                            // Error occurred
                            portalModule.Rollback(null);

                            // Re-throw exception
                            throw new Exception(string.Format("Exception occurred installing '{0}'!", portalModule.GuidID), ex);
                        }

                        try
                        {
                            // Add a new module definition to the database
                            modules.AddGeneralModuleDefinitions(
                                defId,
                                friendlyName,
                                desktopSource,
                                mobileSource,
                                assemblyName,
                                className,
                                portalModule.AdminModule,
                                portalModule.Searchable);
                        }
                        catch (Exception ex)
                        {
                            // Re-throw exception
                            throw new Exception(string.Format("AddGeneralModuleDefinitions Exception '{0}'!", portalModule.GuidID), ex);
                        }

                        // All is fine: we can call Commit
                        portalModule.Commit(null);
                    }
                    else
                    {
                        // Update the general module definition
                        try
                        {
                            ErrorHandler.Publish(LogLevel.Debug, string.Format("Updating '{0}' as new module.", friendlyName));
                            modules.UpdateGeneralModuleDefinitions(
                                defId,
                                friendlyName,
                                desktopSource,
                                mobileSource,
                                assemblyName,
                                className,
                                portalModule.AdminModule,
                                portalModule.Searchable);
                        }
                        catch (Exception ex)
                        {
                            // Re-throw exception
                            throw new Exception(
                                string.Format("UpdateGeneralModuleDefinitions Exception '{0}'!", portalModule.GuidID), ex);
                        }
                    }

                    // Update the module definition - install for portal 0
                    modules.UpdateModuleDefinitions(defId, 0, true);
                }
            }
        }
        /// <summary>
        /// The RightLeftClick server event handler on this page is
        ///   used to move a portal module between layout panes on
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        private void RightLeftClick(object sender, EventArgs e)
        {
            var sourcePane = ((ModuleButton)sender).Attributes["sourcepane"];
            var targetPane = ((ModuleButton)sender).Attributes["targetpane"];

            // add it to the database
            // tiptopweb : OriginalModuleID to have it work with shortcut module
            var admin = new ModulesDB();
            admin.UpdateModuleOrder(this.OriginalModuleID, 99, targetPane);

            // reload the PortalSettings from the database
            HttpContext.Current.Items["PortalSettings"] = PortalSettings.GetPortalSettings(
                PageID, PortalSettings.PortalAlias);
            this.Page.PortalSettings = (PortalSettings)this.Context.Items["PortalSettings"];

            // get source array list
            var sourceList = this.GetModules(sourcePane);

            // reorder the modules in the source pane
            OrderModules(sourceList);

            // resave the order
            foreach (var item in sourceList)
            {
                admin.UpdateModuleOrder(item.ID, item.Order, sourcePane);
            }

            // reorder the modules in the target pane
            var targetList = this.GetModules(targetPane);
            OrderModules(targetList);

            // resave the order
            foreach (var item in targetList)
            {
                admin.UpdateModuleOrder(item.ID, item.Order, targetPane);
            }

            // Redirect to the same page to pick up changes
            this.Page.Response.Redirect(AppendModuleId(this.Page.Request.RawUrl, this.ModuleID));
        }