Sunday, 15 July 2012

Form Authentication-1

Web.Config :-----

<connectionStrings>
        <add name="MyConnection" connectionString="server=syn17;initial catalog=PropertyTest;Integrated Security=SSPI;"/>
    </connectionStrings>

<authentication mode="Forms">
                          <forms name=".MyProperty" loginUrl="Login.aspx" protection="All" timeout="720" />
              </authentication>
        <authorization>
          <deny users="?" />   
        </authorization>

<location path="Admin">
        <system.web>
            <authorization>
                <allow roles="admin" />
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <location path="user">
        <system.web>
            <authorization>
                <allow roles="Location" />
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Global.asax :--------

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Security.Principal" %>

 void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        //Code to authenticate roles and provide access to users
        if(HttpContext.Current.User !=null)
            if(HttpContext.Current.User.Identity.IsAuthenticated)
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket ticket = id.Ticket;
                    string userData = ticket.UserData;
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new GenericPrincipal(id, roles);                  
                }
    }
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
login.aspx.cs :----------


 protected void btnLogin_Click(object sender, EventArgs e)
    {

        Cls_Customer Obj_User = new Cls_Customer();
      
        FormsAuthenticationTicket ticket;
        string cookiestr = "";

        try
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();
            int UserId = 0;
            //this Method is used to check the valid UserName & password from User Table & assing Role
            UserId = Obj_User.AuthenticateUser(username, password);
                   // Obj_User = null;
                    string role = "member";
                    if (UserId > 0)
                    {
                        if (UserId == 1)
                            role = "admin";

                        ticket = new FormsAuthenticationTicket(1, username, DateTime.Now,DateTime.Now.AddMinutes(15), false, role);
                        cookiestr = FormsAuthentication.Encrypt(ticket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                        cookie.Path = FormsAuthentication.FormsCookiePath;
                        Response.Cookies.Add(cookie);
                        if (role == "member")
                        {                 
                            Session["UserName"] = txtUsername.Text.Trim();
                            Response.Redirect("./Location/ViewMyLocation.aspx", true);
                        }

                        else
                        {
                            Session["UserName"] = txtUsername.Text.Trim();
                            Response.Redirect("./Admin/Default.aspx", true);
                        }
                    }
                    else
                    {
                        txtPassword.Text = "";
                        txtUsername.Text = "";
                       // Page.RegisterStartupScript("Message", "<script language=javascript>alert('Incorrect username/password!');</script>");
                        //Response.Write("<script language=javascript>alert('incorrectusername/password!');</script>");
                    }

             
 
        }

        catch (Exception ex)
        {
            string str = ex.Message;

        }
        finally
        {

        }
    }
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Bussiness Layer :---------
Cls_Customer:-----

using System;
using System.Data;
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Cls_Customer
/// </summary>
public class Cls_Customer
{
    public Cls_Customer()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    #region All Private Member Variables are declare here
    private Boolean _Password_Is_Exist;
    /// <summary>
    /// This Member varible Is Used To  Return _User_Is_Exist IF Exist then true Else False
    /// </summary>
    private Boolean _User_Is_Exist;
    /// <summary>
    /// This Member varible Is Used To  Return _Email_Is_Exist IF Exist then true Else False
    /// </summary>
    private Boolean _Email_Is_Exist;
    /// <summary>
    /// This Member Variable is Used TO Hold _User_Is_DtRecod
    /// </summary>
    private DataTable _User_Is_DtRecod;
    /// <summary>
    /// This Member varible SqlCommand Reference
    /// </summary>
    SqlCommand _SqlCmd;

    /// <summary>
    /// This Member varible SqlDataReader Reference
    /// </summary>
    SqlDataReader _SqlDr;
    /// <summary>
    /// This Member varible DataTable Reference
    /// </summary>
    DataTable _Dt;
    /// <summary>
    /// This Member varible is Class AHC_ClsDB  Reference
    /// </summary>
    CDB objClsDB;
    /// <summary>
    /// This Member varible Is Used To Hold or Return _UserExceptionMessgae
    /// </summary>
    private string _UserExceptionMessgae;

    /// <summary>
    /// This Member varible Is Used To Hold or Return _returnint
    /// </summary>
    private int _returnint;
    #endregion
    # region All Property of Private Member Variables are declare here
    #endregion
 
