+1-888-365-2779
Try Now
More in this section

Forums / General Discussions / Add column to backend Users grid

Add column to backend Users grid

10 posts, 0 answered
  1. Robert
    Robert avatar
    70 posts
    Registered:
    05 Feb 2009
    26 Mar 2012
    Link to this post
    Hi, please can somebody guide me, how to add a column to backend Users grid. I want to add fields like IsApproved and approval link.

    I guess it could be a control Telerik.Sitefinity.Security.Web.UI.Principals.UserLists but I have no idea where to change the default template in system administration.

    Thank you!
    Robert
  2. Jen Peleva
    Jen Peleva avatar
    568 posts
    Registered:
    10 Nov 2016
    29 Mar 2012
    Link to this post
    Hello Robert,

    You are on the right track. Indeed to make a change to the grid you need to modify the UserLists.ascx template. Then map the template in Sitefinity through Administration -> Controls -> ViewMap by creating a new ViewMap instance, filled the following way:
    HostType: Telerik.Sitefinity.Security.Web.UI.Principals.UsersList
    LayoutTemplatePath: RelativePathToYourTemplate

    All the best,
    Jen Peleva
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  3. Robert
    Robert avatar
    70 posts
    Registered:
    05 Feb 2009
    29 Mar 2012
    Link to this post
    Thank you, it works.

    On thing I think it is worth to mention here for others is, that UniqueName ID tells the actual index being used in client binder.

    For example:
    <telerik:GridTemplateColumn UniqueName="BinderContainer7" ItemStyle-CssClass="sfDeleteCol" HeaderStyle-CssClass="sfDeleteCol"></telerik:GridTemplateColumn> 

    tells that item at index position 7 is used from client binder, not item with ID=BinderContainer7

    Thanks,
    Robert

  4. Chanan Zass
    Chanan Zass avatar
    123 posts
    Registered:
    21 Aug 2012
    30 May 2012
    Link to this post
    Hi Robert,
    We'd like to add a similar column with the ability of approving users directly from the grid.
    We had no problem displaying the user's status (approved or not), but can't figure out how to add the approval link and make it work (the way we had it in version 3.7).

    Have you succeeded in doing that?
    Thanks in advance.
  5. Robert
    Robert avatar
    70 posts
    Registered:
    05 Feb 2009
    30 May 2012
    Link to this post
    Hi Chanan,
    finally I didn't add the approval link because we decided email is enough, but I think it is rather easy. Just create landing page for user approval, take the link, add link column to the users grid and using link format string merge approval page url + user guid, set target="_blank" and it should work. Actually to get the picture you can take the url from the confirmation email Sitefinity sends by default.

    Robert
  6. Chanan Zass
    Chanan Zass avatar
    123 posts
    Registered:
    21 Aug 2012
    30 May 2012
    Link to this post
    Thanks much, Robert.
    Actually, we were looking for a more immediate handling of user approval (without moving out of the grid).
    For example in our version 3.7 we had in our grid this column:
    <asp:TemplateField AccessibleHeaderText="Account Status" HeaderText="Account Status" >
       <ItemTemplate>
           <asp:Label ID="StatusofUser" runat="server" Text='<%# StatusUser(Eval("UserName")) %>'></asp:Label>
           (<asp:LinkButton runat="server" ID="EnableUser" Text="Enable" ToolTip="EnableUser"
            CommandName="EnableUser" CommandArgument='<%# Eval("UserName") %>'></asp:LinkButton>
             /
             <asp:LinkButton runat="server" ID="DisableUser" Text="Disable" ToolTip="DisableUser"
              CommandName="DisableUser" CommandArgument='<%# Eval("UserName") %>'></asp:LinkButton>)
       </ItemTemplate>
    </asp:TemplateField>

    And in code-behind we had the EnableUser and DisableUser functions to enable and disable users.
    This way we didn't have to leave the page at all.
    The current userlist.ascx does not have a code-behind (all code is compiled in the Sitefinity assemblies), and we are hesitant about messing up with this complex file by trying to introduce commands, etc.
    Any clue would be most appreciated.


  7. Jen Peleva
    Jen Peleva avatar
    568 posts
    Registered:
    10 Nov 2016
    05 Jun 2012
    Link to this post
    Hello Chanan,

    I've already responded in your support ticket.

    Greetings,
    Jen Peleva
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  8. Chanan Zass
    Chanan Zass avatar
    123 posts
    Registered:
    21 Aug 2012
    06 Jun 2012
    Link to this post
    Greetings,

    So, with the help of Jen we've successfully added a command column (checkbox for approving users). Clicking the checkbox sets user.IsApproved to true (if checkbox is checked) -- or to false (checkbox is unchecked).
    However, if you require some additional server-side processing (we need to notify users that they have been approved, sending a localized message according to their country of origin, as entered in their profile), then the only way is to open a pop-up window with another page. The pop-up window is opened automatically after client-side processing is complete.

    We tried to use a RadWindowManager as pop-up window, but this introduced a conflict with the RadWindow that is opened by the EditUser() function (clicking on a user to edit his/her profile would not have any effect).

    Again, all this was so simple in Sitefinity 3.7 because server-side processing was not hidden from us, as it is now.
    If anyone is interested in having our modified UsersList.ascx, let me know.

  9. George
    George  avatar
    204 posts
    Registered:
    05 Sep 2006
    28 May 2013 in reply to Chanan Zass
    Link to this post
    Hi Jen,

    Is there anyway that you can provide me with that code instead of having to rewrite it myself?

    Thanks a lot,

    George
  10. Chanan Zass
    Chanan Zass avatar
    123 posts
    Registered:
    21 Aug 2012
    28 May 2013 in reply to George
    Link to this post
    Hi,
    Attached is our customized control (which includes a pop-up for notifying users; the file NotifyApprovedUser.aspx is not included: it basically asks you if you wish to notify the approved user or not, then sends a standard message in the user's language).

    Please remember to update the UserList ViewMap:
    - Administration
    - Settings
    - Advanced
    - Controls
    - ViewMap
    - Create New
    - HostType: Telerik.Sitefinity.Security.Web.UI.Principals.UsersList, Telerik.Sitefinity
    - LayoutTemplatePath: [path to your UsersList.ascx control]

    <%@ Control Language="C#" %>
    <%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
    <%@ Register Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI" TagPrefix="sitefinity" %>
    <%@ Register Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI.Backend" TagPrefix="sitefinity" %>
     
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
         <script type="text/javascript">
             function openRadEditWindow(uName) {
                 var width = 450;
                 var height = 210;
                 var left = parseInt((screen.availWidth / 2) - (width / 2));
                 var top = parseInt((screen.availHeight / 2) - (height / 2));
     
                 var oWnd = window.open('<%= ResolveUrl("~/") %>NotifyApprovedUser.aspx?u=' + uName, 'RadWindow1', 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ', status=0, location=0, menubar=0, titlebar=0, toobar=1');
                 // oWnd.center();
             }
         </script>
    </telerik:RadCodeBlock>
     
    <sitefinity:ResourceLinks id="resourcesLinks" runat="server">
        <sitefinity:ResourceFile Name="Styles/Grid.css" />
        <sitefinity:ResourceFile Name="Styles/MaxWindow.css" />
        <sitefinity:ResourceFile Name="Styles/ToolBar.css" />
        <sitefinity:ResourceFile Name="Styles/Ajax.css" />
        <sitefinity:ResourceFile Name="Styles/Window.css" />
    </sitefinity:ResourceLinks>
     
    <sitefinity:ClientLabelManager id="clientLabelManager" runat="server">
        <Labels>
            <sitefinity:ClientLabel ClassId="Labels" Key="UserOnline" runat="server" />
            <sitefinity:ClientLabel ClassId="Labels" Key="UserOffline" runat="server" />
            <sitefinity:ClientLabel ClassId="Labels" Key="QuestionBeforeDeletingUsers" runat="server" />
            <sitefinity:ClientLabel ClassId="Labels" Key="QuestionBeforeDeletingUser" runat="server" />
        </Labels>
    </sitefinity:ClientLabelManager>
     
    <telerik:RadWindowManager id="radWindowManager" runat="server" ShowContentDuringLoad="false" Skin="Sitefinity">
        <Windows>
            <telerik:RadWindow id="newUserDialog"
                runat="server"
                NavigateUrl="~/Sitefinity/Dialog/UserNewDialog"
                OnClientClose="EditorClosed"
                Height="100%"
                Width="100%"
                CssClass="sfMaximizedWindow"
                Skin="Sitefinity"
                Behaviors="None"
                InitialBehaviors="Maximize"
                VisibleStatusBar="false">
            </telerik:RadWindow>
            <telerik:RadWindow id="editUserDialog"
                runat="server"
                NavigateUrl="~/Sitefinity/Dialog/UserEditDialog"
                OnClientClose="EditorClosed"
                Height="100%"
                Width="100%"
                CssClass="sfMaximizedWindow"
                Skin="Sitefinity"
                Behaviors="None"
                InitialBehaviors="Maximize"
                VisibleStatusBar="false">
            </telerik:RadWindow>
        </Windows>
    </telerik:RadWindowManager>
     
    <sitefinity:FlatProviderSelector ID="providerSelectorPanel" runat="server">
    </sitefinity:FlatProviderSelector>
     
    <div class="sfAllToolsWrapper">
        <div class="sfAllTools">
            <ul id="commandButtons" class="sfActions">
                <li class="sfMainAction">
                    <asp:LinkButton ID="createNew" CommandName="CreateNew" runat="server" CssClass="sfLinkBtn sfNew" OnClientClick="NewUser(); return false;">
                        <strong class="sfLinkBtnIn">
                            <asp:Literal runat="server" Text="<%$ Resources:PageResources, UsersListCreateUser %>" /></strong>
                    </asp:LinkButton>
                </li>
                <li>
                    <a href="javascript:deleteSelectedUsers();" id="deleteLink" style="display: none; " class="sfLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:Labels, Delete %>" /></strong></a>
                    <span id="deleteLinkDisabled" class="sfLinkBtn sfDisabledLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal2" runat="server" Text="<%$ Resources:Labels, Delete %>" /></strong></span>
                </li>
                <li>
                    <a id="assignLink" href="javascript:ShowRolesPanel('assign');" style="display: none; " class="sfLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal3" runat="server" Text="<%$ Resources:Labels, AssignToRole %>" /></strong></a>
                    <span id="assignLinkDisabled" class="sfLinkBtn sfDisabledLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal4" runat="server" Text="<%$ Resources:Labels, AssignToRole %>" /></strong></span>
                </li>
                <li>
                    <a id="unassignLink" href="javascript:ShowRolesPanel('unassign');" style="display: none; " class="sfLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal runat="server" Text="<%$ Resources:Labels, UnassignFromRole %>" /></strong></a>
                    <span id="unassignLinkDisabled" class="sfLinkBtn sfDisabledLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal6" runat="server" Text="<%$ Resources:Labels, UnassignFromRole %>" /></strong></span>
                </li>
                 
                <li class="sfSeparator">
                    <a href="javascript:ShowSearchPanel();" id="findUsersLink" class="sfLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal7" runat="server" Text="<%$ Resources:Labels, Search %>" /></strong></a><a href="javascript:CloseSearchPanel();" id="closeSearchPanelLink" style="display:none;" class="sfLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal8" runat="server" Text="<%$ Resources:Labels, CloseSearch %>" /></strong></a>
                </li>
                 
            </ul>
            <!-- roles panel -->
            <div id="rolesPanel" style="display:none;" class="sfToolsForm">
                <label for="RoleName" id="assignLabel">
                    <asp:Literal ID="assignLiteral" runat="server" Text='<%$Resources:Labels, AssignUsersTo %>'></asp:Literal>
                </label>
                <label for="RoleName" id="unassignLabel">
                    <asp:Literal ID="unassignLiteral" runat="server" Text='<%$Resources:Labels, UnassignUsersFrom %>'></asp:Literal>
                </label>
                <asp:DropDownList ID="rolesList" runat="server">
                </asp:DropDownList>
                <a sys:href="javascript:void(0);" onclick="AssignUsersToRole();" class="sfLinkBtn sfSave editCommand" id="assignButton">
                    <strong class="sfLinkBtnIn">
                        <asp:Literal ID="assignButtonLiteral" runat="server" Text='<%$Resources:Labels, Assign %>'></asp:Literal>
                    </strong>
                </a>
                <a sys:href="javascript:void(0);" onclick="UnassignUsersFromRole();" class="sfLinkBtn sfRemove deleteCommand" id="unassignButton">
                    <strong class="sfLinkBtnIn">
                        <asp:Literal ID="unassignButtonLiteral" runat="server" Text='<%$Resources:Labels, Unassign %>'></asp:Literal>
                    </strong>
                </a>
                <asp:Literal ID="orLiteral" runat="server" Text='<%$Resources:Labels, or %>'></asp:Literal>
                <a id="closeRolesPanel" href="javascript:HideRolesPanel();" class="sfCancel">
                    <asp:Literal ID="cancelButtonLiteral" runat="server" Text='<%$Resources:Labels, Cancel %>'></asp:Literal>
                </a>
            </div>
            <!-- end roles panel -->
        </div>
        <div id="searchPanel"  class="sfSearch" style="display:none">
            <fieldset class="sfSearchBoxSet">
                <select id="searchType">
                    <option value="UserName" selected >Username</option>
                    <option value="Email">Email</option>
                </select>
                <input type="text" size="100" value="" id="filterText" class="sfTxt" />
                <a href="javascript:SearchUsers();" id="A1" class="sfLinkBtn"><strong class="sfLinkBtnIn"><asp:Literal ID="Literal5" runat="server" Text="<%$ Resources:Labels, Search %>" /></strong></a>
            </fieldset>
        </div>
     
        <telerik:RadToolBar ID="RadToolViews" runat="server" Skin="Sitefinity" CssClass="sfMasterViews" OnClientButtonClicking="ToolbarModeChanged">
            <Items>
                <telerik:RadToolBarButton>
                    <ItemTemplate>
                        <span>
                            <asp:Literal ID="viewsLiteral" runat="server" Text='<%$Resources:Labels, Views %>'></asp:Literal>
                        </span>
                    </ItemTemplate>
                </telerik:RadToolBarButton>
                <telerik:RadToolBarButton Text="<%$ Resources:Labels, Grid %>" Tooltip="<%$ Resources:Labels, Grid %>" Value="Grid" CheckOnClick="True" Group="Views" CssClass="sfMasterViewsGrid" />
                <telerik:RadToolBarButton Text="<%$ Resources:Labels, List %>" Tooltip="<%$ Resources:Labels, List %>" Value="List" CheckOnClick="True" Group="Views" Checked="True" CssClass="sfMasterViewsList" />
            </Items>
        </telerik:RadToolBar>
    </div>
    <div class="sfWorkArea">
     
        <sitefinity:Message ID="messageControl" runat="server"
            ElementTag="div" 
            CssClass="sfMessage sfGridViewMessage"
            RemoveAfter="30000" 
            FadeDuration="10" />
     
        <!-- grid mode -->
        <div id="gridMode" style="display:none;">
            <telerik:RadGrid id="usersGrid" runat="server"
                allowpaging="True"
                allowmultirowselection="true"
                pagesize="20"
                skin="Sitefinity"
                AllowSorting="True"
                CssClass="rgTopOffset">
                <PagerStyle Mode="NumericPages" />           
                <ClientSettings EnableRowHoverStyle="true" EnableAlternatingItems="false">
                    <ClientEvents OnRowSelected="rowSelected" OnRowDeselected="rowDeselected" OnDataBound="Grid_DataBound" OnRowDataBound="Grid_ItemDataBound"/>
                    <Selecting AllowRowSelect="True" />
                </ClientSettings>
                <MasterTableView PageSize="20">
                    <Columns>
                        <telerik:GridClientSelectColumn UniqueName="ClientSelectColumn" ItemStyle-CssClass="sfCheckBoxCol" HeaderStyle-CssClass="sfCheckBoxCol" />
                        <telerik:GridTemplateColumn UniqueName="BinderContainer1" HeaderText="<%$ Resources:Labels, Username %>" SortExpression="UserName" ItemStyle-CssClass="sfTitleCol" HeaderStyle-CssClass="sfTitleCol"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer2" HeaderText="<%$ Resources:Labels, Roles %>"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer0" HeaderText="<%$ Resources:Labels, UserFirstAndLastNameName %>" SortExpression="FirstName"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer3" HeaderText="<%$ Resources:Labels, Email %>" SortExpression="Email"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer4" HeaderText="<%$ Resources:Labels, CreationDate %>" SortExpression="CreationDate"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer5" HeaderText="<%$ Resources:Labels, Status %>" SortExpression="IsLoggedIn"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer6" HeaderText="<%$ Resources:Labels, LastLogin %>" SortExpression="LastLoginDate" ItemStyle-CssClass="sfLongDate" HeaderStyle-CssClass="sfLongDate"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer7" HeaderText="<%$ Resources:MainResource, Approved %>" ItemStyle-HorizontalAlign="Center"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer8" ItemStyle-CssClass="sfDeleteCol" HeaderStyle-CssClass="sfDeleteCol"></telerik:GridTemplateColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>
             
            <sitefinity:RadGridBinder id="usersGridBinder" runat="server"
                    ServiceUrl="~/Sitefinity/Services/Security/Users.svc"
                    TargetId="usersGrid"
                    BindOnLoad="false"
                    OnClientItemEditCommand="OpenItem"
                    OnClientItemDeleteCommand="ClientBinderDeleting"
                    OnClientItemDataBound="UsersBinder_ItemDataBound"
                    OnClientTargetCommand="UsersBinder_TargetCommand"
                    OnClientError="UsersBinder_Error"
                    DataKeyNames="ProviderUserKey"
                    DataMembers="UserName, ProviderName, ProviderUserKey, DisplayName"
                    ContainerTag="div"
                    LoadingPanelID="usersGridLoadingPanel"
                    OnClientDataBound="UsersBinder_ClientDataBound">
                <Containers>
                    <sitefinity:BinderContainer ID="BinderContainer1" runat="server"
                        <span>{{DisplayName}}</span>
                    </sitefinity:BinderContainer>           
                    <sitefinity:BinderContainer ID="BinderContainer2" runat="server"
                        <a sys:href="javascript:void(0);" class="editCommand sfItemTitle sfnostatus">{{UserName}}</a>
                    </sitefinity:BinderContainer
                    <sitefinity:BinderContainer ID="BinderContainer3" runat="server"
                        <span id="rolesContainer"></span>
                    </sitefinity:BinderContainer
                    <sitefinity:BinderContainer ID="BinderContainer4" runat="server"
                        <span>{{Email ? Email : "-"}}</span>
                    </sitefinity:BinderContainer
                    <sitefinity:BinderContainer ID="BinderContainer5" runat="server"
                        <span>{{CreationDate.sitefinityLocaleFormat('dd MMM, yyyy')}}</span>
                    </sitefinity:BinderContainer
                     <sitefinity:BinderContainer ID="BinderContainer6" runat="server"
                        <span id="loginStatus"></span>
                    </sitefinity:BinderContainer
                      <sitefinity:BinderContainer ID="BinderContainer7" runat="server"
                        <span id="loginDate">{{LastLoginDate ? LastLoginDate.sitefinityLocaleFormat('dd MMM, yyyy, hh:mm') : "-"}}</span>
                    </sitefinity:BinderContainer>
                    <sitefinity:BinderContainer ID="BinderContainer15" runat="server"
                        <input type="checkbox" id="IsApproved" class='sf_binderCommand_approvedChanged' />
                    </sitefinity:BinderContainer>
                    <sitefinity:BinderContainer ID="BinderContainer8" runat="server">
                        <a sys:href="javascript:void(0);" class="deleteCommand sfDeleteBtn" title="{$Labels,Delete$}">{$Labels,Delete$}</a>
                    </sitefinity:BinderContainer>
                </Containers>
            </sitefinity:RadGridBinder>
            <telerik:RadAjaxLoadingPanel ID="usersGridLoadingPanel" runat="server" Skin="Sitefinity" IsSticky="false" EnableSkinTransparency="false"><asp:Literal ID="Literal9" runat="server" Text="<%$ Resources:Labels, Loading %>" />
            </telerik:RadAjaxLoadingPanel>   
        </div>
        <!-- end grid mode -->
         
        <!-- list mode -->
        <div id="listMode">
            <telerik:RadGrid id="usersList" runat="server" allowpaging="True" allowmultirowselection="true" pagesize="20" skin="Sitefinity" AllowSorting="True" CssClass="rgTopOffset sfListViewGrid">
                <PagerStyle Mode="NumericPages" />           
                <ClientSettings EnableRowHoverStyle="true" EnableAlternatingItems="false">
                    <ClientEvents OnRowSelected="rowSelected" OnRowDeselected="rowDeselected" OnDataBound="Grid_DataBound"  OnRowDataBound="Grid_ItemDataBound" />
                    <Selecting AllowRowSelect="True" />
                </ClientSettings>
                <MasterTableView PageSize="20">
                    <Columns>
                        <telerik:GridClientSelectColumn UniqueName="ClientSelectColumn" ItemStyle-CssClass="sfCheckBoxCol" HeaderStyle-CssClass="sfCheckBoxCol" />
                        <telerik:GridTemplateColumn UniqueName="BinderContainer0" HeaderStyle-CssClass="sfTitleCol" ItemStyle-CssClass="sfTitleCol sfUserCell" HeaderText="<%$ Resources:SecurityResources, UsernameRole %>"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer1" ItemStyle-CssClass="sfNameCell" HeaderText="<%$ Resources:SecurityResources, NameEmail %>"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer2" HeaderText="<%$ Resources:SecurityResources, Registration %>"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer3" HeaderText="Status" SortExpression="IsLoggedIn"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer4" HeaderText="Last login" SortExpression="LastLoginDate" ItemStyle-CssClass="sfLongDate" HeaderStyle-CssClass="sfLongDate"></telerik:GridTemplateColumn>
                        <telerik:GridTemplateColumn UniqueName="BinderContainer5" ItemStyle-CssClass="sfDeleteCol" HeaderStyle-CssClass="sfDeleteCol"></telerik:GridTemplateColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>
             
            <sitefinity:RadGridBinder id="usersListBinder" runat="server"
                    ServiceUrl="~/Sitefinity/Services/Security/Users.svc"
                    TargetId="usersList"
                    BindOnLoad="false"
                    OnClientItemEditCommand="OpenItem"
                    OnClientItemDeleteCommand="ClientBinderDeleting"
                    OnClientItemDataBound="UsersBinder_ItemDataBound"
                    OnClientTargetCommand="UsersBinder_TargetCommand"
                    DataKeyNames="ProviderUserKey"
                    DataMembers="UserName, ProviderName, ProviderUserKey"
                    ContainerTag="div"
                    LoadingPanelID="usersListLoadingPanel">
                <Containers>
                    <sitefinity:BinderContainer ID="BinderContainer9" runat="server"
                        <a sys:href="javascript:void(0);" class="editCommand">
                            <span class="sfInlineBlock sfAvatarImgWrp"><img ID="avatarImage" /></span>
                            <span class="sfItemTitle">{{UserName}}</span>
                        </a>
                        <span id="rolesContainer" class="sfLine"></span>
                    </sitefinity:BinderContainer
                    <sitefinity:BinderContainer ID="BinderContainer10" runat="server"
                            <strong>
                                {{DisplayName}}
                            </strong>
                        <span>{{Email}}</span>
                    </sitefinity:BinderContainer
                    <sitefinity:BinderContainer ID="BinderContainer11" runat="server"
                        <span>{{CreationDate.sitefinityLocaleFormat('dd MMM, yyyy')}}</span>
                    </sitefinity:BinderContainer
                     <sitefinity:BinderContainer ID="BinderContainer12" runat="server"
                        <span id="loginStatus"></span>
                    </sitefinity:BinderContainer
                      <sitefinity:BinderContainer ID="BinderContainer13" runat="server"
                        <span id="loginDate">{{LastLoginDate ? LastLoginDate.sitefinityLocaleFormat('dd MMM, yyyy; hh : mm') : "-"}}</span>
                    </sitefinity:BinderContainer
                    <sitefinity:BinderContainer ID="BinderContainer14" runat="server">
                        <a sys:href="javascript:void(0);" class="deleteCommand sfDeleteBtn" title="{$Labels,Delete$}">{$Labels,Delete$}</a>
                    </sitefinity:BinderContainer>
                </Containers>
            </sitefinity:RadGridBinder>
            <telerik:RadAjaxLoadingPanel ID="usersListLoadingPanel" runat="server" Skin="Sitefinity" IsSticky="false" EnableSkinTransparency="false"><asp:Literal ID="Literal10" runat="server" Text="<%$ Resources:Labels, Loading %>" />
            </telerik:RadAjaxLoadingPanel>
             
        </div>
        <!-- end list mode -->
        <asp:HiddenField runat="server" ID="hfLoginPageUrl" />
        <asp:HiddenField runat="server" ID="hProvidersAbilities" />
        <asp:HiddenField runat="server" ID="hDefaultMembershipProviderName" />
    </div>   
     
    <asp:HiddenField ID="hUsersServiceUrl" runat="server" />
    <asp:HiddenField ID="hCurrentUserID" runat="server" />
    <asp:HiddenField ID="hDeleteCurrentUserWarning" runat="server" />
     
    <script type="text/javascript">
        var gridBinder;
        var listBinder;
     
        var commandPanel;
        var usersGrid;
        var usersList;
        var newUserDialog;
        var editUserDialog;
        var messageControl;
        var selectedUsersIds;
     
        var checkedItemsFollowupArray = new Array();
     
        var membershipProviderSettings;
        var selectBoxRoles;
        var filtered = false;
     
        var _currentUserId;
        var _currentUserName;
        var editUserProviderName;
        var currentMode = 'List';
        var currentProviderName = '';
     
        var _currentRoleID = "";
        var _currentRoleProviderName = "";
        var _currentFilter = "";
        var bindingInProgress_IgnoreSelectionsOrDeselections = false;
        var loggedInUserID = "";
        var deleteLoggedInUserWarning = "";
        var providersAbilities = [];
     
        var btnCreate = null;
        var defaultMembershipProviderName = null;
     
        var providerSelectorPanel = null;
     
        $("body").addClass("sfHasSidebar");
     
        Sys.Application.add_load(Initialize);
     
        function Initialize() {
            gridBinder = $find('<%= usersGridBinder.ClientID %>');
            usersGrid = $find('<%= usersGrid.ClientID %>');
            usersList = $find('<%= usersList.ClientID %>');
            listBinder = $find('<%= usersListBinder.ClientID %>');
            newUserDialog = GetRadWindowManager().getWindowByName("newUserDialog");
            editUserDialog = GetRadWindowManager().getWindowByName("editUserDialog");
            messageControl = $find('<%= messageControl.ClientID %>');
            loggedInUserID = $get("<%= hCurrentUserID.ClientID %>").value.trim();
            deleteLoggedInUserWarning = $get("<%= hDeleteCurrentUserWarning.ClientID %>").value;
     
            providerSelectorPanel = $find('<%= providerSelectorPanel.ClientID %>');
            providerSelectorPanel.add_onProviderSelected(providerSelectionChanged);
     
            var abilities = $('#' + '<%= hProvidersAbilities.ClientID %>').val();
            if(abilities && abilities != null)
            {
                providersAbilities = Sys.Serialization.JavaScriptSerializer.deserialize(abilities);
            }
            btnCreate = $("#" + "<%= createNew.ClientID %>");
            defaultMembershipProviderName = $("#" + "<%= hDefaultMembershipProviderName.ClientID %>").val();
     
            membershipProviderSettings = GetMembershipProviderSettings(currentProviderName);
        }
     
        function BindProvidersList(strRoleID, strRoleProvider, bUsersWithoutRole) {
            var keys = new Array();
            keys[keys.length] = "GetUserProviders";
            var params = {
                'roleId': strRoleID,
                'roleProvider': strRoleProvider,
                'usersWithoutRole': bUsersWithoutRole,
                'userFilter': _currentFilter
            };
            var serviceUrl = $('#' + '<%= hUsersServiceUrl.ClientID %>').val();
            var clientManager = new Telerik.Sitefinity.Data.ClientManager();
            clientManager.InvokeGet(
                serviceUrl,
                params,     //An array. Constructing the querystring http://svc/?param1=params[param1]¶m2=params[param2]...
                keys,       //An array. URL params are concatenated to the URL http://svc/key1/key2/key3...
                BindProvidersListSuccess,
                BindProvidersListFail,
                this);
        }
     
        function BindProvidersListFail() {
            //NOTE: this is not necessary, as we do a second rebind after which there are no problems
            // plus, when we log out the user that deletes their own account, an error that can't be prevented will occur.
            //alert("UsersList.ascx BindProvidersListFail");
        }
     
        function BindProvidersListSuccess(sender, commandArgs) {
            var providersData = commandArgs.Items;
            //populate the box
            for (var i = 0; i < providersData.length; i++) {
                $find('<%= providerSelectorPanel.ClientID %>').setProviderTitle(providersData[i].UserProviderName, providersData[i].UserProviderTitle + " (" + providersData[i].NumOfUsers + ")");
            }
        }
     
        function providerSelectionChanged(sender, args) {
            Bind();
            RebindUsersInRoles(args.ProviderName);
        }
     
        function updateSelectedItemsCount() {
            var selectedItems = GetCurrentMasterView().get_selectedItems();
            $('#numberOfSelectedUsers').text(selectedItems.length);
     
            if (selectedItems.length == 0) {
                $('#deleteLink, #assignLink, #unassignLink').hide();
                $('#deleteLinkDisabled, #assignLinkDisabled, #unassignLinkDisabled').show();
                HideRolesPanel();
            }
            else {
                $('#deleteLink, #assignLink, #unassignLink').show();
                $('#deleteLinkDisabled, #assignLinkDisabled, #unassignLinkDisabled').hide();
            }
        }
     
        function rowSelected(sender, args) {
            if (!bindingInProgress_IgnoreSelectionsOrDeselections) {
                var userItem = args.get_item().get_dataItem();
                addUserToFollowupArray(userItem);
                updateSelectedItemsCount();
            }
        }
     
        function rowDeselected(sender, args) {
            if (!bindingInProgress_IgnoreSelectionsOrDeselections) {
                var userItem = args.get_item().get_dataItem();
                removeUserFromFollwupArray(userItem);
                updateSelectedItemsCount();
            }
        }
     
        function addUserToFollowupArray(userItem) {
            var arrayUserItem = null;
            //try to lacate the current user in the already existing array
            for (var curItem = 0; curItem < checkedItemsFollowupArray.length; curItem++) {
                if (checkedItemsFollowupArray[curItem].UserID == userItem.UserID) {
                    arrayUserItem = checkedItemsFollowupArray[curItem];
                    break;
                }
            }
            //if the user is not there, add it.
            if (arrayUserItem == null) {
                checkedItemsFollowupArray[checkedItemsFollowupArray.length] = userItem;
            }
        }
     
        function removeUserFromFollwupArray(userItem) {
            for (var curItem = 0; curItem < checkedItemsFollowupArray.length; curItem++) {
                if (checkedItemsFollowupArray[curItem].UserID == userItem.UserID) {
                    checkedItemsFollowupArray.splice(curItem, 1);
                    break;
                }
            }
        }
     
        function PopulateSelectedItemIndexes() {
            selectedUsersIds = [];
            for (var curItem = 0; curItem < checkedItemsFollowupArray.length; curItem++) {
                selectedUsersIds.push(checkedItemsFollowupArray[curItem].UserID);
            }
        }
     
        function SelectSelectedItems() {
            var masterView = GetCurrentMasterView();
            var items = masterView.get_dataItems();
            var itemsLength = items.length;
            for (var i = 0; i < itemsLength; i++) {
                if (checkedItemsFollowupArray.length == 0) {
                    items[i].set_selected(false);
                }
                else {
                    var checkStat = false;
                    for (var curItem = 0; curItem < checkedItemsFollowupArray.length; curItem++) {
                        var dataItem = items[i].get_dataItem();
                        if (dataItem == null) {
                            break;
                        }
                        if (checkedItemsFollowupArray[curItem].UserID == dataItem.UserID) {
                            checkStat = true;
                            break;
                        }
                    }
                    items[i].set_selected(checkStat);
                }
            }
        }
     
        function HideNonSelectedRows() {
            var masterView = GetCurrentMasterView();
            SetVisibilityOfAllRows(false);
            var selectedItems = masterView.get_selectedItems();
     
            for (var i = 0; i < selectedItems.length; i++) {
                var item = selectedItems[i];
                item = item.get_element();
                masterView.showItem(item.rowIndex - 1);
            }
        }
     
        function SetVisibilityOfAllRows(visible) {
            var masterView = GetCurrentMasterView();
            var itemsLength = masterView.get_dataItems().length;
            var totalItemsCount = masterView.get_dataSource().length;
            for (var i = 0; i < totalItemsCount; i++) {
                if (visible) {
                    masterView.showItem(i);
                }
                else {
                    masterView.hideItem(i);
                }
            }
        }
     
        function toggleFilter() {
            if (filtered) {
                SetVisibilityOfAllRows(true);
            }
            else {
                HideNonSelectedRows();
            }
            filtered = !filtered;
        }
     
        function GetMembershipProviderSettings(providerName) {
            // TODO: fix this mess
            var settings = new Object();
            settings.RequiresQuestionAndAnswer = false;
            settings.EnablePasswordRetrieval = false;
            settings.EnablePasswordReset = true;
            settings.Name = providerName;
            return settings;
        }
     
        function GetSelectedUsers() {
            return checkedItemsFollowupArray;
        }
     
        function usernameRoleRelationDeleted(sender, args) {
            // do action after username/role is removed
        }
     
        /* ********************************************** modes ********************************************** */
        function ToolbarModeChanged(sender, args) {
            var button = args.get_item();
            PopulateSelectedItemIndexes();
            var urlParams;
            if (args.get_item().get_value() == 'Grid') {
                $('#gridMode').show();
                $('#listMode').hide();
                currentMode = 'Grid';
                gridBinder.set_sortExpression(listBinder.get_sortExpression());
                urlParams = listBinder.get_urlParams();
                gridBinder.set_filterExpression(listBinder.get_filterExpression());
                gridBinder.set_provider(listBinder.get_provider());
            }
            else if (args.get_item().get_value() == 'List') {
                $('#gridMode').hide();
                $('#listMode').show();
                currentMode = 'List';
                listBinder.set_sortExpression(gridBinder.get_sortExpression());
                urlParams = gridBinder.get_urlParams();
                listBinder.set_filterExpression(gridBinder.get_filterExpression());
                listBinder.set_provider(gridBinder.get_provider());
            }
            Bind(urlParams);
        }
     
        function Bind(urlParams) {
            bindingInProgress_IgnoreSelectionsOrDeselections = true;
            if (currentMode == 'Grid') {
                BindGrid(urlParams);
            } else if (currentMode == 'List') {
                BindList(urlParams);
            }
        }
     
        function UsersBinder_ItemDataBound(sender, args) {
            var dataItem = args.get_dataItem();
     
            var checkBox = args.FindControl('IsApproved');
            if (checkBox) {
                checkBox.checked = dataItem.IsApproved;
            }
     
            var allRoles = dataItem.RolesOfUser;
            var rolesString = "";
            var roleTextElement = args.FindControl('rolesContainer');
            for (var i = 0; i < allRoles.length; i++) {
                rolesString += allRoles[i].RoleName + ", ";
            }
            var clientLabelManager = $find('<%= clientLabelManager.ClientID %>');
            var loggedInMessage = clientLabelManager.getLabel('Labels', 'UserOnline');
            var notLoggedInMessage = clientLabelManager.getLabel('Labels', 'UserOffline');
            var loggedInControl = args.FindControl('loginStatus');
            if (dataItem.IsLoggedIn == true) {
                loggedInControl.innerHTML = loggedInMessage;
                loggedInControl.className = "sfLogged";
            }
            else {
                loggedInControl.innerHTML = notLoggedInMessage;
     
            }
     
            var avatarImageElement = args.FindControl('avatarImage');
            if (avatarImageElement) {
                avatarImageElement.src = dataItem.AvatarThumbnailUrl;
                if (dataItem.AvatarImageSmallerWidth && dataItem.AvatarImageSmallerWidth == true) {
                    jQuery(avatarImageElement).attr("width", 35);
                } else {
                    jQuery(avatarImageElement).attr("height", 35);
                }
            }
     
            rolesString = rolesString.substring(0, rolesString.length - 2);
            roleTextElement.innerHTML = rolesString;
        }
     
        function UsersBinder_ClientDataBound(sender, args) {
            providerSelectorPanel.highlightProviderByName(sender.get_provider());
        }
     
        function Grid_DataBound(sender, args) {
            bindingInProgress_IgnoreSelectionsOrDeselections = false;
            SelectSelectedItems();
        }
     
        function Grid_ItemDataBound(sender, args) {
            var userItem = args.get_dataItem();
            if (userItem != null) {
                for (var curItem = 0; curItem < checkedItemsFollowupArray.length; curItem++) {
                    if (checkedItemsFollowupArray[curItem].UserID == userItem.UserID) {
                        checkedItemsFollowupArray[curItem].RolesOfUser = userItem.RolesOfUser;
                    }
                }
            }
        }
     
        function UsersBinder_TargetCommand(sender, args) {
            PopulateSelectedItemIndexes();
        }
     
        function GetCurrentMasterView() {
            if (currentMode == 'Grid') {
                return usersGrid.get_masterTableView();
            } else if (currentMode == 'List') {
                return usersList.get_masterTableView();
            }
        }
     
        function UsersBinder_Error(sender, args) {
            messageControl.showNegativeMessage(args.get_error());
        }
     
        /* ********************************************** grid mode ********************************************** */
        function BindGrid(urlParams) {
            if (urlParams == null) {
                urlParams = [];
            }
     
            var providerName = $find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName;
            currentProviderName = providerName;
            SetButtonsAccordingToCurrentProvider();
            gridBinder.set_provider(providerName);
            urlParams['roleId'] = _currentRoleID;
            urlParams['roleProvider'] = _currentRoleProviderName;
            urlParams['forAllProviders'] = providerName.length == 0;
            urlParams['filter'] = _currentFilter;
            gridBinder.set_urlParams(urlParams);
            gridBinder.add_onItemCommand(OnItemCommand);
            gridBinder.DataBind();
        }
     
        function OnItemCommand(sender, args) {
            if (args.get_commandName() == "approvedChanged") {
                var user = args.get_dataItem();
                user.IsApproved = $($(args.get_itemElement()).find("input")[1]).attr("checked") == "checked";
                user.ProfileData = [];
     
                var clientManager = new Telerik.Sitefinity.Data.ClientManager();
                var serviceUrl = $('#' + '<%= hUsersServiceUrl.ClientID %>').val() + "/updateBasicInfo/" + user.UserID + "/?provider=Default";
                var urlParams = [];
                var keys = user.ProviderUserKey;
     
                clientManager.InvokePut(serviceUrl, urlParams, null, user, AssignUsersToRol_Success, AssignUsersToRol_Failure);
                HideRolesPanel();
                if (user.IsApproved) {
                    // open window to process user notification
                    openRadEditWindow(user.UserName);
                }
            }
        }
     
        function AssignUsersToRol_Success(result) {
        }
     
        function AssignUsersToRol_Failure(result) {
        }
     
        function GetCurrentProviderNameForUsersCreation() {
            var currentSelectedProviderName = $find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName;
            var defaultProviderIsAllowedToCreateUsers = false;
            var firstProviderAllowedToCreateUsers = "";
             
            //the current selecte provider is the default (the providers panel returns no specific provider).
            if (currentSelectedProviderName.trim() == "") {
                for (var prov in providersAbilities) {
                    //if we encounter a provider which is allowed to create users, keep it.
                    if ((providersAbilities[prov].AddUser == null) || (providersAbilities[prov].AddUser.toLowerCase() != "false")) {
                        if (firstProviderAllowedToCreateUsers == "") {
                            firstProviderAllowedToCreateUsers = providersAbilities[prov].ProviderName;
                        }
                        //is this the default provider? in that case the default provider is allowed to create users.
                        if (providersAbilities[prov].ProviderName == defaultMembershipProviderName) {
                            defaultProviderIsAllowedToCreateUsers = true;
                        }
                    }
                }
                //is the default provider allowed to create users? in that case, return the default provider name.
                if (defaultProviderIsAllowedToCreateUsers) {
                    return defaultMembershipProviderName;
                }
                //is the default provider NOT allowed to create users? in that case, return the first provider which is allowed to do so.
                else {
                    return firstProviderAllowedToCreateUsers;
                }
            }
            //we are not dealing with the default provider selection (an actual provider was chosen in the panel), just return it.
            else
                return currentSelectedProviderName;
        }
     
        /* ********************************************** list mode ********************************************** */
        function BindList(urlParams) {
     
            if (urlParams == null) {
                urlParams = [];
            }
     
            var providerName = $find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName;
            currentProviderName = providerName;
            SetButtonsAccordingToCurrentProvider();
            listBinder.set_provider(providerName);
            urlParams['roleId'] = _currentRoleID;
            urlParams['roleProvider'] = _currentRoleProviderName;
            urlParams['forAllProviders'] = providerName.length == 0;
            urlParams['filter'] = _currentFilter;
            listBinder.set_urlParams(urlParams);
            listBinder.DataBind();
        }
     
        function SetButtonsAccordingToCurrentProvider() {
            var curProvider = providerSelectorPanel.getSelectedProviderItem();
            var foundTheSelectedProvider = false;
            //locate the current provider
            for (var prov in providersAbilities) {
                if (providersAbilities[prov].ProviderName == curProvider.ProviderName) {
                     
                    //set visibility of the create button (visible if no ability specified, or if it's not set to false).
                    if ((typeof (providersAbilities[prov].AddUser) == typeof (undefined)) || (providersAbilities[prov].AddUser.toLowerCase() != "false")) {
                        btnCreate.show();
                    }
                    else {
                        btnCreate.hide();
                    }
     
                    //set visibility of the delete button (visible if no ability specified, or if it's not set to false).
                    if ((typeof (providersAbilities[prov].DeleteUser) == typeof (undefined)) || (providersAbilities[prov].DeleteUser.toLowerCase() != "false")) {
                        $('#deleteLink').show();
                        $('#deleteLinkDisabled').hide();
                    }
                    else {
                        $('#deleteLink').hide();
                        $('#deleteLinkDisabled').show();
                    }
     
                    //set visibility of the assign/unassign buttons (visible if no ability specified, or if it's not set to false).
                    if ((typeof (providersAbilities[prov].UpdateUser) == typeof (undefined)) || (providersAbilities[prov].UpdateUser.toLowerCase() != "false")) {
                        $('#assignLink, #unassignLink').show();
                        $('#assignLinkDisabled, #unassignLinkDisabled').hide();
                    }
                    else {
                        $('#assignLink, #unassignLink').hide();
                        $('#assignLinkDisabled, #unassignLinkDisabled').show();
                    }
                    foundTheSelectedProvider = true;
                    break;
                }
            }
            if (!foundTheSelectedProvider) {
                btnCreate.show();
                $('#deleteLink, #assignLink, #unassignLink').show();
                $('#deleteLinkDisabled, #assignLinkDisabled, #unassignLinkDisabled').hide();
            }
        }
     
        /* ********************************************** user manipulation ********************************************** */
     
        function deleteSelectedUsers() {
            var clientLabelManager = $find('<%= clientLabelManager.ClientID %>');
            var usernames = GetSelectedUsers();
            if (usernames.length > 0) {
                var confirmationMessage = (usernames.length > 1) ? clientLabelManager.getLabel('Labels', 'QuestionBeforeDeletingUsers') : clientLabelManager.getLabel('Labels', 'QuestionBeforeDeletingUser');
                if (confirm(confirmationMessage)) {
                    for (var usernameIndex = 0; usernameIndex < usernames.length; usernameIndex++) {
                        var key = [];
                        var user = usernames[usernameIndex];
                        key["ProviderUserKey"] = user.ProviderUserKey;
                        gridBinder.DeleteItem(key);
                    }
     
                    checkedItemsFollowupArray = [];
                    updateSelectedItemsCount();
                    Bind();
                    RebindUsersInRoles($find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName);
                    BindProvidersList(_currentRoleID, _currentRoleProviderName);
                }
            }
        }
     
        function ClientBinderDeleting(sender, args) {
            // cancel the automatic delete
            args.set_cancel(true);
            var clientLabelManager = $find('<%= clientLabelManager.ClientID %>');
     
            // prompt for confirmation
            var message = clientLabelManager.getLabel('Labels', 'QuestionBeforeDeletingUser');
            if (args.get_dataItem().UserID == loggedInUserID) {
                message = deleteLoggedInUserWarning;
                alert(message);
                return;
            }
            if (confirm(message)) {
                var providerName = args.get_dataItem().ProviderName;
                var oldProviderName = sender.get_provider();
                sender.set_provider(providerName);
                sender.DeleteItem(args.get_key());
                sender.set_provider(oldProviderName);
                Bind();
                RebindUsersInRoles($find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName);
                BindProvidersList(_currentRoleID, _currentRoleProviderName);
            }
        }
     
        /* ********************************************** role management ********************************************** */
        function ShowRolesPanel(command) {
            $('#rolesPanel').show();
            $('#commandButtons').hide();
            if (command == 'assign') {
                $('#assignButton').show();
                $('#unassignButton').hide();
                $('#assignLabel').show();
                $('#unassignLabel').hide();
            } else {
                $('#assignButton').hide();
                $('#unassignButton').show();
                $('#assignLabel').hide();
                $('#unassignLabel').show();
            }
        }
     
        function HideRolesPanel() {
            $('#rolesPanel').hide();
            $('#commandButtons').show();
        }
     
        function AssignUsersToRole() {
            PopulateSelectedItemIndexes();
     
            var data = GetUsersRolesObject(true, GetSelectedRoleProviderPair());
            if (data == null) {
                messageControl.showNegativeMessage('User could not be assigned to the role.');
                return;
            }
            messageControl.hide();
     
            var clientManager = new Telerik.Sitefinity.Data.ClientManager();
            var serviceUrl = $('#' + '<%= hUsersServiceUrl.ClientID %>').val();
            var urlParams = [];
            var keys = ["SaveUserRole"];
     
            clientManager.InvokePut(serviceUrl, urlParams, keys, data, AssignUsersToRole_Success, AssignUsersToRole_Failure);
            HideRolesPanel();
        }
     
        function UnassignUsersFromRole() {
            PopulateSelectedItemIndexes();
     
            var data = GetUsersRolesObject(false, GetSelectedRoleProviderPair());
            if (data == null) {
                messageControl.showNegativeMessage('User could not be unassigned from the role.');
                return;
            }
            messageControl.hide();
     
            var clientManager = new Telerik.Sitefinity.Data.ClientManager();
            var serviceUrl = $('#' + '<%= hUsersServiceUrl.ClientID %>').val();
            var urlParams = [];
            var keys = ["SaveUserRole"];
     
            clientManager.InvokePut(serviceUrl, urlParams, keys, data, UnassignUsersToRole_Success, UnassignUsersToRole_Failure);
            HideRolesPanel();
        }
     
        function AssignUsersToRole_Success(result) {
            Bind();
            RebindUsersInRoles($find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName);
        }
     
        function AssignUsersToRole_Failure(result) {
            messageControl.showNegativeMessage(result.Detail);
        }
     
        function UnassignUsersToRole_Success(result) {
            Bind();
            RebindUsersInRoles($find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName);
        }
     
        function UnassignUsersToRole_Failure(result) {
            messageControl.showNegativeMessage(result.Detail);
        }
     
        function GetUsersRolesObject(isAdding, roleProviderPair) {
            var users = GetSelectedUsers();
            var userRolesItems = [];
            for (userIter = 0; userIter < users.length; userIter++) {
                var originalRoles = users[userIter].RolesOfUser;
                var roleExists = RoleExists(roleProviderPair.RoleId, roleProviderPair.ProviderName, originalRoles);
                var newRoles = [];
                var addRemove = false;
                if (isAdding && !roleExists) {
                    newRoles = AddRole(roleProviderPair.RoleId, roleProviderPair.ProviderName, originalRoles);
                    addRemove = true;
                } else if (!isAdding && roleExists) {
                    newRoles = RemoveRole(roleProviderPair.RoleId, roleProviderPair.ProviderName, originalRoles);
                    addRemove = true;
                }
                if (addRemove) {
                    var userRoleItem = { 'UserName': users[userIter].UserName, 'UserId': users[userIter].ProviderUserKey, 'Roles': newRoles };
                    userRolesItems.push(userRoleItem);
                }
            }
            if (userRolesItems.length > 0)
                return userRolesItems;
            else
                return null;
        }
     
        function RoleExists(roleId, roleProvider, rolesCollection) {
            for (roleIter = 0; roleIter < rolesCollection.length; roleIter++) {
                if (rolesCollection[roleIter].RoleId == roleId && rolesCollection[roleIter].ProviderName == roleProvider) {
                    return true;
                }
            }
            return false;
        }
     
        function AddRole(roleId, roleProvider, rolesCollection) {
            rolesCollection.push({ 'RoleId': roleId, 'ProviderName': roleProvider });
            return rolesCollection;
        }
     
        function RemoveRole(roleId, roleProvider, rolesCollection) {
            var newRoles = [];
            for (roleIter = 0; roleIter < rolesCollection.length; roleIter++) {
                if (rolesCollection[roleIter].RoleId != roleId || rolesCollection[roleIter].ProviderName != roleProvider) {
                    newRoles.push({ 'RoleId': rolesCollection[roleIter].RoleId, 'ProviderName': rolesCollection[roleIter].ProviderName });
                }
            }
            return newRoles;
        }
     
        function GetSelectedRoleProviderPair() {
            var stringPair = $('#' + '<%= rolesList.ClientID %>').val().split('~');
            return { 'RoleId': stringPair[0], 'ProviderName': stringPair[1] };
        }
     
        /* ********************************************** searching ********************************************** */
     
        function ShowSearchPanel() {
            $("#closeSearchPanelLink").show();
            $("#findUsersLink").hide();
            $('#searchPanel').show();
            $("body").addClass("sfShowSearchPanel");
        }
     
     
     
        function CloseSearchPanel() {
            $("#closeSearchPanelLink").hide();
            $("#findUsersLink").show();
            $('#searchPanel').hide();
            $("body").removeClass("sfShowSearchPanel");
            var _oldFilter = _currentFilter;
            _currentFilter = "";
            $('#filterText').val('');
            //Rebind if we had a filter applied.
            if(_oldFilter)
                Bind();
             
        }
     
        function SearchUsers() {
            _currentFilter = $('#searchType').val() + ".StartsWith(%22" + escape($.trim($('#filterText').val())) + "%22)";
            Bind();
        }
     
        /* ********************************************** filtering ********************************************** */
     
        // this is a function called by command panel
        function LoadData(cmdPnl, args) {
            commandPanel = cmdPnl;
     
            _currentRoleID = ((args == null) ? "" : args.RoleId);
            _currentRoleProviderName = ((args == null) ? "" : args.ProviderName);
            _currentFilter = "";
            var urlParams = [];
            if (gridBinder != null) {
                // set properties so filter by role works
                if (args != null) {
                    urlParams['role'] = args.RoleName;
                    urlParams['filter'] = args.Filter;
                    _currentFilter = args.Filter;
                    urlParams['roleProvider'] = args.ProviderName;
                }
                else {
                    urlParams = null;
                }
                Bind(urlParams);
            }
            if (!(_currentRoleID == null))
                BindProvidersList(_currentRoleID, _currentRoleProviderName);
            else
                BindProvidersList(null, null);
        }
     
        /* ********************************************** dialogs ********************************************** */
     
        function OpenItem(sender, args) {
            var key = args.get_key();
            _currentUserId = key['ProviderUserKey'];
            _currentUserName = args.get_dataItem().UserName;
            editUserProviderName = args.get_dataItem().ProviderName;
            EditUser();
        }
     
        function EditorClosed(sender, args) {
            var arg = args.get_argument();
            if (arg == "redirectToLoginPage") {
                window.location.href = $('#' + '<%= hfLoginPageUrl.ClientID %>').val();
            }
            if (arg == 'rebind') {
                //HACK: fix 78949 grid items rebind ('GET' requests) fail with status 0 at Chrome
                //The most posible reason is that previous('PUT') request on save didnt completed it's callback.
                // At this situation all next requests have status 0.
                setTimeout('_onDataBind()', 0);
            }
        }
     
        function _onDataBind() {
            Bind();
            RebindUsersInRoles($find('<%= providerSelectorPanel.ClientID %>').getSelectedProviderItem().ProviderName);
            BindProvidersList(_currentRoleID, _currentRoleProviderName);
        }
     
        // new user dialog methods
        function NewUser() {
            newUserDialog.add_pageLoad(OnNewUserPageLoaded);
            newUserDialog.show();
            newUserDialog.maximize();
        }
     
        function OnNewUserPageLoaded() {
            newUserDialog.remove_pageLoad(OnNewUserPageLoaded);
            newUserDialog.add_show(OnNewUserShow);
            OnNewUserShow();
        }
     
        function OnNewUserShow() {
            newUserDialog.get_contentFrame().contentWindow.SetForm(GetCurrentProviderNameForUsersCreation());
        }
     
        // edit user dialog methods
        function EditUser() {
            editUserDialog.add_pageLoad(OnEditUserPageLoaded);
            editUserDialog.show();
            editUserDialog.maximize();
        }
     
        function OnEditUserPageLoaded() {
            editUserDialog.remove_pageLoad(OnEditUserPageLoaded);
            editUserDialog.add_show(OnEditUserShow);
            OnEditUserShow();
        }
     
        function OnEditUserShow() {
            editUserDialog.get_contentFrame().contentWindow.OpenUser(_currentUserId, _currentUserName, editUserProviderName);
        }
         
    </script>

10 posts, 0 answered