Hello All, We are going to start new batch from next week. message/call or mail us for more details.

4 September 2013

Membership is a self-standing feature in ASP.NET for authentication; it can be integrated with ASP.NET role management to provide authorization services for your site. Membership can also be integrated with user profile properties to provide application-specific customization that can be tailored to individual users.

In this article I will tell you how to use these properties. To use these properties follow these steps:-

Configure database

 
Create a new database.
Run aspnet_regsql.exe
(You can find aspnet_regsql.exe in C:\Windows\Microsoft.NET\Framework\v4.0.30319)
After running aspnet_regsql.exe a window appears like this
Membership, Roles, and the User Profile Properties in ASP.NET
Click on next->choose Configure SQL Server for Application services-> click next
Membership, Roles, and the User Profile Properties in ASP.NET
Membership, Roles, and the User Profile Properties in ASP.NET
A confirmation screen appears with setting summery, click next to confirm
Membership, Roles, and the User Profile Properties in ASP.NET
After clicking on next a screen is appears like this
Membership, Roles, and the User Profile Properties in ASP.NET
Click on finish.
Now your database is configured to use these properties.
Now create a new website from File->New->Website
Select ASP.NET Empty Website
Click on ok.
Membership, Roles, and the User Profile Properties in ASP.NET
Create three folders(Account,Product,User) in your project
Membership, Roles, and the User Profile Properties in ASP.NET
Add Web.sitemap file to setting menu items
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Web.sitemap
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
  <siteMapNode roles="*">
    <siteMapNode url="Home.aspx" title="Home"  description="Home" />
    <!--to allow only adminstrators-->
    <siteMapNode  title="User"  description="" roles="Administrator" >
      <siteMapNode url="~/User/Create.aspx" title="Create User"  description="Create User" />    
      <siteMapNode url="~/User/ViewAll.aspx" title="View All"  description="View All" />
    </siteMapNode>
    <!--to allow all users-->
    <siteMapNode    description="Product"  title="Product" roles="*">
      <siteMapNode url="~/Product/Create.aspx" title="Create" description="Create New Product"/>
      <siteMapNode  url="~/Product/Index.aspx" description="View All"  title="View All"/>
    </siteMapNode>
  </siteMapNode>
</siteMap>
Add a master page site.master, user interface of master page
Membership, Roles, and the User Profile Properties in ASP.NET
Code of site.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %>
 
<!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">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div  style=" background-color:#E0E0E0; height:80px;" >
    <span style="font-family:Calibri;font-size:large; font-weight:bold;color: Blue;margin-right:35%">
        <asp:Label ID="lblHeaderText" runat="server" Text="" Height=""></asp:Label></span>
    <span style="margin-left:75%; width:15%;font-family:Calibri;font-size:large;">
        <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
            <AnonymousTemplate>
                [ <a href="~/Account/Login.aspx" id="HeadLoginStatus" runat="server">Log In</a>
                ]
            </AnonymousTemplate>
            <LoggedInTemplate>
                Welcome <span>
                    <asp:LoginName ID="HeadLoginName" runat="server" />
                </span>! [
                <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out"
                    LogoutPageUrl="~/Account/Login.aspx" />
                ]
            </LoggedInTemplate>
        </asp:LoginView>
        </span>
        </div>
        <asp:Menu ID="Menu1" runat="server" DataSourceID="siteMapSource" BackColor="#B5C7DE"
            DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="Small" ForeColor="#284E98"
            Orientation="Horizontal" StaticSubMenuIndent="10px" Font-Bold="True"
            Font-Overline="False" Font-Strikeout="False" Height="30px" Width="40%">
            <DynamicHoverStyle BackColor="#284E98" ForeColor="White" />
            <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
            <DynamicMenuStyle BackColor="#B5C7DE" />
            <DynamicSelectedStyle BackColor="#507CD1" />
            <StaticHoverStyle BackColor="#284E98" ForeColor="White" />
            <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
            <StaticSelectedStyle BackColor="#507CD1" />
        </asp:Menu>
        <asp:SiteMapDataSource runat="server" ShowStartingNode="false" ID="siteMapSource" />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
       
    </div>
    </form>