    #region All Method are declare here
    /// <summary>
    /// This Method Is Used to Get Authenticate the user and return the id of the user to the caller 
    /// </summary>
    ///
    public int AuthenticateUser(string username, string password)
    {
        objClsDB = new CDB();
        int AuthenticatedId = 0;
        DataTable dt = new DataTable();
        try
        {
            _SqlCmd = new SqlCommand("SP_AuthenticateUser");
            _SqlCmd.Parameters.AddWithValue("@username", username);
            _SqlCmd.Parameters.AddWithValue("@password", password);
            _SqlCmd.CommandType = CommandType.StoredProcedure;
            dt = objClsDB.getDataTable(_SqlCmd);
            if (dt.Rows.Count > 0)
                AuthenticatedId = Convert.ToInt32(dt.Rows[0]["CustId"].ToString());
            dt = null;

            return AuthenticatedId;
        }
        catch (Exception ex)
        {
            _UserExceptionMessgae = ex.Message;
            return AuthenticatedId;
        }
        finally
        {
            _SqlCmd.Dispose();
        }
    }
    #endregion
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DataLayer :---

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// This Class Contain all Member variable and member function to communicate with database
/// </summary>
public class CDB
{

    public CDB()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    #region All Private Member Variables are declare here

    /// <summary>
    /// This varibale is SqlConnection Object and Use for Specify connectionstring for Database
    /// </summary>

    SqlConnection _SqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ToString());

    /// <summary>
    /// This varibale is SqlDataAdapter Reference
    /// </summary>
    SqlDataAdapter _SqlDa;

    /// <summary>
    /// This varibale is DAtaset Reference
    /// </summary>
    DataSet _Ds;

    /// <summary>
    /// This Member varible Is Used To  Return Int
    /// </summary>
    private int _DBReturnInt;

    /// <summary>
    /// This Member varible Is Used To  Return String
    /// </summary>
    private string _DBReturnString;


    /// <summary>
    /// This Member varible Is Used To  Return Decimal
    /// </summary>
    private decimal _DBReturnDecimal;

    /// <summary>
    /// This Member varible Is Used To  Return DatabaseException
    /// </summary>
    private string _DBExceptionMessage;

    # endregion

    #region All Property of Private Member Variables are declare here

    /// <summary>
    /// This get  Property is Handle Private Variable _DBReturnDecimal;
    /// </summary>
    public decimal DBReturnDecimal
    {
        get
        {
            return _DBReturnDecimal;
        }
    }

    /// <summary>
    /// This get  Property is Handle Private Variable DBReturnInt;
    /// </summary>
    public int DBReturnInt
    {
        get
        {
            return _DBReturnInt;
        }
    }

    /// <summary>
    /// This get  Property is Handle Private Variable _DBReturnString;
    /// </summary>
    public string DBReturnString
    {
        get
        {
            return _DBReturnString;
        }
    }

    /// <summary>
    /// This get  Property is Handle Private Variable DatabaseExceptionMessgae;
    /// </summary>
    public string DBExceptionMessage
    {
        get
        {
            return _DBExceptionMessage;
        }
    }

    # endregion

    #region All Method which Interact with Database will declare here

    /// <summary>
    /// This Method Is Used to Insert a New Record In Database
    /// </summary>
    /// <Param name="SqlCommand"> SqlCmd</Param>
    public Boolean InsertRecord(SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                Int32 _RowAffect = _SqlCmd.ExecuteNonQuery();
                if (_RowAffect == 1)
                {

                }
            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }

    /// <summary>
    /// This Method Is Used to Update  Old Record In Database
    /// </summary>
    /// <Param name="SqlCommand">SqlCmd</Param>
    public Boolean UpdateRecord(SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                Int32 _RowAffect = _SqlCmd.ExecuteNonQuery();
                if (_RowAffect >= 1)
                {

                }
            }
            return true;

        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }

    /// <summary>
    /// This Method Is Used to Delete  Old Record In Database
    /// </summary>
    /// <Param name="SqlCommand">SqlCmd</Param>
    public Boolean DeleteRecord(SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                Int32 _RowAffect = _SqlCmd.ExecuteNonQuery();
                if (_RowAffect >= 1)
                {

                }
            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }

    /// <summary>
    /// This Method Is Used to Retuen a Int Value From Database
    /// </summary>
    /// <Param name="SqlCommand">SqlCmd</Param>
    public Boolean ReturnInt(SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _DBReturnInt = Convert.ToInt32(_SqlCmd.ExecuteScalar());

            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }

    /// <summary>
    /// This Method Is Used to Retuen a   String Value From Database
    /// </summary>
    /// <Param name="SqlCommand">SqlCmd</Param>
    public Boolean ReturnString(SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _DBReturnString = _SqlCmd.ExecuteScalar().ToString();

            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }

    /// <summary>
    /// This Method Is Used to Retuen a   decimal Value From Database
    /// </summary>
    /// <Param name="SqlCommand">SqlCmd</Param>
    public Boolean ReturnDecimal(SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _SqlCmd.ExecuteNonQuery();

                _DBReturnDecimal = Convert.ToDecimal(_SqlCmd.Parameters[2].Value);
                //string s =  _SqlCmd.Parameters[2].Value.ToString();


            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }

    /// <summary>
    /// This Method Is Used to Retuen a   String Value From Database
    /// </summary>
    /// <Param name="SqlCommand">SqlCmd</Param>
    public Boolean ReturnSqlDataReader(SqlCommand _SqlCmd, ref SqlDataReader _SqlDr)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _SqlDr = _SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);

            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            //if (_SqlCon.State == ConnectionState.Open)
            //{
            //    _SqlCon.Close();
            //}
        }
    }

    /// <summary>
    /// This Method Is Used to Retuen a  DataTable  From Database
    /// </summary>
    /// <Param name="DataTable">_Dt</Param>
    public Boolean ReturnDataTable(SqlCommand _SqlCmd, ref DataTable _Dt)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _SqlDa = new SqlDataAdapter();
                _SqlDa.SelectCommand = _SqlCmd;
                _SqlDa.Fill(_Dt);
                return true;
            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
    }



    /// <summary>
    /// This Method Is Used to Fill a DropDownList
    /// </summary>
    /// <Param name="DropDownLIst">_ddlList</Param>
    ///  <Param name="SQlCommand">_SqlCmd</Param>
    ///  <Param name="string">_TextField</Param>
    ///  <Param name="string">_ValueField</Param>
    public Boolean FillDropDownList(ref DropDownList _ddlList, SqlCommand _SqlCmd, string _TextField, string _ValueField)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }
            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _SqlDa = new SqlDataAdapter();
                _SqlDa.SelectCommand = _SqlCmd;
                _Ds = new DataSet();
                _SqlDa.Fill(_Ds);
                _ddlList.DataSource = _Ds;
                _ddlList.DataTextField = _TextField;
                _ddlList.DataValueField = _ValueField;
                _ddlList.DataBind();

            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
            _SqlDa.Dispose();
            _Ds.Dispose();
        }
    }

  
    /// <summary>
    /// This Method Is Used to Fill a DropDownList
    /// </summary>
    /// <Param name="GridView">_Gv</Param>
    ///  <Param name="SQlCommand">_SqlCmd</Param>  

    public Boolean FillGridView(ref GridView _Gv, SqlCommand _SqlCmd)
    {
        try
        {
            if (_SqlCmd == null)
            {
                _DBExceptionMessage = "";
                return false;
            }

            else if (_SqlCmd != null)
            {
                if (_SqlCon.State == ConnectionState.Closed)
                {
                    _SqlCon.Open();
                }
                _SqlCmd.Connection = _SqlCon;
                _SqlDa = new SqlDataAdapter();
                _SqlDa.SelectCommand = _SqlCmd;
                _Ds = new DataSet();
                _SqlDa.Fill(_Ds);
                _Gv.DataSource = _Ds;
                _Gv.DataBind();

            }
            return true;
        }
        catch (SqlException _SqlEx)
        {
            throw;
            _DBExceptionMessage = _SqlEx.Message;
            return false;
        }
        catch (Exception _Ex)
        {
            throw;
            _DBExceptionMessage = _Ex.Message;
            return false;
        }
        finally
        {
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
            _SqlDa.Dispose();
            _Ds.Dispose();
        }
    }
    /// <summary>
    /// This Method Is Used to Retuen a DataTable  From Database
    /// </summary>
    public DataTable getDataTable(SqlCommand _SqlCmd)
    {
        IDataReader _SqlDr;
        DataTable dt = new DataTable();
        if (_SqlCmd != null)
        {
            if (_SqlCon.State == ConnectionState.Closed)
            {
                _SqlCon.Open();
            }
            _SqlCmd.Connection = _SqlCon;
            _SqlDr = _SqlCmd.ExecuteReader();
            dt.Load(_SqlDr);
            _SqlDr = null;
            if (_SqlCon.State == ConnectionState.Open)
            {
                _SqlCon.Close();
            }
        }
        return dt;
    }
}


DBTable Name :--- Customer 
CustID int,
Username varchar(25)
Password varchar(25)

SP:----------------
 Alter PROCEDURE SP_AuthenticateUser   
    (
  @username Char( 25 ),
   @password Char( 25 )

  )
   As
  
 
  
   SELECT  *  FROM [Customer]
   Where username = @username and password = @password and IsActive=1
  
------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment