Skip to content

Instantly share code, notes, and snippets.

@JosiahSiegel
Last active June 2, 2017 17:18
Show Gist options
  • Save JosiahSiegel/9008348 to your computer and use it in GitHub Desktop.
Save JosiahSiegel/9008348 to your computer and use it in GitHub Desktop.
#ASP .NET Create hierarchically sorted roles page
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="DisplayRoles.aspx.cs" Inherits="MyProject.Pages.DisplayRoles" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="mainDiv" runat="server">
<div id="userDiv" runat="server">
<asp:Label ID="LabelUsername" runat="server" Text="Label"><b>Username</b>&nbsp</asp:Label>
<asp:TextBox ID="TextBoxUserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBoxUserName" ErrorMessage="Username is required."
ValidationGroup="AllValidations" SetFocusOnError="True" CssClass="failureNotification">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexpDate" runat="server"
ErrorMessage="Employee code must be three alpha-numeric characters long" Text="*" ControlToValidate="TextBoxUserName"
ValidationExpression="^[a-zA-Z0-9]{3}$" ValidationGroup="AllValidations" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid Username." Text="*" ValidationGroup="AllValidations"
ControlToValidate="TextBoxUserName" SetFocusOnError="true"
CssClass="failureNotification" onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Button ID="ButtonSearch" runat="server" Text="Search" onclick="ButtonSearch_Click" ValidationGroup="AllValidations" />
</div>
<div id="RolesDiv" runat="server">
<fieldset>
<legend>Assigned Roles</legend>
<asp:CheckBoxList ID="CheckBoxListRoles" runat="server"></asp:CheckBoxList>
</fieldset>
<asp:Button ID="ButtonUpdate" runat="server" Text="Update" onclick="ButtonUpdate_Click" />
</div>
</div>
<div id="DoneDiv" runat="server">
<asp:Button ID="ButtonDone" runat="server" Text="Done" onclick="ButtonDone_Click" />
</div>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using MyProject.DAO.TableAdapters;
namespace MyProject.Pages
{
public partial class DisplayRoles : System.Web.UI.Page
{
Label lblNotification = new Label();
bool isValidUser = false;
protected void Page_Load(object sender, EventArgs e)
{
// Hide roles assignment
RolesDiv.Visible = false;
// Hide done button
DoneDiv.Visible = false;
}
//Validate username entered exists on DB
private Boolean validateUsername(String userName)
{
UsersTableAdapter userTableAdapter = new UsersTableAdapter();
if ((int)userTableAdapter.GetUser(userName) > 0)
{
return true;
}
return false;
}
//Populate Roles dropdown with all roles
private void PopulateRoles(String userName)
{
String[] roleNames = Roles.GetAllRoles();
CheckBoxListRoles.Items.Clear();
foreach (String roleName in roleNames)
{
ListItem roleListItem = new ListItem();
//check if the rolename starts with a letter
bool roleStartsLetter = char.IsLetter(roleName.FirstOrDefault());
if (roleStartsLetter == false)
{
if (roleName[2] != '0')
{
roleListItem.Text = " " + roleName.Substring(3);
}
else
{
roleListItem.Text = roleName.Substring(3);
roleListItem.Attributes.Add("Style", "color: blue;");
}
roleListItem.Selected = Roles.IsUserInRole(userName, roleName.Substring(3));
CheckBoxListRoles.Items.Add(roleListItem);
}
else if (roleName == "Administrator")
{
roleListItem.Text = roleName;
roleListItem.Attributes.Add("Style", "color: blue;");
roleListItem.Selected = Roles.IsUserInRole(userName, roleName);
CheckBoxListRoles.Items.Add(roleListItem);
}
}
RolesDiv.Visible = true;
}
//Update roles that user check or uncheck
private void UpdateRoles(String userName)
{
foreach (ListItem checkBox in CheckBoxListRoles.Items)
{
// if selected and user is not in role, add role to user
if (checkBox.Selected && !Roles.IsUserInRole(userName, checkBox.Text))
{
Roles.AddUserToRole(TextBoxUserName.Text, checkBox.Text);
}
// if not selected and user is in role, remove role from user
if (!checkBox.Selected && Roles.IsUserInRole(TextBoxUserName.Text, checkBox.Text))
{
Roles.RemoveUserFromRole(TextBoxUserName.Text, checkBox.Text);
}
}
int count = 0;
Label lblNotification = (Label)Master.FindControl("labelNotification");
lblNotification.Text = "Roles updated successfully. <br/><br/>";
lblNotification.Text += "Roles assigned to user " + TextBoxUserName.Text + ":";
//Display roles
lblNotification.Text += "<ul>";
foreach (ListItem checkBox in CheckBoxListRoles.Items)
{
if (checkBox.Selected)
{
count++;
lblNotification.Text += "<li>" + checkBox.Text + "</li>";
}
}
if (count < 1)
{
lblNotification.Text += "<li>None</li>";
}
lblNotification.Text += "</ul>";
Master.FindControl("notificationDiv").Visible = true;
DoneDiv.Visible = true;
//hide everything everything else
mainDiv.Visible = false;
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
if (isValidUser)
{
PopulateRoles(TextBoxUserName.Text);
}
}
protected void ButtonUpdate_Click(object sender, EventArgs e)
{
UpdateRoles(TextBoxUserName.Text);
}
protected void ButtonDone_Click(object sender, EventArgs e)
{
mainDiv.Visible = true;
// Hide notification box
Master.FindControl("notificationDiv").Visible = false;
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (!validateUsername(TextBoxUserName.Text))
{
RolesDiv.Visible = false;
args.IsValid = false;
isValidUser = false;
}
else
{
isValidUser = true;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Caching;
using System.Diagnostics;
using System.Net;
using MyProject.WSClient;
using MyProject.App_Codes;
using log4net;
using System.Threading;
namespace MyProject
{
public class Global : System.Web.HttpApplication
{
private static readonly ILog log = LogManager.GetLogger(typeof(Global));
// private const string DummyCacheItemKey = "123456";
//TODO: make this the login page
private static string DummyPageUrl = ((CustomConfig)System.Configuration.ConfigurationManager.GetSection(
"customConfigGroup/customConfig")).PingUrl;
void Application_Start(object sender, EventArgs e)
{
//log4net.Config.XmlConfigurator.Configure();
log.Debug("application start");
// Code that runs on application startup
if (!Roles.RoleExists("Menu"))
{
Roles.CreateRole("Menu");
}
if (!Roles.RoleExists("SubMenu"))
{
Roles.CreateRole("SubMenu");
}
//Roles added with index sorting
if (!Roles.RoleExists("010Menu"))
{
Roles.CreateRole("010Menu");
}
if (!Roles.RoleExists("011SubMenu"))
{
Roles.CreateRole("011SubMenu");
}
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment