May
17
Written by:
Michael Washington
5/17/2012 5:59 AM
Visual Studio LightSwitch uses the standard ASP.NET Membership provider. This allows you to create web applications that can manage the LightSwitch users and roles. Integration with LightSwitch and ASP.NET has been covered in: Integrating LightSwitch Into An ASPNET Application To Provide Single Sign On. This article starts with the application created for that article, and adds an administration page that allows you to drag and drop roles, to assign and un-assign them for users.
The Application
The page allows us to choose an existing member in the drop down.
The Roles the user is in and not in will show.
We can drag and drop the Roles from each list to make a re-assignment.
(note: the Administrator role cannot be unassigned to prevent a person from accidently un-assigning themselves as an administrator)
The ASP.NET Application
We will start with the code in: Integrating LightSwitch Into An ASPNET Application To Provide Single Sign On.
This ASP.NET website application can be pointed to any LightSwitch application.
The ASP.NET application allows users to create accounts and to log in.
We enable this by pointing the web.config settings of the ASP.NET website application to the LightSwitch application.
For directions on how this is done see:
Integrating LightSwitch Into An ASPNET Application To Provide Single Sign On.
Also see this post by LightSwitch team member Valerie Andersen:
http://social.msdn.microsoft.com/Forums/en-US/lightswitchgeneral/thread/60c76dde-07dd-48f7-8aed-f7aec66c47d4
Also note that in addition to the web.config changes, you will also need to change the line in the Default.aspx file to point to your LightSwitch application.
Creating The Application
Open the code from: Integrating LightSwitch Into An ASPNET Application To Provide Single Sign On in Visual Studio 2010 (or higher).
You will see the files in the Solution Explorer in Visual Studio.
The sample we will create requires JQueryUI, JuiceUI and Wijmo. The easiest way to install the needed components is to use Nuget.
If you have Visual Studio 2010 and you do not have Nuget installed, install it from here:
http://nuget.org/
(note: if you have a higher version of Visual Studio, it may already be installed).
Open the Nuget console by selecting: Tools / Library Package Manager / Package Manager Console.
Type in:
Install-Package JuiceUI
and press the Enter key.
The files will install.
Next, type in :
Install-Package WijmoOpenJuiceUI
and press the Enter key.
When you refresh the files n the Solution Explorer, you will see that everything is installed (even the web.config has been updated).
The Admin.aspx Page
Next, we add a new page called Admin.aspx.
We use the following code for the markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head id="Head1" runat="server">
<title>User Management</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<style>
.draggable
{
width: 100px;
height: 50px;
}
.droppable
{
width: 150px;
height: 150px;
padding-bottom: 2.0em;
margin: 10px;
}
</style>
<style type="text/css">
.formdecorator label
{
display: block;
}
.formdecorator
{
list-style: none;
margin: 0;
padding: 0;
}
.formdecorator li
{
clear: both;
margin-bottom: 1em;
}
</style>
<div>
<h4>
<asp:Label ID="lblTitle" runat="server"
Text="Visual Studio LightSwitch Role Manager (JQueryUI/JuiceUI/Wijmo)" /></h4>
</div>
<asp:Panel ID="pnlApplication" runat="server">
<table class="formdecorator">
<tr>
<td style="vertical-align: top" colspan="3">
<strong>User:</strong><br>
<br></br>
<asp:DropDownList ID="ddlUsers" runat="server" AutoPostBack="True"
ClientIDMode="Static" DataTextField="Text" DataValueField="Text"
Width="200px">
</asp:DropDownList>
</br>
</td>
</tr>
<tr>
<td style="vertical-align: top" align="center">
</td>
<td style="vertical-align: top">
</td>
<td style="vertical-align: top" align="center">
</td>
</tr>
<tr>
<td style="vertical-align: top">
</td>
<td style="vertical-align: top">
</td>
<td style="vertical-align: top">
</td>
</tr>
</table>
<br />
<div id="Result">
</div>
</asp:Panel>
</form>
</body>
</html>
We use the following code for the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Configuration;
using System.Web.Services;
using System.Web.Security;
using Juice;
public partial class Admin : System.Web.UI.Page
{
public class DropDownText
{
public string Text { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated) // Logged in
{
if (!Page.IsPostBack)
{
if (Roles.IsUserInRole("Administrator"))
{
ShowUsers();
}
else
{
lblTitle.Text = "Only Administrators can use this application";
pnlApplication.Visible = false;
}
}
}
else // Not Logged In
{
Response.Redirect("~/Login.aspx");
}
}
#region ShowUsers
private void ShowUsers()
{
var colDropDownText = new List<DropDownText>();
foreach (var item in Membership.GetAllUsers())
{
colDropDownText.Add(new DropDownText() { Text = item.ToString() });
}
// Bind entire collection to GridView
ddlUsers.DataSource = colDropDownText;
ddlUsers.DataBind();
}
#endregion
}
When we run the application, log in, and navigate to the Admin.aspx page, we see a drop down list of the users.
Display The Roles
Next, we add the following markup to display the Roles a user is in (and not in):
<tr>
<td style="vertical-align: top">
<asp:Panel ID="UserRoles" CssClass="droppable ui-widget-header" runat="server" ClientIDMode="Static"
Height="100%">
<asp:DataList ID="dlRoles" runat="server" Width="100%">
<ItemTemplate>
<asp:Panel ID="DraggablePanel" runat="server" HorizontalAlign="Center">
<p style="border: thin solid #C0C0C0;
padding: 5px; margin: 5px; cursor: hand; background-color: #FFFFCC;
font-weight: bold; width: 85%;">
<%# Eval("Text")%></p>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</td>
<td style="vertical-align: top">
</td>
<td style="vertical-align: top">
<asp:Panel ID="AllRoles" CssClass="droppable ui-widget-header" runat="server" ClientIDMode="Static"
Height="100%">
<asp:DataList ID="dlAllRoles" runat="server" Width="100%">
<ItemTemplate>
<asp:Panel ID="DraggablePanel" runat="server" HorizontalAlign="Center">
<p style="border: thin solid #C0C0C0;
padding: 5px; margin: 5px; cursor: hand; background-color: #FFFFCC;
font-weight: bold; width: 85%;">
<%# Eval("Text")%></p>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</td>
</tr>
We use the following code behind to fill the lists:
#region DisplayRolesForUser
private void DisplayRolesForUser(string UserName)
{
var colRolesForUser = new List<DropDownText>();
foreach (var item in Roles.GetRolesForUser(UserName))
{
colRolesForUser.Add(new DropDownText() { Text = item.ToString() });
}
// Bind entire collection to GridView
dlRoles.DataSource = colRolesForUser;
dlRoles.DataBind();
// Query OData source -- Roles
var RolesResult = new List<DropDownText>();
foreach (var item in Roles.GetAllRoles())
{
if(!Roles.IsUserInRole(UserName,item))
{
RolesResult.Add(new DropDownText() { Text = item.ToString() });
}
}
// Bind entire collection to GridView
dlAllRoles.DataSource = RolesResult;
dlAllRoles.DataBind();
}
#endregion
When we run the application, the Roles display.
Drag And Drop
To enable drag, we add JuiceUI tags such as this:
<juice:Draggable ID="DraggableControl" TargetControlID="DraggablePanel" runat="server" Revert="true" />
To enable drop we also add JuiceUI tags such as this:
<juice:Droppable ID="Droppable1" TargetControlID="AllRoles" runat="server" />
We add the following JQuery to handle the drop and call the UpdateRole method (that will make the update to the user’s account):
$(function () {
$(".droppable").droppable("option", "drop", function (event, ui) {
var dropPanel = $(this).attr("id");
var userName = $("#ddlUsers option:selected").val();
// Add element to the drop panel
$(this).append(ui.draggable);
// Get the text of the draggable item
var roleName = "";
var ua = $.browser;
// Firefox uses textContent
// all others use innerText
if (ua.mozilla) {
roleName = ui.draggable[0].textContent;
}
else {
roleName = ui.draggable[0].innerText;
}
// Set the text of the parameter to be passed to the web method
var jsonText = JSON.stringify({ "DropPanel": dropPanel, "RoleName": roleName, "UserName": userName });
// Call the web method
$.ajax({
type: "POST",
url: "Admin.aspx/UpdateRole",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
We add the following static method to the code behind that will actually update the user’s account:
#region UpdateRole
[WebMethod]
public static string UpdateRole(string DropPanel, string RoleName, string UserName)
{
string strResponse = "";
Page objPage = new Page();
// Must be logged in
if (objPage.User.Identity.IsAuthenticated)
{
if (Roles.IsUserInRole("Administrator"))
{
if (DropPanel == "UserRoles") // Adding a role
{
try
{
Roles.AddUserToRole(UserName, RoleName);
}
catch (Exception ex)
{
strResponse = ex.Message;
}
}
else // Removing a role
{
try
{
Roles.RemoveUserFromRole(UserName, RoleName);
}
catch (Exception ex)
{
strResponse = ex.Message;
}
}
}
}
return strResponse;
}
#endregion
Prevent Administration Role From Being Dragged
We want to prevent an administrator from accidently removing themselves from the Administrator role.
We add a hidden panel that will not be draggable and a onItemDataBound event.
We use the following code for the onItemDataBound event:
#region dlRoles_ItemDataBound
protected void dlRoles_ItemDataBound(object sender, DataListItemEventArgs e)
{
// Get the data item
DropDownText objText = (DropDownText)e.Item.DataItem;
// Get an instance of the panels
Panel DraggablePanel = (Panel)e.Item.FindControl("DraggablePanel");
Panel pnlAdministrator = (Panel)e.Item.FindControl("pnlAdministrator");
// If the data item is Administrator...
if (objText.Text == "Administrator")
{
// Hide the draggable panel
DraggablePanel.Visible = false;
// Show the non draggable panel
pnlAdministrator.Visible = true;
}
}
#endregion
Adding Wijmo
To add the Wijmo Open for JuiceUI control that will provide a theming, we only need to add a single line such as this:
<wijmo:WijDropdown ID="Dropdown1" runat="server" TargetControlID="ddlUsers" />
When we run the application we see the dropdown has an attractive theme.
Download The Code
Download the code at: http://lightswitchhelpwebsite.com/Downloads.aspx
2 comment(s) so far...
Is there any plan to create this same tutorial but for the HTML client?
By Larry on
4/20/2013 8:38 PM
|
@Larry - Sorry, no.
By Michael Washington on
4/21/2013 5:00 AM
|