</body>
</html>
 
Code of site.master.cs
using System;
using System.Web;
public partial class Site : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.User.IsInRole("Administrator"))
        {
            //change header when Adminstrator login
            lblHeaderText.Text = "User Registration And Product Entry";
        }
        else
        {
            //change header when User login
            lblHeaderText.Text = "Product Entry";
        }
    }
}
 
Add a page Login.aspx in Account folder, which User Interface is like this
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
 
<!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">
<head runat="server">
    <title>Login</title>
  
</head>
<body>
    <form id="form1" runat="server">
    <center>
        <div style="margin-top:220px;">
            <asp:Login ID="LoginCtrl" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8"
                BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
                Font-Size="0.8em" ForeColor="#333333" Height="124px" Width="276px" 
               >
                <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
                <LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px"
                     Font-Names="calibari" Font-Size="1.0em" ForeColor="#284775" />
                <TextBoxStyle Font-Size="1.0em" />
                <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em" ForeColor="White" />
            </asp:Login>
        </div>
    </center>
    </form>
</body>
</html>
 
Code of Login.cs
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;
 
public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
   
}
 
Add four pages(Create.aspx,Edit.aspx,Index.aspx,Delete.aspx) in product folder.These pages are visible to both user and administrators.
User Interface of Create.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Create.aspx.cs" Inherits="AddNewProduct" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="../css/StyleSheet.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="margin-top: 5%; margin-left: 20%; margin-right: 20%;">
        <fieldset style="border-color: Black;">
            <legend style="left: 0px; font-family: Calibri;">Add New Product</legend>
            <table width="100%" cellpadding="5%" style="margin-left: 15%; margin-right: 20%;">
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Style="width: 200px; outline: none; border: 1px solid black;"
                            MaxLength="50"></asp:TextBox>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtName"
                            ErrorMessage="*" ToolTip="Alphabets Only!" ValidationExpression="^[a-zA-Z]+$"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                            ErrorMessage="*" ToolTip="Name can't Blank!"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        Description:
                    </td>
                    <td>
                        <asp:TextBox ID="txtDesc" runat="server" Style="width: 200px; outline: none; border: 1px solid black;"
                            MaxLength="100" TextMode="MultiLine"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnCreate" runat="server" Text="Save" OnClick="btnCreate_Click" Style="border: 1px solid black;
                            font-family: Verdana; margin-left: 25%; margin-top: 10px;" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center">
                        <asp:Label ID="lblMsg" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
</asp:Content>
 
Code of Create.cs
using System;
public partial class AddNewProduct : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        ProductCRUD crudClass = new ProductCRUD();
        bool res = crudClass.CreateProduct(txtName.Text, txtDesc.Text);
 
        lblMsg.Text = res ? "Record saved!" : "Unable to save record!";
        txtName.Text = string.Empty;
        txtDesc.Text = string.Empty;
    }
}
 
User interface for Edit.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Edit.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Edit.aspx.cs" Inherits="Product_Edit" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <script language="javascript" type="text/javascript">
 
        function SetButtonStatus(sender) {
            var name = document.getElementById('<%=txtName.ClientID %>');
            var desc = document.getElementById('<%=txtDesc.ClientID %>');
 
            if ((sender.value.length >= 1 && name.defaultValue != name.value) || (sender.value.length >= 1 && desc.defaultValue != desc.value))
                document.getElementById('<%=btnSave.ClientID %>').disabled = false;
            else
                document.getElementById('<%=btnSave.ClientID %>').disabled = true;
        }
  
 
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="margin-top: 5%; margin-left: 20%; margin-right: 20%;">
        <fieldset style="border-color: Black;">
            <legend style="left: 0px; font-family: Calibri;">Add New Product</legend>
            <table width="100%" cellpadding="5%" style="margin-left: 15%; margin-right: 20%;">
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        <input id="txtName" type="text" runat="server" onkeyup="SetButtonStatus(this)" style="width: 200px;
                            outline: none; border: 1px solid black;" maxlength="50" />
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtName"
                            ErrorMessage="*" ToolTip="Alphabets Only!" ValidationExpression="^[a-zA-Z]+$"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
                            ErrorMessage="*" ToolTip="Name can't Blank!"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        Description:
                    </td>
                    <td>
                        <textarea id="txtDesc" cols="5" rows="2" runat="server" style="width: 200px; outline: none;
                            border: 1px solid black;" onkeyup="SetButtonStatus(this)" maxlength="50"></textarea>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" Enabled="false"
                            Style="border: 1px solid black; font-family: Verdana; margin-left: 25%; margin-top: 10px;" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center">
                        <asp:Label ID="lblMsg" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
</asp:Content>
 
Code of Edit.cs
using System;
using System.Web.UI;
 
public partial class Product_Edit : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            try
            {
                ProductCRUD crudCls = new ProductCRUD();//create object of global class
                Product product = null;
 
                if (crudCls.Search(Request.QueryString["prodId"].ToString(), out product))//search product
                {   
                    //setting textboxes value
                    txtName.Value = product.Name;
                    txtDesc.Value = product.Description;
                    crudCls.dr.Close();
                }
 
               
            }
            catch (Exception)
            {
                Response.Redirect("~/Home.aspx");
            }
        }
    }
  
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            ProductCRUD crudCls = new ProductCRUD();
            if (crudCls.UpdateProduct(Request.QueryString["prodId"].ToString(), txtName.Value.Trim(), txtDesc.Value.Trim()))//Update Product
            {
                Response.Redirect("~/Product/Index.aspx?msg=Record Updated!");
            }
            else
            {
                Response.Redirect("~/Product/Index.aspx?msg=Record Not Updated!&lblColor=Red");
            }
        }
        catch (Exception)
        {
            Response.Redirect("~/Product/Index.aspx?msg=Record Not Updated!&lblColor=Red");
        }
    }
}
 
User Interface of Index.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Index.aspx
 
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Product_Index" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="margin-top:5%;margin-left:20%;margin-right:20%;">
        <fieldset style="border-color:Black;">
            <legend style="font-family:Calibri" >Product List</legend>
            <center>
            <div><asp:Label ID="lblMsg" Text="" runat="server" ForeColor="Green"></asp:Label></div>
                <div>
                    <asp:GridView ID="GridViewProduct" runat="server" CellPadding="4" ForeColor="#333333"
                        GridLines="None" Width="100%" AutoGenerateColumns="False" DataKeyNames="ProductId"
                        DataSourceID="ProductSqlDataSource">
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                            <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
                            <asp:TemplateField HeaderText="Action">
                                <ItemTemplate>
                                    <asp:HyperLink ID="HlEdit" runat="server" NavigateUrl='<%#"~/Product/Edit.aspx?prodId="+Eval("ProductId")  %>'>Edit</asp:HyperLink>
                                    |<asp:HyperLink ID="HLDelete" runat="server" NavigateUrl='<%#"~/Product/Delete.aspx?prodId="+Eval("ProductId")  %>'>Delete</asp:HyperLink>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <EditRowStyle BackColor="#999999" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                    </asp:GridView>
                    <asp:SqlDataSource ID="ProductSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:MRU_ProductConnectionString %>"
                        SelectCommand="SELECT * FROM [Product]"></asp:SqlDataSource>
                </div>
            </center>
        </fieldset>
    </div>
</asp:Content>
 
Code of Index.cs
using System;
using System.Drawing;
 
public partial class Product_Index : System.Web.UI.Page
{
  
      
    protected void Page_Load(object sender, EventArgs e)
    {
       
        try
        {          
            lblMsg.Text = Request.QueryString["msg"].ToString();
            lblMsg.ForeColor = Color.FromName(Request.QueryString["lblColor"].ToString());
        }
        catch { }
    }
}
 
User Interface of Delete.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Delete.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Delete.aspx.cs" Inherits="Product_DeleteProduct" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  <div style="margin-top:5%;margin-left:20%;margin-right:20%;">
    <fieldset style="border-color:Black" >
    <legend>Confirmation</legend>
        <center>Are you sure to delete
        <asp:Literal ID="ltrlProName" runat="server"></asp:Literal>
        <asp:Button ID="btnYes" runat="server" Text="Yes" onclick="btnYes_Click" style="border: 1px solid black; font-family: Verdana;" />
        <asp:Button ID="btnNo" runat="server" Text="No" onclick="btnNo_Click" style="border: 1px solid black; font-family: Verdana; " />
        </center>
         </fieldset>
    </div>
