Friday, 8 March 2013

SQL Role manager - Custom Login, Roles stored in SQL Table


Web.config
<configuration>
  <connectionStrings>
    <add name="SqlRoleManagerConnection" 
         connectionString="Data Source=sqlinstance;
                          Initial Catalog=dbname;Integrated Security=SSPI;">
 <!--
    <add name="SimpleTopupConnection" connectionString="Server=localhost\SQLExpress;Database=SimpleTopup; User ID=masuddb; Password=Simple!1; Trusted_Connection=False;" providerName="System.Data.SqlClient"/>
    -->

    <add name="MyDbConnectionString" connectionString="Server=svrcis; Database=WebRegister; User Id=WebRegister; Password=poker; Trusted_Connection=false;" 
         providerName="System.Data.SqlClient"/>

  </connectionStrings>
</configuration>

<roleManager enabled="true" defaultProvider="SqlRoleManager">
  <providers>
    <add name="SqlRoleManager" 
         type="System.Web.Security.SqlRoleProvider"
         connectionStringName="SqlRoleManagerConnection"
         applicationName="MyApplication" />
  </providers>
</roleManager>


Login.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_Login : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void createNewUserButton_Click(object sender, EventArgs e)
    {
        string userName, password, email, securityQuestoin, securityAnswer, country, gender;
        userName = userNameTextBox.Text.ToString();
        password = passwordTextBox.Text.ToString();
        email = emailTextBox.Text.ToString();
        securityQuestoin = questionDropDownBox.Text.ToString();
        securityAnswer = answerDropDownBox.Text.ToString();
        country = countryDropDownBox.Text.ToString();
        gender = genderDropDownBox.Text.ToString();
        int age = Int16.Parse( ageTextBox.Text.ToString());
        UserDetailsAccess.UserAdd(userName, password, email, securityQuestoin, securityAnswer, country, gender, age);
    }

    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        Boolean bauthenticated = false;
        bauthenticated = UserDetailsAccess.IsValidUser(Login1.UserName, Login1.Password);
        if (bauthenticated)
        {
            e.Authenticated = true;
            //save the productId into session variable to use it later on
            Session["loggedInUserName"] = Login1.UserName;
        }

        else
        {
            e.Authenticated = false;
        }
    }
}




UserDetailsAccess.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;

/// <summary>
/// Summary description for CreateCustomerWizard
/// </summary>
public class UserDetailsAccess
{
    public UserDetailsAccess()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    //get all user
    public static DataTable GetAllUser()
    {
        DbCommand comm = GenericDataAccess.CreateCommand();//create command
        comm.CommandText = "GetUsers"; //set stored procedure
        return GenericDataAccess.ExecuteSelectCommand(comm);
    }

