This is a migrated thread and some comments may be shown as answers.

Help! Dynamic dock creation and state maintenance with ajax

1 Answer 52 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Kenneth Skillett
Top achievements
Rank 1
Kenneth Skillett asked on 17 Apr 2014, 06:56 AM
Hi.  I need help with figuring out how to get my dynamically created Telerik dock controls to visually persist and recreate given the following scenario.

I have a dashboard page that is displayed withing a master page container (don't know if this details matter, just outlining this).
In it I have 3 dockzones defined. In the database I have a set of widgets stored on per user basis that is separated by delimiter.
On initial load the widgets are parsed out and added sequentially to each zone according to their designation from the database.
When user interacts with the widgets, they are ajaxified, so visually the page does not appear to be reloading, but obviously on the background the page init and other events get kick off. 
I need help figure out the proper sequence to make it work so that I could still keep my persistence code in place (that stores the removal or widgets in db) and at the same time visually on the screen if page reloaded I would not get the exceptions about viewstate being different.

I currently either get exceptions about viewstate being different or about the docks with such and such uniqueid trying to dock to wrong zone. I'm assuming it's because they are stored in the sessionstate object, but if I'm removing them I end up with the viewstate error and if I'm clearing the session state object then it does not know about the changes and not all events fire as expected since the uniquename/id are gone...  I don't mind re-creating the docks again and again as long as visually the page does not appear to be reloading AND the db persistence takes place.

I'm providing the slightly simplified version of my code below for both the aspx and the code behind.  Any help would be appreciated.  TIA!!!

== aspx ==

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="default3.aspx.cs" Inherits="Web.default3" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<asp:Content runat="server" ID="Head" ContentPlaceHolderID="HeadContent">
<title><%=WebSettings.ApplicationName %></title>
</asp:Content>
<asp:Content runat="server" ID="Main" ContentPlaceHolderID="MainContent">
<asp:UpdatePanel ID="triggerPanel" runat="server"></asp:UpdatePanel>
<div style="display:none" id="ShowDockTags" runat="server"></div>
                <telerik:RadDockLayout runat="server" ID="RadDockLayout1" OnSaveDockLayout="RadDockLayout1_SaveDockLayout"
               OnLoadDockLayout="RadDockLayout1_LoadDockLayout" EnableLayoutPersistence="True" LayoutPersistenceRepositoryType="Cookies">
          
              <table cellspacing="0" cellpadding="0" style="text-align:center;" >
                  <tr style="text-align:center;">
                      <td style="width: 300px;">
                          <telerik:RadDockZone runat="server" ID="RadDockZone1" Width="300px" MinHeight="200"
                    Style="float: left; vertical-align:top" BorderStyle="None" FitDocks="True" Orientation="Vertical" RenderMode="Auto">
                              </telerik:RadDockZone>
                          </td>
                      <td style="width: 300px;">
                           <telerik:RadDockZone Width="300px" MinHeight="200" runat="server" ID="RadDockZone2" FitDocks="True" RenderMode="Auto"
                    Style="float: left; vertical-align:top" BorderStyle="None" Orientation="Vertical">
                               </telerik:RadDockZone>
                          </td>
                      <td style="width: 300px;">
                          <telerik:RadDockZone Width="300px" MinHeight="200" runat="server" ID="RadDockZone3" FitDocks="True" RenderMode="Auto"
                    Style="float: left; vertical-align:top" BorderStyle="None" Orientation="Vertical">
                              </telerik:RadDockZone>
                          </td>
                       </tr>
              </table> 
               
          </telerik:RadDockLayout>
</asp:Content>

== code behind ==

 protected void Page_Init(object sender, EventArgs e)
        {
            
                if ((CurrentDockStates.Count == 0) || Session["DockToRemove"] != "")
                {
                    GenerateDashboard();
                    Session["DockToRemove"] = "";
                }
                else
                {
                    for (int i = 0; i < CurrentDockStates.Count; i++)
                    {
                        RadDock dock;
                        if (CurrentDockStates[i].Closed == true)
                        {
                            dock = CreateRadDock(DockMode.Floating, CurrentDockStates[i].Title, (int)CurrentDockStates[i].Width.Value, (int)CurrentDockStates[i].Height.Value, "", "", false);
                        }
                        else
                        {
                            dock = CreateRadDock(DockMode.Docked, CurrentDockStates[i].Title, (int)CurrentDockStates[i].Width.Value, (int)CurrentDockStates[i].Height.Value, "", "", true);
                        }

                        dock.ID = string.Format("RadDock{0}", CurrentDockStates[i].UniqueName);
                        dock.ApplyState(CurrentDockStates[i]);

                        UpdatePanel up = new UpdatePanel();
                        LoadUserControl(dock.Tag, up);
                        dock.ContentContainer.Controls.Add(up);

                        if (dock.Closed == true)
                        {
                            dock.Pinned = false;
                        }
                        else dock.Pinned = true;
                        RadDockLayout1.Controls.Add(dock);
                        CreateSaveStateTrigger(dock);
                    }
                }
}

        private void GenerateDashboard()
        {
               UserSettingController _controller = new UserSettingController();
                UserController _usercontroller = new UserController();

                var user = _usercontroller.Select("where Login=@0", Context.User.Identity.Name).SingleOrDefault();
                if (user != null)
                {
                    var settings = _controller.Select("where User_Id=@0 and Setting_id in (31,32,33)", user.Id).ToList();
                    if (settings != null)
                    {
                        ShowDockTags.InnerHtml = "";
                        for (int i = 0; i < settings.Count; i++)
                        {
                            var setting = settings[i];
                            string widgets = setting.SettingValue;
                            int panelID = setting.SettingId;

                            string[] widgetValues = widgets.Split((char)29);
                            LoadUserWidgets(widgetValues, panelID);

                        }
                    }
                }
                RadDock dock = CreateRadDock(DockMode.Floating, "Add/Remove Widgets", 300, 270, "", "", false);

                UpdatePanel up = new UpdatePanel();
                up.ID = "WidgetSelector.ascx";
                LoadUserControl("WidgetSelector.ascx", up);
                dock.Tag = "WidgetSelector.ascx";
                dock.Closed = true;
                dock.ContentContainer.Controls.Add(up);
                RadDockLayout1.Controls.Add(dock);
            }

        }

        private void LoadUserWidgets(string[] widgets, int panelID)
        {
            RadDockZone curZone = RadDockZone1;
            switch (panelID)
            {
                case 31:
                    curZone = RadDockZone1;
                    break;
                case 32:
                    curZone = RadDockZone2;
                    break;
                case 33:
                    curZone = RadDockZone3;
                    break;

            }
            UserSettingMapper usm = new UserSettingMapper();

            for (int i = 0; i < widgets.Length; i++)
            {
                string widgetName = widgets[i];
                if (widgetName.Trim() != "")
                {
                    
                    string uc = usm.GetWidgetUpdatedName(widgets[i]);
                    ShowDockTags.InnerHtml += uc + ",";
                    string title = usm.GetWidgetTitle(uc);
                    uc += ".ascx";
                    RadDock dock = CreateRadDock(DockMode.Docked, title, 300, 200, "", "CloseWidgetCheck", true);
                    dock.Title = title;
                    UpdatePanel up = new UpdatePanel();
                    up.ID = uc;
                    LoadUserControl(uc, up);
                    dock.ContentContainer.Controls.Add(up);
                    dock.Tag = uc;
                    dock.Pinned = true;
                    curZone.Controls.Add(dock);
                    CreateSaveStateTrigger(dock);
                }

            }
        }

        private RadDock CreateRadDock(DockMode modetype, string title, int width, int height, string clinetinit, string clientcommand, bool expandcommand)
        {
                RadDock dock = new RadDock();
                dock.DockMode = modetype;
                dock.UniqueName = Guid.NewGuid().ToString().Replace("-", "a");
                dock.ID = string.Format("RadDock{0}", dock.UniqueName);
                dock.OnClientInitialize = clinetinit;
                dock.OnClientCommand = clientcommand;
                dock.Title = title;
                dock.Width = Unit.Pixel(width);
                dock.Height = Unit.Pixel(height);
                dock.Commands.Add(new DockCloseCommand());
                if (expandcommand == true) dock.Commands.Add(new DockExpandCollapseCommand());
                dock.Command += new DockCommandEventHandler(dock_Command);
                return dock;
        }

        public void LoadUserControl(string ucname, UpdatePanel panel)
        {
            Control widget = LoadControl(ucname);
            panel.ContentTemplateContainer.Controls.Clear();
            panel.ContentTemplateContainer.Controls.Add(widget);
        }

        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.
            foreach (DockState state in CurrentDockStates)
            {
                e.Positions[state.UniqueName] = state.DockZoneID;
                e.Indices[state.UniqueName] = state.Index;
                }
        }

        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 = true;

                AsyncPostBackTrigger saveStateTrigger = new AsyncPostBackTrigger();
                saveStateTrigger.ControlID = dock.ID;
                saveStateTrigger.EventName = "DockPositionChanged";
                triggerPanel.Triggers.Add(saveStateTrigger);
                
                saveStateTrigger = new AsyncPostBackTrigger();
                saveStateTrigger.ControlID = dock.ID;
                saveStateTrigger.EventName = "Command";

                triggerPanel.Triggers.Add(saveStateTrigger);
            
            
        }
        private List<DockState> CurrentDockStates
        {
            get
            {
                //Store the info about the added docks in the session. For real life
                // applications we recommend using database or other storage medium
                // for persisting this information.
                List<DockState> _currentDockStates = (List<DockState>)Session["CurrentDockStatesDynamicDocks"];
                if (Object.Equals(_currentDockStates, null))
                {
                    _currentDockStates = new List<DockState>();
                    Session["CurrentDockStatesDynamicDocks"] = _currentDockStates;
                }
                return _currentDockStates;
            }
            set
            {
                Session["CurrentDockStatesDynamicDocks"] = value;
            }
        }

        private bool CheckDockClientClosed(RadDock dock)
        {
            if (Session["DockToRemove"].ToString() != "")
            {
                if (dock.UniqueName == Session["DockToRemove"].ToString())
                {
                    CurrentDockStates.Remove(dock.GetState());
                    //Session["DockToRemove"] = "";
                    return true;
                } 
            }
            return false;
        }

