Pages

Wednesday, 29 June 2011

authentications in asp.net

//.web.config file
<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="Conn" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Employee" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>

    <authentication mode="Forms">
      <forms loginUrl="~/Login.aspx" timeout="20"></forms>
    </authentication>
   
    <authorization>
      <deny users="?"/>
      <allow users="*"/>
    </authorization>

    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
  </system.web>
  <system.web>
    <pages theme="SkinFile"> </pages>
  </system.web>
  <location path="Admin" >
    <system.web>
      <authorization>
        <allow users="Admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="Employee">
    <system.web>
      <authorization>
        <allow users="Employee"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="Users">
    <system.web>
      <authorization>
        <allow users="Users"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
</configuration>
//login button
   protected void BtnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            if (validations())
            {
                UserName = TxtUserName.Text.Trim();

                Session["uname"] = UserName;
                //check the username and pwd
                objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
                SqlCommand objcommand = new SqlCommand();
                objcommand.Connection = objconnection;
                objcommand.CommandType = CommandType.Text;
                objcommand.CommandText = "Select Count(*) from UserLogin where UserName='" + UserName + "' and Password='" + TxtPassword.Text.Trim() + "'";
                objconnection.Open();
                val = int.Parse(objcommand.ExecuteScalar().ToString());
                if (val > 0)
                {
                    //get  the user roleid
                    objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
                    objcommand = new SqlCommand();
                    objcommand.Connection = objconnection;
                    objcommand.CommandType = CommandType.Text;
                    objcommand.CommandText = "Select Role from UserLogin where UserName='" + UserName + "'";
                    objconnection.Open();
                    RoleId = int.Parse(objcommand.ExecuteScalar().ToString());
                    //check the userid and roleid is active or not
                    objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
                    objcommand = new SqlCommand();
                    objcommand.Connection = objconnection;
                    objcommand.CommandType = CommandType.Text;
                    objcommand.CommandText = "Select Count(*) from UserLogin where UserName='" + UserName + "' and Role='" + RoleId + "' and Active=" + 1 + "";
                    objconnection.Open();
                    int val1 = int.Parse(objcommand.ExecuteScalar().ToString());
                    objconnection.Close();
                    string role = "";
                    if (RoleId == 1)
                    {
                        role = "Admin";

                    }
                    else if (RoleId == 2)
                    {
                        role = "Employee";
                    }
                    else if (RoleId == 3)
                    {
                        role = "Users";
                    }
                    FormsAuthentication.RedirectFromLoginPage(role.Trim(), false);
                    if (val1 > 0)
                    {
                        if (RoleId == 1)
                        {
                            Response.Redirect("~/Admin/Default.aspx");
                        }
                        else if (RoleId == 2)
                        {
                            Response.Redirect("~/Employee/Default.aspx");
                        }
                        else if (RoleId == 3)
                        {
                            Response.Redirect("~/Users/Default.aspx");
                        }
                        //objconnection.Close();
                    }
                    else
                    {
                        MessageBox.Show("Access is denined Please contact administrator? Mr/Mrs:" + TxtUserName.Text.Trim(), "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        TxtUserName.Focus();
                    }

                }
                else
                {
                    MessageBox.Show("the Username or Password mismatch", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    TxtUserName.Focus();
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error occur", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        //finally
        //{
        //    objconnection.Close();
        //}
    }
//edig grid
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;


public partial class GridviewP : System.Web.UI.Page
{
    private SqlConnection objconnection;
    private SqlDataReader dr;
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillGridValues();
        }

    }
    private void FillGridValues()
    {
        try
        {
            objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            SqlCommand objcommand = new SqlCommand();
            objcommand.Connection = objconnection;
            objcommand.CommandType = CommandType.Text;
            objcommand.CommandText = "Select * from Employee";
            SqlDataAdapter da = new SqlDataAdapter(objcommand);
            DataSet ds = new DataSet();
            da.Fill(ds, "Emp");
            // GridView1.DataSource = ds.Tables[0];
            //GridView1.DataBind();
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
            // MessageBox.Show(ex.Message);
        }

    }
    protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    //private DataTable GridDataSource()
    //{
    //    DataTable dTable = new DataTable();
    //    try
    //    {
    //        objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
    //        SqlCommand objcommand = new SqlCommand();
    //        objcommand.Connection = objconnection;
    //        objcommand.CommandType = CommandType.Text;
    //        objcommand.CommandText = "Select * from Employee";
    //        SqlDataAdapter da = new SqlDataAdapter(objcommand);
    //        DataSet ds = new DataSet();
    //        da.Fill(ds, "Emp");
    //        dTable = ds.Tables[0];
    //        //grdContact.DataSource = dTable;
    //        //grdContact.DataBind();
    //    }
    //    catch (Exception ex)
    //    {
    //        Label2.Text = ex.Message;
    //    }

    //    return dTable;
    //}
    protected void Updating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            //int EmpCode = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            int intResult = 0;
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            TextBox txtcode = (TextBox)row.FindControl("txtempcode");
            TextBox TXTname = (TextBox)row.FindControl("txtEmpName");
            TextBox txtqualification = (TextBox)row.FindControl("txtQualification");
            TextBox txtaddress = (TextBox)row.FindControl("txtAddress");
            TextBox txtcompanyname = (TextBox)row.FindControl("txtCompanyName");
            //if (TXTCODE.Text.Trim() == null && TXTCODE.Text.Trim() == "" && TXTname.Text.Trim() == null && TXTname.Text.Trim() == ""
            //    && txtqualification.Text.Trim() == null && txtqualification.Text.Trim() == "" && txtaddress.Text.Trim() == null && txtaddress.Text.Trim() == ""
            //        && txtcompanyname.Text.Trim() == null && txtcompanyname.Text.Trim() == "")
            //{
            objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            SqlCommand objcommand = new SqlCommand();
            objcommand.Connection = objconnection;
            objcommand.CommandType = CommandType.Text;
            objcommand.CommandText = "UPDATE Employee   SET EmpName ='" + TXTname.Text.Trim() + "' ,Address = '" + txtaddress.Text.Trim() + "'" +
            ",CompanyName = '" + txtcompanyname.Text.Trim() + "',Qualification ='" + txtqualification.Text.Trim() + "' WHERE EmpCode=" + txtcode.Text.Trim() + "";
            objconnection.Open();
            intResult = objcommand.ExecuteNonQuery();
            objconnection.Close();
            if (intResult == 1)
            {
                GridView1.EditIndex = -1;
                Label2.Text = "Record Updated Successfully.";
                FillGridValues();
            }
            else
            {
                Label2.Text = "Record couldn't updated";
                FillGridValues();
                GridView1.EditIndex = -1;
            }
        }
        catch (Exception ex)
        {
            Label2.Text += ex.Message;
            GridView1.EditIndex = -1;
        }

    }
    protected void Editing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    protected void Deleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int EmpCode = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            SqlCommand objcommand = new SqlCommand();
            objcommand.Connection = objconnection;
            objcommand.CommandType = CommandType.Text;
            objcommand.CommandText = "Delete from Employee where EmpCode=" + EmpCode + "";
            objconnection.Open();
            int val = objcommand.ExecuteNonQuery();
            objconnection.Close();

            if (val == 1)
            {
                GridView1.EditIndex = -1;
                Label2.Text = "Record Deleted Successfully.";
                FillGridValues();
            }
            else
            {
                Label2.Text = "Record couldn't Deleted";
                FillGridValues();
                GridView1.EditIndex = -1;
            }
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
            GridView1.EditIndex = -1;
            //MessageBox.Show("Error" + ex.Message, "CURD", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    protected void Canceling(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = -1;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    protected void pageindexchanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridView1.PageIndex = e.NewPageIndex;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        try
        {
            string id = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
            //switch (id)
            //{
            //    case "Enter":
            //        break;
            //    case "Delete":
            //        Deleting();
            //        break;
            //    case "Insert":
            //        //Insert();
            //        break;
            //    default:
            //        Label2.Text = "No operations is done";
            //        break;
            //}
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }

    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sortExpression = e.SortExpression;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            } 
          
        }
        catch (Exception ex)
        {
           // Label2.Text = ex.Message;
            throw;
        }

    }
    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private void SortGridView(string sortExpression, string direction)
    {
        //  You can cache the DataTable for improving performance
        FillGridValues();
        DataTable dt = GridView1.DataSource as DataTable;
        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + direction;
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

  
}
//.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;


