I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}
Related
This is my code inside my button Login Click. I would like to know How can I retrieve records from the database from the user that is currently logged in from any of the web forms that proceed the login form or what command do I insert into a select statement to be able to select the username of the current logged n user.
protected void btnLogin_Click(object sender, EventArgs e)
{
var CS = ConfigurationManager.ConnectionStrings["TupperwareDemAppConnString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
var cmd = new SqlCommand(#"SELECT * FROM [USER] WHERE userName= #txtUserName AND userPassword= #txtuserPassword ", con);
cmd.Parameters.Add(new SqlParameter("#txtUserName", txtUsername.Text));
cmd.Parameters.Add(new SqlParameter("#txtuserPassword", txtPassword.Text));
con.Open();
var sda = new SqlDataAdapter(cmd);
var dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = txtUsername.Text;
Response.Cookies["Pword"].Value = txtPassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddDays(15);
Response.Cookies["PWord"].Expires = DateTime.Now.AddDays(15);
}
else
{
Response.Cookies["UName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["PWord"].Expires = DateTime.Now.AddDays(-1);
}
}
}
}
Store user id in any of the session variable (loggedInUserId) and passe it in where condition. you can get data into the datatable.
public void BindData()
{
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [USER] WHERE userId='+ loggedInUserId +'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
}
It shows invalid user credentials even though I inputted the right one. I don't know if I made the parameters wrong or if my query is wrong. I want to learn about parameterized queries but I don't know what I'm doing wrong here.
con.OpenConnection();
using (con.connection)
{
String query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
try
{
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
MessageBox.Show("Invalid user credentials.");
}
else
{
//Do stuff
}
}
catch (MySqlException mse)
{
MessageBox.Show(mse.Message);
}
finally
{
con.CloseConnection();
}
Not sure why it is not working but if you use AddWithValue, it will work. Something like this
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
Change your code so that it's calls a method, when you click on a Button, pass the Username and Password variable into this Method. Create a AutoProperty for UserName and Password at the Class Level
private DataTable PopulateSomeDatatSet(DataSet aDataset, string UserName, string Password)
{
var query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
MySqlDataAdapter sda;
using (SqlConnection connStr = new SqlConnection(ConnString)) //replace with your ConnectionString Variable
{
using (MySqlCommand cmd = new MySqlCommand(query, connStr))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = UserName;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = Password;
sda = new MySqlDataAdapter(cmd);
new MySqlDataAdapter(cmd).Fill(aDataset);
}
}
((IDisposable)sda).Dispose();
return aDataset.Tables[0];
}
I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}
I have a gridview with edit option at the start of the row. Also I maintain a seperate table called Permission where I maintain user permissions. I have three different types of permissions like Admin, Leads, Programmers. These all three will have access to the gridview. Except admin if anyone tries to edit the gridview on clicking the edit option, I need to give an alert like This row has important validation and make sure you make proper changes.
When I edit, the action with happen on table called Application. The table has a column called Comments. Also the alert should happen only when they try to edit rows where the Comments column have these values in them.
ManLog datas
Funding Approved
Exported Applications
My try so far.
public bool IsApplicationUser(string userName)
{
return CheckUser(userName);
}
public static bool CheckUser(string userName)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(CS))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select * from Permissions where AppCode='Nest' and UserID = '" + userName + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
if (dt.Rows.Count >= 1)
return true;
else
return true;
}
protected void Details_RowCommand(object sender, GridViewCommandEventArgs e)
{
string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name;
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string[] words = currentUser.Split('\\');
currentUser = words[1];
bool appuser = IsApplicationUser(currentUser);
if (appuser)
{
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(str))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select Role_Cd from User_Role where AppCode='PM' and UserID = '" + currentUser + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
if (e.CommandName.Equals("Edit") && ds.Tables[0].Rows[0]["Role_Cd"].ToString().Trim() != "ADMIN")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gvCurrentGrid = (GridView)sender;
GridViewRow row = gvCurrentGrid.Rows[index];
string strID = ((Label)row.FindControl("lblID")).Text;
string strAppName = ((Label)row.FindControl("lblAppName")).Text;
Response.Redirect("AddApplication.aspx?ID=" + strID + "&AppName=" + strAppName + "&Edit=True");
}
}
}
Kindly let me know if I need to add something. Thanks for any suggestions.
public static bool CheckUserAdminOrNot(your arguments)
{
string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name;
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string[] words = currentUser.Split('\\');
currentUser = words[1];
bool appuser = IsApplicationUser(currentUser);
if (appuser)
{
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(str))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select Role_Cd from User_Role where AppCode='PM' and UserID = '" + currentUser + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
if(user is not Admin)
return string that you want....
}
}
}
After that you get response in ajax use this response and redirect page and pass value in url that you want...
I have a username db table that I'm trying to connect with to compare the username/pass.
Here is my code, it's not working, what am I doing wrong?
DataTable dt = null;
protected void btn_Click_Login(object sender, EventArgs e)
{
string query = string.Format("SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", txtUsername.Text, txtPassword.Text);
using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter(query, c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
if (dt.Rows.Count > 0)
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
lblError.Text = "success";
}
else
{
lblError.Text = "Wrong Username/Password combination";
}
}
}
most probably you are using wrong datatable to check no of rows returned.
Check for t and dt instances of datatable.
Try creating a SqlCommand to hold your query.
SqlCommand cmd = new SqlCommand(query, c);
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataTable t = new DataTable();
a.Fill(t);
}
I'm not 100% sure that's your issue, but back in the days when i used to use ADO.NET (before L2SQL/EF, dark days indeed), i seem to remember an issue with DataTable's and SqlDataAdapter.
From what i remember - you can't fill a DataTable with a SqlDataAdapter based on a raw query string - you need to use SqlCommand. But i believe this can be accomplished with DataSet.
So either change to SqlCommand, or change to DataSet.
You fill t:
DataTable t = new DataTable();
a.Fill(t);
but read dt:
if (dt.Rows.Count > 0)
I decided to try the data reader and got it working:
protected void btn_Click_Login(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RbConnectionString"].ConnectionString);
conn.Open();
string queryString = "SELECT * FROM [Users] WHERE Username=#username AND Password= #password";
SqlCommand command = new SqlCommand(queryString, conn);
command.Parameters.AddWithValue("#username", txtUsername.Text);
command.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
}
else
{
lblError.Visible = true;
lblError.Text = "Incorrect Username/Password Combination";
}
conn.Close();
}
What error you are getting is not clear. But i feel your connection is open and is never closed. Try
c.Close();