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 = "";
}

No comments:

Post a Comment