public partial class GridviewP : System.Web.UI.Page
{
    private SqlConnection objconnection;
    private SqlDataReader dr;
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillGridValues();
        }

    }
    private void FillGridValues()
    {
        try
        {
            objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            SqlCommand objcommand = new SqlCommand();
            objcommand.Connection = objconnection;
            objcommand.CommandType = CommandType.Text;
            objcommand.CommandText = "Select * from Employee";
            SqlDataAdapter da = new SqlDataAdapter(objcommand);
            DataSet ds = new DataSet();
            da.Fill(ds, "Emp");
            // GridView1.DataSource = ds.Tables[0];
            //GridView1.DataBind();
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
            // MessageBox.Show(ex.Message);
        }

    }
    protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    //private DataTable GridDataSource()
    //{
    //    DataTable dTable = new DataTable();
    //    try
    //    {
    //        objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
    //        SqlCommand objcommand = new SqlCommand();
    //        objcommand.Connection = objconnection;
    //        objcommand.CommandType = CommandType.Text;
    //        objcommand.CommandText = "Select * from Employee";
    //        SqlDataAdapter da = new SqlDataAdapter(objcommand);
    //        DataSet ds = new DataSet();
    //        da.Fill(ds, "Emp");
    //        dTable = ds.Tables[0];
    //        //grdContact.DataSource = dTable;
    //        //grdContact.DataBind();
    //    }
    //    catch (Exception ex)
    //    {
    //        Label2.Text = ex.Message;
    //    }

    //    return dTable;
    //}
    protected void Updating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            //int EmpCode = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            int intResult = 0;
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            TextBox txtcode = (TextBox)row.FindControl("txtempcode");
            TextBox TXTname = (TextBox)row.FindControl("txtEmpName");
            TextBox txtqualification = (TextBox)row.FindControl("txtQualification");
            TextBox txtaddress = (TextBox)row.FindControl("txtAddress");
            TextBox txtcompanyname = (TextBox)row.FindControl("txtCompanyName");
            //if (TXTCODE.Text.Trim() == null && TXTCODE.Text.Trim() == "" && TXTname.Text.Trim() == null && TXTname.Text.Trim() == ""
            //    && txtqualification.Text.Trim() == null && txtqualification.Text.Trim() == "" && txtaddress.Text.Trim() == null && txtaddress.Text.Trim() == ""
            //        && txtcompanyname.Text.Trim() == null && txtcompanyname.Text.Trim() == "")
            //{
            objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            SqlCommand objcommand = new SqlCommand();
            objcommand.Connection = objconnection;
            objcommand.CommandType = CommandType.Text;
            objcommand.CommandText = "UPDATE Employee   SET EmpName ='" + TXTname.Text.Trim() + "' ,Address = '" + txtaddress.Text.Trim() + "'" +
            ",CompanyName = '" + txtcompanyname.Text.Trim() + "',Qualification ='" + txtqualification.Text.Trim() + "' WHERE EmpCode=" + txtcode.Text.Trim() + "";
            objconnection.Open();
            intResult = objcommand.ExecuteNonQuery();
            objconnection.Close();
            if (intResult == 1)
            {
                GridView1.EditIndex = -1;
                Label2.Text = "Record Updated Successfully.";
                FillGridValues();
            }
            else
            {
                Label2.Text = "Record couldn't updated";
                FillGridValues();
                GridView1.EditIndex = -1;
            }
        }
        catch (Exception ex)
        {
            Label2.Text += ex.Message;
            GridView1.EditIndex = -1;
        }

    }
    protected void Editing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    protected void Deleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int EmpCode = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            objconnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
            SqlCommand objcommand = new SqlCommand();
            objcommand.Connection = objconnection;
            objcommand.CommandType = CommandType.Text;
            objcommand.CommandText = "Delete from Employee where EmpCode=" + EmpCode + "";
            objconnection.Open();
            int val = objcommand.ExecuteNonQuery();
            objconnection.Close();

            if (val == 1)
            {
                GridView1.EditIndex = -1;
                Label2.Text = "Record Deleted Successfully.";
                FillGridValues();
            }
            else
            {
                Label2.Text = "Record couldn't Deleted";
                FillGridValues();
                GridView1.EditIndex = -1;
            }
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
            GridView1.EditIndex = -1;
            //MessageBox.Show("Error" + ex.Message, "CURD", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    protected void Canceling(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = -1;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    protected void pageindexchanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridView1.PageIndex = e.NewPageIndex;
            FillGridValues();
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        try
        {
            string id = GridView1.DataKeys[e.NewSelectedIndex].Value.ToString();
            //switch (id)
            //{
            //    case "Enter":
            //        break;
            //    case "Delete":
            //        Deleting();
            //        break;
            //    case "Insert":
            //        //Insert();
            //        break;
            //    default:
            //        Label2.Text = "No operations is done";
            //        break;
            //}
        }
        catch (Exception ex)
        {
            Label2.Text = ex.Message;
        }

    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sortExpression = e.SortExpression;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            } 
          
        }
        catch (Exception ex)
        {
           // Label2.Text = ex.Message;
            throw;
        }

    }
    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
    private void SortGridView(string sortExpression, string direction)
    {
        //  You can cache the DataTable for improving performance
        FillGridValues();
        DataTable dt = GridView1.DataSource as DataTable;
        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + direction;
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

  
}

No comments:

Post a Comment