dock state using cookies and checkboxlist

2 posts, 0 answers
  1. davoud nayebi
    davoud nayebi avatar
    3 posts
    Member since:
    Jan 2010

    Posted 21 Jun 2011 Link to this post

    When i move more docks, after the 3rd dock i get an error 500.

    using
    System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Telerik.Web.UI;
    using System.Data.SqlClient;
    using System.Text;
    using System.Collections;
    using System.Configuration;
     
     
    public partial class mods_arrange : System.Web.UI.UserControl
    {
        private int _userID = 1;
        private SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        private List<DockState> CurrentDockStates
        {
            get
            {
                //Get saved state string from the database - set it to dockState variable for example
                string dockStatesFromDB = "";
                if (Request.Cookies["landingStates_V"] != null)
                {
                    dockStatesFromDB = Request.Cookies["landingStates_V"].Value;
                }
                else
                {
                    _conn.Open();
                    SqlCommand command = new SqlCommand("select State from landing_States where id='" + _userID + "' ", _conn);
                    dockStatesFromDB = command.ExecuteScalar().ToString();
                    _conn.Close();
                }
                List<DockState> _currentDockStates = new List<DockState>();
                string[] stringStates = dockStatesFromDB.Split('|');
                foreach (string stringState in stringStates)
                {
                    if (stringState.Trim() != string.Empty)
                    {
                        _currentDockStates.Add(DockState.Deserialize(stringState));
                    }
                }
                return _currentDockStates;
            }
        }
     
        protected void Page_Load(object sender, EventArgs e)
        {
            //RadAjaxManager manager = RadAjaxManager.GetCurrent(Page);
            //manager.ClientEvents.OnRequestStart = "RequestStart";
            //manager.ClientEvents.OnResponseEnd = "ResponseEnd";
     
            if (!IsPostBack)
            {
                DropDownZone.DataBind();
     
            }
        }
     
        public ArrayList GetZones()
        {
            ArrayList zones = new ArrayList();
            zones.Add(RadDockZone1);
            zones.Add(RadDockZone2);
            zones.Add(RadDockZone3);
            return zones;
        }
     
        protected void Page_Init(object sender, EventArgs e)
        {
     
            //Recreate the docks in order to ensure their proper operation
            for (int i = 0; i < CurrentDockStates.Count; i++)
            {
                if (CurrentDockStates[i].Closed == false)
                {
                    RadDock dock = CreateRadDockFromState(CurrentDockStates[i]);
     
                    //We will just add the RadDock control to the RadDockLayout.
                    // You could use any other control for that purpose, just ensure
                    // that it is inside the RadDockLayout control.
                    // The RadDockLayout control will automatically move the RadDock
                    // controls to their corresponding zone in the LoadDockLayout
                    // event (see below).
                    RadDockLayout1.Controls.Add(dock);
     
                    //We want to save the dock state every time a dock is moved.
                    CreateSaveStateTrigger(dock);
                    //Load the selected widget
                    LoadWidget(dock);
     
                }
            }
            loadCheckboxes();
        }
        private void loadCheckboxes()
        {
            ListItem i1 = new ListItem("News", "~/Controls/News.ascx");
            ListItem i2 = new ListItem("Events", "~/Controls/Events.ascx");
            ListItem i3 = new ListItem("Languages", "~/Controls/Languages.ascx");
            ListItem i4 = new ListItem("Market", "~/Controls/MarketIndex.ascx");
            ListItem i5 = new ListItem("VC", "~/Controls/VC.ascx");
            ListItem i6 = new ListItem("DVD", "~/Controls/DVD.ascx");
            ListItem i7 = new ListItem("PIF", "~/Controls/PIF.ascx");
            CheckBoxList1.Items.Add(i1);
            CheckBoxList1.Items.Add(i2);
            CheckBoxList1.Items.Add(i3);
            CheckBoxList1.Items.Add(i4);
            CheckBoxList1.Items.Add(i5);
            CheckBoxList1.Items.Add(i6);
            CheckBoxList1.Items.Add(i6);
     
            LcookieCheck();
        }
     
        protected void RadDockLayout1_LoadDockLayout(object sender, DockLayoutEventArgs e)
        {
            //Populate the event args with the state information. The RadDockLayout control
            // will automatically move the docks according that information.
            //if (!IsPostBack)
            //{
            //    foreach (DockState state in CurrentDockStates)
            //    {
            //        e.Positions[state.UniqueName] = state.DockZoneID;
            //        e.Indices[state.UniqueName] = state.Index;
            //    }
            //}
            if (!Page.IsPostBack)
            {
                string dockStatesFromCookie = "";
     
                HttpCookie cookieStates = Request.Cookies["dockState"];
     
                if (cookieStates != null)
                {
                    dockStatesFromCookie = cookieStates.Value;
                    string[] stringStates = dockStatesFromCookie.Split('|');
     
                    Hashtable states = new Hashtable();
                    for (int i = 0; i < stringStates.Length - 1; i++)
                    {
                        string[] currentState = stringStates[i].Split('#');
                        string uniqueName = currentState[0];
                        string state = currentState[1];
                        states.Add(uniqueName, state);
                    }
     
                    foreach (RadDock dock in RadDockLayout1.RegisteredDocks)
                    {
                        string uniqueName = dock.UniqueName;
                        DockState state = DockState.Deserialize(states[uniqueName].ToString());
                        dock.ApplyState(state);
                    }
                }
            }
        }
     
        protected void RadDockLayout1_SaveDockLayout(object sender, DockLayoutEventArgs e)
        {
            List<DockState> stateList = RadDockLayout1.GetRegisteredDocksState();
            StringBuilder serializedList = new StringBuilder();
            int i = 0;
     
            while (i < stateList.Count)
            {
                serializedList.Append(stateList[i].ToString());
                serializedList.Append("|");
                i++;
            }
     
            string dockState = serializedList.ToString();
            if (dockState.Trim() != String.Empty)
            {
                if (Request.Cookies["landingStates_V"] != null)
                {
                    Response.Cookies["landingStates_V"].Value = dockState;
                }
                else
                {
                    Response.Cookies["landingStates_V"].Value = dockState;
                    Response.Cookies["landingStates_V"].Expires = DateTime.Now.AddDays(5);
                }
                _conn.Open();
                //SqlCommand command = new SqlCommand(String.Format("update landing_States set State='{0}' where id='" + _userID + "'", dockState), _conn);
                //command.ExecuteNonQuery();  //update Dbase
                _conn.Close();
            }
     
        }
     
        private RadDock CreateRadDockFromState(DockState state)
        {
            RadDock dock = new RadDock();
            dock.DockMode = DockMode.Docked;
            dock.ID = string.Format("RadDock{0}", state.UniqueName);
            dock.ApplyState(state);
            //by aresh
            dock.DefaultCommands = Telerik.Web.UI.Dock.DefaultCommands.None;
            dock.DockMode = DockMode.Docked;
            dock.CssClass = "vbox" + state.Title.Replace(' ', 'a');
     
            DockToggleCommand cmd = new DockToggleCommand();
            cmd.OnClientCommand = "OnClientCommand" + state.Title.Replace(' ', 'a');
            cmd.Text = "Edit";
            cmd.CssClass = "rdEdit";
            cmd.AutoPostBack = false;
     
     
            DockCloseCommand cmdclose = new DockCloseCommand();
            cmdclose.AutoPostBack = false;//true;
     
            DockExpandCollapseCommand cmdminmax = new DockExpandCollapseCommand();
            cmdminmax.AutoPostBack = false;
     
     
            dock.Commands.Add(cmdclose);
            dock.Commands.Add(cmdminmax);
            //dock.Commands.Add(cmd);
     
            return dock;
        }
        private RadDock CreateRadDock(String name)
        {
            int docksCount = CurrentDockStates.Count;
     
            RadDock dock = new RadDock();
            dock.DockMode = DockMode.Docked;
            dock.UniqueName = Guid.NewGuid().ToString().Replace(' ', 'a');
            dock.ID = string.Format("RadDock{0}", dock.UniqueName);
            dock.Title = name.Replace('_', ' ');
            dock.Width = Unit.Pixel(300);
            //by aresh
            dock.DefaultCommands = Telerik.Web.UI.Dock.DefaultCommands.None;
            dock.DockMode = DockMode.Docked;
            dock.CssClass = "vbox" + name.Replace(' ', 'a');
     
            DockToggleCommand cmd = new DockToggleCommand();
            cmd.OnClientCommand = "OnClientCommand" + name.Replace(' ', 'a'); ;
            cmd.Text = "Edit";
            cmd.CssClass = "rdEdit";
            cmd.AutoPostBack = false;
     
     
            DockCloseCommand cmdclose = new DockCloseCommand();
            cmdclose.AutoPostBack = false;//true;
     
            DockExpandCollapseCommand cmdminmax = new DockExpandCollapseCommand();
            cmdminmax.AutoPostBack = false;
     
     
            dock.Commands.Add(cmdclose);
            dock.Commands.Add(cmdminmax);
            //dock.Commands.Add(cmd);
     
            return dock;
        }
        private void CreateSaveStateTrigger(RadDock dock)
        {
            //Ensure that the RadDock control will initiate postback
            // when its position changes on the client or any of the commands is clicked.
            //Using the trigger we will "ajaxify" that postback.
            dock.AutoPostBack = true;
            dock.CommandsAutoPostBack = false;
     
            AjaxUpdatedControl updatedControl = new AjaxUpdatedControl();
            updatedControl.ControlID = "Panel1";
     
            AjaxSetting setting1 = new AjaxSetting(dock.ID);
            setting1.EventName = "DockPositionChanged";
            setting1.UpdatedControls.Add(updatedControl);
     
            RadAjaxManagerArrange.AjaxSettings.Add(setting1);
        }
        private void LoadWidget(RadDock dock)
        {
            if (string.IsNullOrEmpty(dock.Tag))
            {
                return;
            }
            Control widget = LoadControl(dock.Tag);
            dock.ContentContainer.Controls.Add(widget);
        }
     
     
        protected void ButtonAddDock_Click(object sender, EventArgs e)
        {
            //Load the selected widget in the RadDock control
            foreach (ListItem con in CheckBoxList1.Items)
            {
                if (con.Selected == true)
                {
                    WcookieCheck(con.Value, con.Text);
                    RadDock dock = CreateRadDock(con.Text);
                    //find the target zone and add the new dock there
                    RadDockZone dz = (RadDockZone)FindControl(DropDownZone.SelectedItem.Text);
                    dz.Controls.Add(dock);
     
                    CreateSaveStateTrigger(dock);
     
                    dock.Tag = con.Value;
                    LoadWidget(dock);
     
                    //Register a script to move dock to the last place in the RadDockZone
                    //The zone.dock(dock,index) client-side method is used
                    ScriptManager.RegisterStartupScript(this,
                        this.GetType(),
                        "MoveDock",
                    string.Format(@"function _moveDock() {{
                                Sys.Application.remove_load(_moveDock);
                                $find('{1}').dock($find('{0}'),{2});
                                }};
                                Sys.Application.add_load(_moveDock);", dock.ClientID, DropDownZone.SelectedValue, dz.Docks.Count),
                    true);
                }
            }Response.Redirect("/default.aspx");
     
        }
        protected void ButtonPostBack_Click(object sender, EventArgs e)
        {
            if (Request.Cookies["landingChecks_V"] != null)
            {
                HttpCookie myCookie = new HttpCookie("landingChecks_V");
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);
            }
            Response.Redirect("default.aspx");
        }
     
     
        private void WcookieCheck(string val, string txt)
        {
            HttpCookie cookie = Request.Cookies["landingChecks_V"];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddYears(-30);
                Response.Cookies.Remove("landingChecks_V");
     
                HttpCookie Newcookie = new HttpCookie("landingChecks_V");
                Newcookie.Expires = DateTime.Now.AddDays(5);
                Newcookie.Values.Add(val, txt);
                Response.Cookies.Add(Newcookie);
     
                cookie.Values.Add(val, txt);
                Response.Cookies.Add(cookie);
            }
            else
            {
                HttpCookie Newcookie = new HttpCookie("landingChecks_V");
                Newcookie.Expires = DateTime.Now.AddDays(5);
                Newcookie.Values.Add(val, txt);
                Response.Cookies.Add(Newcookie);
     
            }
        }
        private void LcookieCheck()
        {
            HttpCookie cookie = Request.Cookies["landingChecks_V"];
            if (cookie != null && cookie.Values != null)
            {
                foreach (string key in cookie.Values.Keys)
                {
                    ListItem item = CheckBoxList1.Items.FindByValue(key);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
            else
            {
                CheckBoxList1.Items[0].Selected = true;
                CheckBoxList1.Items[1].Selected = true;
                CheckBoxList1.Items[2].Selected = true;
                CheckBoxList1.Items[3].Selected = true;
                CheckBoxList1.Items[4].Selected = true;
                CheckBoxList1.Items[5].Selected = true;
                CheckBoxList1.Items[6].Selected = true;
            }
     
        }
    }

    how do i load the docks from the cookie state using the checkboxes?

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="arrange.ascx.cs" Inherits="mods_arrange" %>
     
    <div class="content-in">
         
     <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
     
            <script type="text/javascript">
                var currentLoadingPanel = null;
                var currentUpdatedControl = null;
                function RequestStart(sender, args) {
                    currentLoadingPanel = $find("<%= LoadingPanel1.ClientID %>");
                    currentUpdatedControl = "TableLayout";
                    currentLoadingPanel.show(currentUpdatedControl);
                }
                function ResponseEnd() {
                    //hide the loading panel and clean up the global variables
                    if (currentLoadingPanel != null)
                        currentLoadingPanel.hide(currentUpdatedControl);
                    currentUpdatedControl = null;
                    currentLoadingPanel = null;
                }
            </script>
     
        </telerik:RadCodeBlock>
         
     
        <br />
        <asp:Panel ID="Panel1" runat="server">
            <telerik:RadDockLayout runat="server" ID="RadDockLayout1"  OnSaveDockLayout="RadDockLayout1_SaveDockLayout"
                OnLoadDockLayout="RadDockLayout1_LoadDockLayout" EnableEmbeddedSkins="false" Skin="myx" EnableViewState="false">
                <table id="TableLayout" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td>
                <div class="left">
                            <telerik:RadDockZone runat="server" ID="RadDockZone1"  >
                            </telerik:RadDockZone>
                </div>
                <div class="center">
                            <telerik:RadDockZone runat="server" ID="RadDockZone2"  >
                            </telerik:RadDockZone>
                </div>
                <div class="right">
                            <telerik:RadDockZone runat="server" ID="RadDockZone3" >
                            </telerik:RadDockZone>
                </div>
                        </td>
                    </tr>
                </table>
            </telerik:RadDockLayout>
        </asp:Panel>
     
    <asp:Panel ID="Panel2" runat="server" CssClass="customizePanel">
        <a name="customizepage"></a>
        <div class="movable">
        <div class="draggable"><h2>Customize</h2></div>
        <div class="block">
     
     
     
        <div>
            <p>
            <%= vboxTitles.getTitle("Add and remove your preferred topics", Request.QueryString["language"])%>
    </p>
    <asp:CheckBoxList ID="CheckBoxList1" runat="server"  Enabled="false"
    RepeatLayout="UnorderedList">
    </asp:CheckBoxList>
                              
    <asp:DropDownList ID="DropDownZone" runat="server" DataSource="<%#GetZones() %>"
    DataTextField="ID" DataValueField="ClientID" Width="150" Visible="false" >
    </asp:DropDownList>
    <br />
    <br />
    <telerik:RadButton ID="ButtonAddDock" runat="server"  OnClick="ButtonAddDock_Click"
                        Text="Save">
                            <Icon PrimaryIconCssClass="rbOk" PrimaryIconLeft="4" PrimaryIconTop="4" />
                    </telerik:RadButton>
    <asp:Button runat="server" CssClass="button" ID="ButtonPostBack" Text="Reset"
    OnClick="ButtonPostBack_Click" />
        <div class="clear"></div>
        </div>
     
     
        </div>
        <div class="block-bottoml">
        <div class="block-bottomr"></div>
        </div>
        </div>
    </asp:Panel>
                     
                             
            <br />
        </div>   
     
    <telerik:RadAjaxManager  ID="RadAjaxManagerArrange" runat="server" ClientEvents-OnRequestStart="RequestStart"
            ClientEvents-OnResponseEnd="ResponseEnd">
    <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="ButtonAddDocks" EventName="Click">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="Panel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
    </telerik:RadAjaxManager>
     
        <telerik:RadAjaxLoadingPanel ID="LoadingPanel1" runat="server" MinDisplayTime="500"
            Skin="Default">
        </telerik:RadAjaxLoadingPanel>
     
    please help with sample project on how to get this working

    thank you
  2. Slav
    Admin
    Slav avatar
    1356 posts

    Posted 24 Jun 2011 Link to this post

    Hi Davoud,

    While testing the code you provided, I came upon the following issues:

    1. You don't need to redirect the page to itself after postback as you did in ButtonAddDock Click event handler.
    protected void ButtonAddDock_Click(object sender, EventArgs e)
        {
            //Load the selected widget in the RadDock control
            foreach (ListItem con in CheckBoxList1.Items)
            {
                if (con.Selected == true)
                {
                    WcookieCheck(con.Value, con.Text);
                    RadDock dock = CreateRadDock(con.Text);
                    //find the target zone and add the new dock there
                    RadDockZone dz = (RadDockZone)FindControl(DropDownZone.SelectedItem.Text);
                    dz.Controls.Add(dock);
     
                    CreateSaveStateTrigger(dock);
     
                   // dock.Tag = con.Value;
                    LoadWidget(dock);
     
                    //Register a script to move dock to the last place in the RadDockZone
                    //The zone.dock(dock,index) client-side method is used
                    ScriptManager.RegisterStartupScript(this,
                        this.GetType(),
                        "MoveDock",
                    string.Format(@"function _moveDock() {{
                                Sys.Application.remove_load(_moveDock);
                                $find('{1}').dock($find('{0}'),{2});
                                }};
                                Sys.Application.add_load(_moveDock);", dock.ClientID, DropDownZone.SelectedValue, dz.Docks.Count),
                    true);
                }
            }
             
            //Response.Redirect("/default.aspx");
            //redirects the page to a wrong page after each postback. It is not necessary to attempt to redirect the page to itself
     
        }

    2. The size of the cookies cannot be more then 4KB. And since you implemented saving the position of RadDocks in a cookie, this causes them to disappear after the limit is reached. This is the size of the cookie after the manipulations. In this video you can see the described behavior. I have attached the cookie, used for storage, so you can check it out.

    For more information about the maximum size of a cookie you can check this search - http://www.google.bg/search?q=max+size+for+a+cookie.

    Note that HTTP Status Code 500 defines as "The server encountered an unexpected condition which prevented it from fulfilling the request.". You should take this in consideration as well.

    If the problem persists, please open a regular support ticket and send a simple, runnable project that will help us pinpoint what is the causing the issue.

    Kind regards,
    Slav
    the Telerik team

    Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

  3. UI for ASP.NET Ajax is Ready for VS 2017
Back to Top