    // Remove a shopping cart item
    public static bool DeleteUser(int userID)
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "UserDelete";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@UserID";
        param.Value = userID;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
        // returns true in case of success or false in case of an error
        try
        {
            // execute the stored procedure and return true if it executes
            // successfully, or false otherwise
            return (GenericDataAccess.ExecuteNonQuery(comm) != -1);
        }
        catch
        {
            // prevent the exception from propagating, but return false to
            // signal the error
            return false;
        }
    }
    // Add a new customer
    public static bool UserAdd(string userName, string password, string email, string securityQuestion, string securityAnswer, string country, string Gender, int Age)
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "UserAdd";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@UserName";
        param.Value = userName;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Password";
        param.Value = password;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Email";
        param.Value = email;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@SecurityQuestion";
        param.Value = securityQuestion;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@SecurityAnswer";
        param.Value = securityAnswer;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Country";
        param.Value = country;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Gender";
        param.Value = Gender;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Age";
        param.Value = Age;
        param.DbType = DbType.Int32;
        comm.Parameters.Add(param);
    
        // returns true in case of success or false in case of an error
        try
        {
            // execute the stored procedure and return true if it executes
            // successfully, or false otherwise
            return (GenericDataAccess.ExecuteNonQuery(comm) != -1);
        }
        catch
        {
            // prevent the exception from propagating, but return false to
            // signal the error

            return false;
        }
    }
    // verify users against existing database
    public static bool IsValidUser(string userName, string password)
    {
        // get a configured DbCommand object
        DbCommand comm = GenericDataAccess.CreateCommand();
        // set the stored procedure name
        comm.CommandText = "UserIsExist";
        // create a new parameter
        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@UserName";
        param.Value = userName;
        param.DbType = DbType.String;
        param.Size = 36;
        comm.Parameters.Add(param);
        // create a new parameter
        param = comm.CreateParameter();
        param.ParameterName = "@Password";
        param.Value = password;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        // return the result table
        DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
        if (table.Rows.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


Creating the Admin Panel




Show/Hide The Menu Items to The Users Depending on Roles
if (Roles.IsUserInRole("Admin"))
{
    Menu1.Items[0].Text = "Admin";
}
else
{
    Menu1.Items[0].Text = "";
}

ASP.NET: ASPNETDB- SQL Role manager

SQL Role manager, SQL Role provider SQL Authentication 
To use a role store in SQL Server, add a connection string to point to your role database and add a role provider definition in the Web.config file, as shown here.


<configuration>
  <connectionStrings>
    <add name="SqlRoleManagerConnection" 
         connectionString="Data Source=sqlinstance;
                          Initial Catalog=aspnetdb;Integrated Security=SSPI;">
    </add>
  </connectionStrings>
</configuration>

<roleManager enabled="true" defaultProvider="SqlRoleManager">
  <providers>
    <add name="SqlRoleManager" 
         type="System.Web.Security.SqlRoleProvider"
         connectionStringName="SqlRoleManagerConnection"
         applicationName="MyApplication" />
  </providers>
</roleManager>


Using the Role Management APIs

You can assign users to roles or remove users from roles by using methods of the System.Web.Security.Roles class. You can also check for the user's role membership and authorize as appropriate.
Note   Because the WindowsTokenRoleProvider is read-only, it supports only the IsUserInRole andGetRolesForUser methods.
The following code shows how to create new roles.
using System.Web.Security;

if (!Roles.RoleExists("TestRole"))
{
  Roles.CreateRole("TestRole");
}
  
Note   Role names are not case sensitive. If you attempt to create the same role twice, an exception is thrown.
The following code shows how to add uses to roles.
// Example 1 - Add one user to one role
Roles.AddUserToRole("TestOne", "ExampleRole1");

// Example 2 - Add one user to several roles
Roles.AddUserToRoles("TestTwo", 
  new string[] { "ExampleRole1", "ExampleRole2" });

// Example 3 - Add several users to one roles
Roles.AddUsersToRole(
  new string[] { "TestTwo", "TestThree" }, "ExampleRole3");

// Example 4 - Add several users to several roles
Roles.AddUsersToRoles(
  new string[] { "TestThree", "TestFour" }, 
  new string[] { "ExampleRole4" }); 
  
The following code shows how to remove users from roles.
// Example 1 - Add one user to one role
Roles.RemoveUserFromRole("TestOne", "ExampleRole1");

// Example 2 - Add one user to several roles
Roles.RemoveUserFromRoles("TestTwo", 
  new string[] { "ExampleRole1", "ExampleRole2" });

// Example 3 - Add several users to one roles
Roles.RemoveUsersFromRole(
  new string[] { "TestTwo", "TestThree" }, "ExampleRole3");

// Example 4 - Add several users to several roles
Roles.RemoveUsersFromRoles(
  new string[] { "TestThree", "TestFour" }, 
  new string[] { "ExampleRole4" }); 
  
Note   Both the AddUser and RemoveUser methods throw a TargetInvocationException if you specify a role that does not exist or if you specify an invalid Windows user account name.

Sample: Using SqlRoleProvider or AuthorizationStoreRoleProvider

This sample uses the SqlRoleProvider or AuthorizationStoreRoleProvider.
To test role management with SqlRoleProvider or AuthorizationStoreRoleProvider
  1. Use Visual Studio.NET 2005 to create a Web site, add a Web.config file, and configure the role store andSqlRoleProvider or AuthorizationStoreRoleProvider as described in steps 1 and 2 of this How To.
  2. Using the Internet Information Services MMC snap-in, edit the properties of the Web site. Edit the Anonymous access and authentication control on the Directory security tab. Clear the Anonymous access check box and select the Integrated Windows authentication check box.
  3. In the Web.config file, enable Windows authentication.
    <system.web>
        ...
        <authentication mode="Windows"/>
        ...
    </system.web>
      
  4. Add the following code to the Default.aspx file.
    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    
    <script runat="server">
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Roles.RoleExists("TestRole"))
            {
                Roles.CreateRole("TestRole");
            }
            ShowRoleMembership();
        }
        private void ShowRoleMembership()
        {
            if (Roles.IsUserInRole("TestRole"))
            {
                Label1.Text = User.Identity.Name + " is in role TestRole";
            }
            else
            {
                Label1.Text = User.Identity.Name + " is NOT in role TestRole";
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Roles.AddUserToRole(User.Identity.Name, "TestRole");
            ShowRoleMembership();
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            Roles.RemoveUserFromRole(User.Identity.Name, "TestRole");
            ShowRoleMembership();
        }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Add to role" 
                        OnClick="Button1_Click" /><br />
            <br />
            <asp:Button ID="Button2" runat="server" Text="Remove from role" 
                        OnClick="Button2_Click" /><br />
            <br />
            <asp:Label ID="Label1" runat="server" />
        </div>
        </form>
    </body>
    </html>
      
  5. Run the application. Note the following features about this application:
    1. When you browse to the application, the code in the Page_Load event handler creates the role TestRole if it does not already exist.
      • The text of Label1 shows whether the current authenticated user is a member of the TestRole role.
      • When you click the Add to role button, the code in the Button1_Click event handler uses the role management API to add the current authenticated user to the TestRole role.
      • If you click the Add to role button again before clicking the Remove from role button, the call toRoles.AddUserToRole throws an exception because the user is already in the role TestUser. You must code for this condition in your applications.
      • When you click the Remove from role button, the current authenticated user is removed from the role TestRole.
      • If you click the Remove from role button again before clicking the Add to role button, the call toRoles.RemoveUserFromRole throws an exception because the user is already not in the roleTestUser and cannot be removed twice. You must code for this condition in your applications.
To control access to pages and folders using roles
A typical use for roles is to establish rules that allow or deny access to pages or folders. You can set up such access rules in the <authorization> section of the Web.config file. The following example allows users in the role of members to view pages in the folder named memberPages and denies access to anyone else.
<configuration>
   <location path="memberPages">
       <system.web>
            <authorization>
               <allow roles="Manager" />
               <deny users="*" />
            </authorization>
          </system.web>
        </location>
   <!-- other configuration settings here -->
<configuration>

ADDITIONAL CONSIDERATIONS

If a user's browser accepts cookies, you can store role information for that user in a cookie on the user's computer. On each page request, ASP.NET reads the role information for that user from the cookie. This can improve application performance by reducing the amount of communication required with the roles data store.
To configure and enable role caching, set cacheRolesInCookie = true as shown here.
<roleManager enabled="true" 
             cacheRolesInCookie="true" 
             cookieName=".ASPXROLES"                 
             cookieTimeout="30" 
             cookiePath="/" 
             cookieRequireSSL="false" 
             cookieSlidingExpiration="true"                 
             cookieProtection="All" 
             defaultProvider="AspNetSqlRoleProvider"       
             createPersistentCookie="false" 
             maxCachedResults="25"/>
  
If the role information for a user is too long to store in a cookie, ASP.NET stores only the most recently used role information in the cookie, and then it looks up additional role information in the data source as required.
To secure the role cookie:
  • Set cookieRequireSSL to true to ensure the cookie is only used over an SSL protected channel.
  • Set createPersistentCookie to false to prevent the cookie from being stored on the client computer, in which case the cookie is only used to protect the current session.
  • Set cookieTimeout to the number of minutes for which the cookie is valid.

show/hide css menu item depending user role using asp.net


You can put this in the Page_Load..
    Dim cs As ClientScriptManager = Page.ClientScript

    If Not cs.IsClientScriptBlockRegistered(Me.GetType(), "RoleVariable") Then
        Dim js As New String
        js = "var _role = " & role & ";"
        cs.RegisterStartupScript(Me.GetType(), "RoleVariable", js, True)
    End If
And from there, you will have the role in the Javascript realm, where you can manipulate the visibility of the items you want.
So...
<script type="text/javascript">
    function hideStuff() {
        if (_role === "operator") {
            // hide/show your elements here
        }
        else if (_role === "guest") {
            // hide/show your elements here
        }
    }
</script>
Keep in mind that this approach is all client-side and is therefore easy for another developer to manipulate if theyreally wanted to. But on the other hand, it's the simplest. Don't use this approach for high-security situations.


Consider catching the MenuItemDataBound event and then using whatever logic you choose to make it Show or hide.
Try below code, hope it helps.
protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
    {
        System.Web.UI.WebControls.Menu menu = (System.Web.UI.WebControls.Menu)sender;
        SiteMapNode mapNode = (SiteMapNode)e.Item.DataItem;


        System.Web.UI.WebControls.MenuItem itemToRemove = menu.FindItem(mapNode.Title);


        if (mapNode.Title == "Node")
        {
            System.Web.UI.WebControls.MenuItem parent = e.Item.Parent;
            if (parent != null)
            {
                parent.ChildItems.Remove(e.Item);
            }
        }
    }

Thursday, 7 March 2013

User Control in UpdatePanel Loses Styles on Postback - IE only


In the IE9 update panel lose style but not in google chrome or firefox.
You must add a ScriptManager control to the page and set its EnablePartialRendering property to true
<asp:ScriptManager EnablePartialRendering="True|False" />

Wednesday, 6 March 2013

Creating ASP.NET Menu control


 Resource:

  • http://msdn.microsoft.com/en-us/library/ecs0x9w5(v=vs.80).aspx

Code:
<div class="clear hideSkiplink">
                <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
                    <Items>
                        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="Admin"/>
                        <asp:MenuItem NavigateUrl="~/About.aspx" Text="About"/>
                    </Items>
                </asp:Menu>
            </div>