How can I extract the column data from my user row? EX: This gets called on my WCF server when the client logs in. It works up to var xx = ds.Tables[0].Rows[1]; where it throws an error on the clients side. Basically I am trying to have the user/pass verified in the database. Then return to the Client a DateTime of when his subscription expires.
public bool Authenticate(string userId, string password, out string token)
{
token = "";
string MyConnectionString = "Server=localhost;Database=testdb;Uid=root;Pwd=admin;";
MySqlConnection sqlCon = new MySqlConnection(MyConnectionString);
sqlCon.Open();
MySqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = "SELECT * FROM table1 WHERE username = '"+userId+"' AND password = '"+password+"'";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
token = Guid.NewGuid().ToString();
var xx = ds.Tables[0].Rows[0];
CustomDataSource.AddUserData(token, userId);
return true;
}
return false;
}
Well I suppose that your query returns only one row (if it finds the user with the correct password)
In that case you get the date from the first row returned (index zero).
Also I assume that your date is stored in the fifth column (index four), if not you should adjust the second index to point to the correct column. (The base array index is always zero)
if (ds.Tables[0].Rows.Count > 0)
{
token = Guid.NewGuid().ToString();
var xx = ds.Tables[0].Rows[0][4];
CustomDataSource.AddUserData(token, userId);
return true;
}
Said that, let me point to a big problem of this code.
This code could be easily used for a Sql Injection Attack because it concatenates strings, probably typed by your user, to form a Sql Text passed to the database engine. Instead you should use parameters to avoid the Sql Injection problem and the quoting of user text (password with an apostrophe?)
using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
sqlCon.Open();
MySqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = "SELECT * FROM table1 WHERE username = ?user AND password = ?pwd";
cmd.Parameters.AddWithValue("?user", userId);
cmd.Parameters.AddWithValue("?pwd", password);
using(MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
adap.Fill(ds);
}
}
var xx = ds.Tables[0].Rows[0].ItemArray[5];
Is how.
try using foreach loop
foreach (DataRow row in ds.Tables[0].Rows)
{
var xx = row[1];
var x = row[5];
// other codes
return true;
}
one more thing, parameterized your query to avoid SQL injection
using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM table1 WHERE username = #user AND password = #pass";
cmd.Parameters.AddWithValue("#user", userId);
cmd.Parameters.AddWithValue("#pass", password);
using (MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
{
try
{
DataSet ds = new DataSet();
adap.Fill(ds);
}
catch (MySqlException e)
{
// do something with the exception
// don't hide it!
}
}
}
}
Related
I have a user login menu. I want to redirect the user based on their Level. The Level data is in the SQL table. I want to get the Level data from the table based on their username and assign it to a variable.
protected void btnDefault_Click(object sender, EventArgs e)
{
//filter entered text
string strUserName = Tools.checkSQLInjection(txtUserName.Text).Trim();
string strPassword = Tools.checkSQLInjection(txtPassword.Text);
string strError = "";
//Get Dealer Level Value
SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email='" + strUserName + "'");
string strDealerLvl = "dealerLvl".ToString();
int intDealerLvl;
bool isParsable = Int32.TryParse(strDealerLvl, out intDealerLvl);
if (strDealerLvl == "1")
{ Response.Redirect("/dealers/dashboard"); }
else if (strDealerLvl == "2")
{ Response.Redirect("/dealers/dashboard-2"); }
You don't seem to be checking the password, but perhaps that supposed to come later.
A working code stub to do this would look like say this:
DataTable MyTable = new DataTable();
int intDealerLvl = 0;
using (SqlCommand cmdSQL = new SqlCommand("SELECT dealerLv1 FROM Users where email = #meail",
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
}
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
switch (intDealerLvl)
{
case 1:
{
Response.Redirect("/dealers/dashboard");
break;
}
case 2:
{
Response.Redirect("/dealers/dashboard-2");
break;
}
default:
{
// no level found - where to go??
break;
}
}
However, it not clear if you supposed to be checking the password, and if so then of course we use this:
DataTable MyTable = new DataTable();
string strSQL;
strSQL = "SELECT dealerLv1 FROM Users where email = #Email and Password = #Pass";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Parameters.Add("#Pass", SqlDbType.NVarChar).Value = strPassword;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
using(SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email= #strUserName", connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#strUserName", strUserName);
DataSet ds = new DataSet();
using(SqlDataAdapter da = new SqlDataAdapter(command))
da.Fill(ds);
//Get the result of the first row
DataRow dr = ds.Tables[0].Rows[0];
//Get the value of the column in the first row
string strDealerLvl = dr["dealerLvl"].ToString();
}
These are the tables in my project:
I am trying to update a DataGridView so that it displays the data of the user who is logged in.
I am getting the error: 'Must declare scalar variable '#CurrentUserID'... I think this is because I cannot convert the value to an int but if this is the case how do I fix the problem?
This is my code so far:
//Find ID of user who is logged in
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True");
SqlCommand command = new SqlCommand("select UserID from Users where Username = '"+loggedInLabel.Text+"' ", conn);
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
int currentUserID = reader.GetInt32(reader.GetOrdinal("UserID"));
command.Parameters.Add("#CurrentUserID", SqlDbType.Int);
command.Parameters["#CurrentUserID"].Value = currentUserID;
//update datagridview
string dgvconn = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = #CurrentUserID";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
dataGridView.DataSource = ds;
dataGridView.DataMember = "Records";
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Just in case anyone else was stuck with it.
I solved it by removed the code where I added the parameters and replacing it with :
dataadapter.SelectCommand.Parameters.AddWithValue("#CurrentUserID", currentUserID);
Thanks for the help!
You have many errors in your code, you're not disposing anything and re-using the command in a invalid way (while the reader is executing).
You're not using parameters. You're not re-using the SQL Connection. You're not adding parameters in the correct way.
This is how the code should look
try
{
DataSet records = new DataSet();
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\newest\CW\CW\Database1.mdf;Integrated Security=True"))
{
int? userId = null;
using (SqlCommand command = new SqlCommand("select UserID from Users where Username = #Username", conn))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = loggedInLabel.Text;
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
if (reader.Read())
userId = reader.GetInt32(reader.GetOrdinal("UserID"));
conn.Close();
}
if (userId == null) // No row found
throw new ApplicationException("User not found");
using (SqlCommand command = new SqlCommand("select * from Records where UserID = #CurrentUserID", conn))
{
command.Parameters.Add("#CurrentUserID", SqlDbType.Int).Value = userID.Value;
// SqlDataAdapter opens and closes the connection itself.
using (SqlDataAdapter dataadapter = new SqlDataAdapter(command))
dataadapter.Fill(records , "Records");
}
}
//update datagridview
dataGridView.DataSource = records ;
dataGridView.DataMember = "Records";
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
You should also combine SQL Queries
select UserID from Users where Username = #Username and select * from Records where UserID = #CurrentUserID can be combined into this:
select Records.*
from Records
join Users
on Users.UserID = Records.UserID
where Users.Username = #Username
Then you only have to supply the Username and you'll get the records if everything is there.
I'm trying to get a value from my database but it keeps returning a value of 0 and i cannot figure out why. I've been retrieving data from the database for the whole of my project and it is just not working here. None of the values in the database are = to 0.
int rentalPrice is the one being returned as 0`
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("DisplayCars.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cars where id ='" + id + "'";
cmd.ExecuteNonQuery();
lblCarID.Text = id.ToString();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
foreach (DataRow dr2 in dt2.Rows)
{
rentalPrice = Convert.ToInt32(dr2["car_rental_price"]);
}
lblRentalPrice.Text = rentalPrice.ToString();
con.Close();
}
// This uses a Connection pool, so you don't need to reuse the same SqlConnection
using (SqlConnection con = new SqlConnection(...))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select [car_rental_price] from cars where id = #Id";
var idParam = new SqlParameter("#Id");
idParam.Value = id;
cmd.Parameters.Add(idParam);
con.Open();
using (var reader = cmd.ExcecuteReader())
{
reader.Read();
lblRentalPrice.Text = reader.GetInt32(0).ToString();
lblCarID.Text = id.ToString();}
}
}
}
To execute a query and get results, you need to use cmd.ExecuteReader.
Also, rather than concatenating values into a string to build your SQL query, you need to use parameterized queries. This helps prevent SQL Injection attacks.
Also, SqlConnection should not be put in a field (class level variable). Instead, you should use local variables and wrap them in a using statement to ensure that they get disposed of properly.
hey you did not fill the Data Table.. then how it has any Values???
first Fill the data Table and use it in Foreach loop
adapter.Fill(DataTable);
foreach(DataRow dr in DataTable)
{
//get the id
}
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...