private string GetZoneDocks(RadDockZone rdz)
        {
            UserSettingMapper usm = new UserSettingMapper();
            RadDock dock;
            string widgets = "";
            char delim = (char)29;

            if (rdz != null)
            {
                if (rdz.Docks.Count > 0)
                {
                    for (int i = 0; i < rdz.Docks.Count; i++)
                    {
                        dock = rdz.Docks[i];
                        if (CheckDockClientClosed(dock) == true) continue;

                        if (dock.Closed == false)
                        {
                            if (dock.DockMode == DockMode.Docked)
                            {
                                string tag = dock.Tag.Substring(0, dock.Tag.Length - 5);
                                string uc = usm.GetWidgetOldName(tag);
                                if (uc != null)
                                {
                                    string docks = usm.GetWidgetUpdatedName(uc);
                                    ShowDockTags.InnerHtml += docks + ",";
                                    widgets += uc + delim;
                                }
                            }

                        }
                    }
                    return widgets;
                }
                return "" + delim;
            }
            return "" + delim;
        }

        protected void RadDockLayout1_SaveDockLayout(object sender, DockLayoutEventArgs e)
        {
            //Save the dock state in the page Session. This will enable us
            // to recreate the dock in the next Page_Init.
            UserSettingController _controller = new UserSettingController();
            UserController _usercontroller = new UserController();
            char delim = (char)29;
            string widgets1 = "";
            string widgets2 = "";
            string widgets3 = "";
            ShowDockTags.InnerHtml = "";

                widgets1 = GetZoneDocks(RadDockZone1);
                widgets2 = GetZoneDocks(RadDockZone2);
                widgets3 = GetZoneDocks(RadDockZone3);
            
            var user = _usercontroller.Select("where Login=@0", Context.User.Identity.Name).SingleOrDefault();
            if (user != null)
            {
                    var settings = _controller.Select("where User_Id=@0 and Setting_id in (31,32,33)", user.Id).ToList();
                    if (settings != null)
                    {
                        for (int i = 0; i < settings.Count; i++)
                        {
                            var setting = settings[i];
                            if (setting.SettingId == 31)
                            {
                                if (widgets1 == "")
                                {
                                    setting.SettingValue = "" + delim;
                                }
                                else setting.SettingValue = widgets1;
                                _controller.Save(setting);
                            }
                            else if (setting.SettingId == 32)
                            {
                                if (widgets2 == "")
                                {
                                    setting.SettingValue = "" + delim;
                                }
                                else setting.SettingValue = widgets2;
                                _controller.Save(setting);
                            }
                            else if (setting.SettingId == 33)
                            {
                                if (widgets3 == "")
                                {
                                    setting.SettingValue = ""+delim;
                                }
                                else setting.SettingValue = widgets3;
                            
                                _controller.Save(setting);
                            }
                        }
                    }
                
            }
                CurrentDockStates = RadDockLayout1.GetRegisteredDocksState();
        }

1 Answer, 1 is accepted

Sort by
0
Kenneth Skillett
Top achievements
Rank 1
answered on 17 Apr 2014, 09:40 PM
I was able to resolve it myself, thanks for taking a look at this issue though!
Tags
General Discussions
Asked by
Kenneth Skillett
Top achievements
Rank 1
Answers by
Kenneth Skillett
Top achievements
Rank 1
Share this question
or