using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
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;

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

    }
    
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (ValidateUserLogin(txtUser.Text, txtPassword.Text) == true)
        {
            System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtUser.Text, false);
        }
        else
        {
            lblError.Text = "Invalid logon attempt";
        }
    }

    //check user data based on user and passw
    // bad practice
    private bool ValidateUserLogin(string userName, string password)
    {
        SqlConnection cn = new SqlConnection();
        cn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

        string Sql = "SELECT COUNT(userid) FROM tblUser WHERE username ='" + userName + "' AND password = '" + password + "'";

        cn.Open();
        SqlCommand cmd = new SqlCommand(Sql, cn);
        int iUser = (int)cmd.ExecuteScalar();
        cn.Close();

        if (iUser > 0)
        { return true; }
        else
        { return false; }
    }

    //check user data based on user and passw
    // good practice with command parameter
    //private bool ValidateUserLogin(string userName, string password)
    //{
    //    SqlConnection cn = new SqlConnection();
    //    cn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

    //    string Sql = "SELECT COUNT(userid) FROM tblUser WHERE username = @username AND password = @password";

    //    cn.Open();
    //    SqlCommand cmd = new SqlCommand(Sql, cn);
    //    cmd.CommandType = CommandType.Text;

    //    SqlParameter prUser = new SqlParameter("@username", SqlDbType.Char, 10);
    //    prUser.Value = userName;
    //    cmd.Parameters.Add(prUser);

    //    SqlParameter prPassword = new SqlParameter("@password", SqlDbType.VarChar, 20);
    //    prPassword.Value = password;
    //    cmd.Parameters.Add(prPassword);

    //    int iUser = (int)cmd.ExecuteScalar();
    //    cn.Close();

    //    if (iUser == 1)
    //    { return true; }
    //    else
    //    { return false; }
    //}
}