</asp:Content>
 
Code of Delete.cs
using System;
 
public partial class Product_DeleteProduct : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ProductCRUD crudCls = new ProductCRUD();//create global class object
            Product product = null;
 
            if (crudCls.Search(Request.QueryString["prodId"].ToString(), out product))//search product
            {
 
                ltrlProName.Text = product.Name + "?";
 
            }
        }
        catch (Exception ee)
        {
            Response.Write(ee.Message);
        }
    }
 
    protected void btnYes_Click(object sender, EventArgs e)
    {
        try
        {
            ProductCRUD crudCls = new ProductCRUD();
            if (crudCls.DeleteProduct(Request.QueryString["prodId"].ToString()))
            {
                Response.Redirect("~/Product/Index.aspx?msg=Product Deleted!&lblColor=Green");
            }
            else
            {
                Response.Redirect("~/Product/Index.aspx?msg=Error!Product Not Deleted.&lblColor=Red");
            }
        }
        catch (Exception ee)
        {
            Response.Write(ee.Message);
        }
    }
    protected void btnNo_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Product/Index.aspx");
    }
}
 
 
Make four pages(Create.aspx,Delete.aspx,Edit.aspx,ViewAll.aspx) in user folder.These pages are only visible to Administrators.
User Interface of Create.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Create.aspx.cs" Inherits="Account_Create" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
   
 
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="margin-top:5%;margin-left:20%;margin-right:20%;">
<fieldset   style="border-color:Black;" >
          <legend style="font-family:Calibri">Create New User</legend>
            <table width="100%" cellpadding="5%" style="margin-left:15%; margin-right:20%;" >
                <tr >
                    <td > Name</td>
                    <td> <asp:TextBox ID="txtName" runat="server"
                            Style="width: 200px; outline: none; border: 1px solid black;" MaxLength="50"></asp:TextBox>
               <asp:RegularExpressionValidator ID="REVName" runat="server"
                    ControlToValidate="txtName" ErrorMessage="*" ToolTip="Alphabets Only!"
                    ValidationExpression="^[a-zA-Z]+$"></asp:RegularExpressionValidator>
                <asp:RequiredFieldValidator ID="RFVName" runat="server"
                    ControlToValidate="txtName" ErrorMessage="*" ToolTip="Name can't Blank!"></asp:RequiredFieldValidator></td>
                </tr>
                <tr  >
                    <td>Password:</td>
                    <td><asp:TextBox ID="txtPass" runat="server"
                            Style="width: 200px; outline: none; border: 1px solid black;" MaxLength="15"
                            TextMode="Password"></asp:TextBox>            
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                    ControlToValidate="txtPass" ErrorMessage="*" ToolTip="Password can't Blank!"></asp:RequiredFieldValidator>
                       </td>
                </tr>
                <tr  >
                    <td>Confirm Password:</td>
                    <td><asp:TextBox ID="txtCnfPass" runat="server"
                    Style="width: 200px; outline: none; border: 1px solid black;"
                    TextMode="Password" MaxLength="15"></asp:TextBox>
              
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                    ControlToValidate="txtCnfPass" ErrorMessage="*" ToolTip="Confirm Password can't Blank!"></asp:RequiredFieldValidator>
                        <asp:CompareValidator ID="CompareValidator1" runat="server"
                            ControlToCompare="txtCnfPass" ControlToValidate="txtPass" ErrorMessage="*"
                            ToolTip="Both passwords are not same!"></asp:CompareValidator>
                    </td>
                </tr>
                <tr  >
                    <td>Email:</td>
                    <td><asp:TextBox ID="txtEmail" runat="server"
                            Style="width: 200px; outline: none; border: 1px solid black;" MaxLength="50"></asp:TextBox>
              
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                    ControlToValidate="txtEmail" ErrorMessage="*" ToolTip="Email can't Blank!"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="REVEmail" runat="server"
                            ControlToValidate="txtEmail" ErrorMessage="*"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr  >
                    <td>User Type</td>
                    <td>
                        <asp:RadioButton ID="RBAdmin" runat="server" Checked="True"
                            GroupName="RBUserType" Text="Administrator" />
                        <asp:RadioButton ID="RBUser" runat="server" GroupName="RBUserType"
                            Text="User" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2"><asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" style="border: 1px solid black; font-family: Verdana; margin-left: 25%; margin-top: 10px;"/></td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center">
                        <asp:Label ID="lblMsg" runat="server" ForeColor="Green"></asp:Label>
                    </td>
                </tr>
          </table>
            </fieldset>
</div>
</asp:Content>
 
Code of Create.cs
using System;
using System.Web.Security;
using System.Drawing;
 
public partial class Account_Create : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (RBAdmin.Checked == true)
            {
               //create a new user
                Membership.CreateUser(txtName.Text.Trim(), txtPass.Text, txtEmail.Text.Trim());
                //add role for new user
                Roles.AddUserToRole(txtName.Text.Trim(), "Administrator");
                lblMsg.Text = "Administrator Created Sucessfully!";
                txtEmail.Text = string.Empty;
                txtName.Text = string.Empty;
                txtPass.Text = string.Empty;
                txtCnfPass.Text = string.Empty;
            }
            else if (RBUser.Checked == true)
            {
               //create a new user
                Membership.CreateUser(txtName.Text.Trim(), txtPass.Text, txtEmail.Text.Trim());
               //add role for new user
                Roles.AddUserToRole(txtName.Text.Trim(), "User");
                lblMsg.Text = "User Created Sucessfully!";
                txtEmail.Text = string.Empty;
                txtName.Text = string.Empty;
                txtPass.Text = string.Empty;
                txtCnfPass.Text = string.Empty;
            }
        }
        catch(Exception)
        {
            lblMsg.ForeColor = Color.Red;
            lblMsg.Text = "Error!Unable to Save Records!";
        }
    }
   
 
}
 
User interface of Delete.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Delete.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Delete.aspx.cs" Inherits="User_Delete" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="margin-top:5%;margin-left:20%;margin-right:20%;">
    <fieldset style="border-color:Black" >
    <legend>Confirmation</legend>
        <center>Are you sure to delete
        <asp:Literal ID="ltrlUserName" runat="server"></asp:Literal>
        <asp:Button ID="btnYes" runat="server" Text="Yes" onclick="btnYes_Click" style="border: 1px solid black; font-family: Verdana;" />
        <asp:Button ID="btnNo" runat="server" Text="No" onclick="btnNo_Click" style="border: 1px solid black; font-family: Verdana; " />
        </center>
         </fieldset>
    </div>
  
</asp:Content>
 
Code of Delete.cs
using System;
using System.Web.Security;
 
public partial class User_Delete : System.Web.UI.Page
{
 
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ltrlUserName.Text = Request.QueryString["name"].ToString() + "?";
        }
        catch
        {
            Response.Redirect("~/User/ViewAll.aspx");
        }
    }
    protected void btnYes_Click(object sender, EventArgs e)
    {
        try
        {
           //get the role of current user
                string[] roles = Roles.GetRolesForUser(User.Identity.Name);
                if (roles[0] == "Administrator")
                {
                    Response.Redirect("~/User/ViewAll.aspx?msg=You Can't Delete Adminstrator!");
                }
                else
                {
                 //delete user by user name
                    Membership.DeleteUser(Request.QueryString["name"].ToString(), true);
                    Response.Redirect("~/User/ViewAll.aspx?msg=Record Deleted Sucessfully!&lblColor=Green");
                }
           
        }
        catch (Exception ee)
        {
            Response.Write(ee.Message);
        }
    }
 
 
    protected void btnNo_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/User/ViewAll.aspx");
    }
}
 
 
User interface of Edit.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Edit.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Edit.aspx.cs" Inherits="User_Edit" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
 
    <script language="javascript" type="text/javascript">
 
        function SetButtonStatus(sender, target) {
            var email = document.getElementById('<%=txtEmail.ClientID %>');
 
            if ((sender.value.length >= 1 && sender.defaultValue != sender.value))
                document.getElementById('<%=btnSave.ClientID %>').disabled = false;
            else
                document.getElementById('<%=btnSave.ClientID %>').disabled = true;
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="margin-top: 5%; margin-left: 20%; margin-right: 20%;">
        <fieldset style="border-color: Black;">
            <legend style="font-family: Calibri">Edit User Details</legend>
            <table width="100%" cellpadding="5%" style="margin-left: 15%; margin-right: 20%;">
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" Style="width: 200px; outline: none; border: 1px solid black;"
                            MaxLength="50" Enabled="False"></asp:TextBox>
                        <asp:RegularExpressionValidator ID="REVName" runat="server" ControlToValidate="txtName"
                            ErrorMessage="*" ToolTip="Alphabets Only!" ValidationExpression="^[a-zA-Z]+$"></asp:RegularExpressionValidator>
                        <asp:RequiredFieldValidator ID="RFVName" runat="server" ControlToValidate="txtName"
                            ErrorMessage="*" ToolTip="Name can't Blank!"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        Email:
                    </td>
                    <td>
                        <input id="txtEmail" type="text" runat="server" style="width: 200px; outline: none;
                            border: 1px solid black;" onkeyup="SetButtonStatus(this,'btnSave')" maxlength="50" />
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtEmail"
                            ErrorMessage="*" ToolTip="Email can't Blank!"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="REVEmail" runat="server" ControlToValidate="txtEmail"
                            ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            ToolTip="Invalid Email!"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" Enabled="False"
                            Style="border: 1px solid black; font-family: Verdana; margin-left: 25%; margin-top: 10px;" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align: center">
                        <asp:Label ID="lblMsg" runat="server" ForeColor="Green"></asp:Label>
                    </td>
                </tr>
            </table>
        </fieldset>
    </div>
</asp:Content>
 
Code of Edit.cs
using System;
using System.Web.Security;
 
public partial class User_Edit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                MembershipUser user = Membership.GetUser(Request.QueryString["name"].ToString());//get user details
                //setting user details in textboxes
                txtName.Text = user.UserName;             
                txtEmail.Value = user.Email;
              
            }
        }
        catch
        {
            Response.Redirect("~/User/ViewAll.aspx");
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string strEmail;
        strEmail =  txtEmail.Value;
 
        try
        {
            MembershipUser user = Membership.GetUser(Request.QueryString["name"].ToString());
            user.Email = strEmail;
            Membership.UpdateUser(user);//update user details
           Response.Redirect("~/User/ViewAll.aspx?msg=Record updated sucessfully!");
           
        }
        catch
        {
            lblMsg.Text = "Error!Unable to update record!";
        }
    }
    protected void txtEmail_TextChanged(object sender, EventArgs e)
    {
        btnSave.Enabled=true;
    }
}
 
 
User Interface of ViewAll.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Code of ViewAll.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="ViewAll.aspx.cs" Inherits="User_Delete" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="margin-top: 5%; margin-left: 20%; margin-right: 20%;">
        <fieldset style="border-color: Black;">
            <legend style="font-family: Calibri">Users List</legend>
            <center>
    <asp:Label ID="lblMsg" Text="" runat="server" ForeColor="Green"></asp:Label>
    <asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" Width="100%"
        cellpadding="4" datakeynames="userid" datasourceid="sqldatasource1"
        forecolor="#333333" gridlines="none">
        <alternatingrowstyle backcolor="white" forecolor="#284775" />
        <columns>
            <asp:boundfield datafield="username" headertext="username"
                sortexpression="username" />
            <asp:boundfield datafield="email" headertext="email" sortexpression="email" />
            <asp:boundfield datafield="createdate" headertext="createdate"
                sortexpression="createdate" />
            <asp:templatefield headertext="action">
                <itemtemplate>
                    <asp:hyperlink id="hledit" runat="server" navigateurl='<%#"~/user/Edit.aspx?name="+Eval("username")  %>' >Edit</asp:hyperlink>
                    |<asp:hyperlink id="hldelete" runat="server" navigateurl='<%#"~/user/Delete.aspx?name="+Eval("username")  %>'>Delete</asp:hyperlink>
                </itemtemplate>
            </asp:templatefield>
        </columns>
        <editrowstyle backcolor="#999999" />
        <footerstyle backcolor="#5d7b9d" font-bold="true" forecolor="white" />
        <headerstyle backcolor="#5d7b9d" font-bold="true" forecolor="white" />
        <pagerstyle backcolor="#284775" forecolor="white" horizontalalign="center" />
        <rowstyle backcolor="#f7f6f3" forecolor="#333333" />
        <selectedrowstyle backcolor="#e2ded6" font-bold="true" forecolor="#333333" />
        <sortedascendingcellstyle backcolor="#e9e7e2" />
        <sortedascendingheaderstyle backcolor="#506c8c" />
        <sorteddescendingcellstyle backcolor="#fffdf8" />
        <sorteddescendingheaderstyle backcolor="#6f8dae" />
    </asp:gridview>
    </center>
        </fieldset>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MRU_ProductConnectionString %>"
            SelectCommand="SELECT [UserName], [Email], [CreateDate], [UserId] FROM [vw_aspnet_MembershipUsers]">
        </asp:SqlDataSource>
    </div>
</asp:Content>
 
Code of ViewAll.cs
using System;
using System.Drawing;
 
public partial class User_Delete : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            lblMsg.Text = Request.QueryString["msg"].ToString();
            lblMsg.ForeColor = Color.FromName(Request.QueryString["lblColor"].ToString());
        }
        catch { }
    }
}
 
Now make a home page, which is outside of these folders.
User Interface of Home.aspx
(Home.aspx is accessible to all users and administrators)
Membership, Roles, and the User Profile Properties in ASP.NET
Code of Home.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <center><asp:Image ImageUrl="~/image/homepage.jpg"  runat="server"
        Width="50%"/>
   </center>
   
</asp:Content>
 
Code of Home.aspx
using System;
 
public partial class Home : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
}
 
Code of web.config
<?xml version="1.0"?>
 
<configuration>
  <appSettings/>
  <connectionStrings>
    <add name="MRU_ProductConnectionString" connectionString="Data Source=(local);Initial Catalog=MRU_Product;User ID=sa;Password=abc"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <!--setting access to folders-->
  <location path="user">
    <system.web>
      <authorization>
        <allow roles="Administrator"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="Product">
    <system.web>
      <authorization>
        <allow roles="Administrator"/>
        <allow roles="User"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="Home.aspx">
    <system.web>
      <authorization>
        <allow roles="Administrator"/>
        <allow roles="User"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <system.web>
    <!--authentication setting-->
    <authentication mode="Forms">
      <forms  loginUrl="~/Account/Login.aspx" defaultUrl="~/Home.aspx" timeout="2880"/>
    </authentication>
    <membership>
      <providers>
        <clear />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MRU_ProductConnectionString" applicationName="MRU_Product"
          enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" />
      </providers>
    </membership>
    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="MRU_ProductConnectionString" applicationName="MRU_Product"/>
      </providers>
    </profile>
    <!--sitemap setting-->
    <siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
      <providers>
        <add name="XmlSiteMapProvider"
          description="Default SiteMap provider."
          type="System.Web.XmlSiteMapProvider "
          siteMapFile="Web.sitemap"
          securityTrimmingEnabled="true" />
      </providers>
    </siteMap>
    <!--to enable role-->
    <roleManager enabled="true" defaultProvider="sqlRoleManager">
      <providers>
        <clear />
        <add name="sqlRoleManager" type="System.Web.Security.SqlRoleProvider" connectionStringName="MRU_ProductConnectionString" applicationName="MRU_Product"  />
      </providers>
    </roleManager>
    <compilation debug="true" targetFramework="4.0"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
</configuration>
Here all things are done.

Output screens:

 Login.aspx
Membership, Roles, and the User Profile Properties in ASP.NET
Home.aspx (after Administrator Login)
On Administrator login you can see that both user and product menus are visible.
Membership, Roles, and the User Profile Properties in ASP.NET
Home.aspx (after User Login)
On User Login only product menu is visible.
Membership, Roles, and the User Profile Properties in ASP.NET

No comments:

Post a Comment