C# get sql table column value and put it in a variable - c#

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();
}

Related

Pulling sql data from [columnnr] to a string for a later check

I'm creating a small app. Until now I've had admin users hardcoded into the app, but I have the columns ready in the sql db to check if a user is admin or have edit rights. I'm just having trouble getting that info drawn out of the db.
And wanted to move on to being able to dynamically change admin users.
Heres the code from the app's Load
private void FrmMain_Load(object sender, EventArgs e)
{
if (labelUser.Text.Contains("JAM") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("DST") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("KBW") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("JDJ") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else if (labelUser.Text.Contains("THR") == true)
{
btnAdmin.Visible = true;
btnUpdate.Visible = true;
btnNew.Visible = true;
}
else
{
btnAdmin.Visible = false;
btnUpdate.Visible = false;
btnNew.Visible = false;
}
//SQLconnection string
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf";
//SQLconnection
SqlConnection con = new SqlConnection(cs);
con.Open();
string strCmd = "select * from AvSites";
SqlCommand cmd = new SqlCommand(strCmd, con);
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
DataSet ds = new DataSet();
//Fill combobox list with items from the SQL database
da.Fill(ds);
combo1.ValueMember = "id";
combo1.DisplayMember = "siteName";
combo1.DataSource = ds.Tables[0];
combo1.Enabled = true;
this.combo1.SelectedItem = -1;
this.combo1.SelectedText = "--select--";
cmd.ExecuteNonQuery();
con.Close();
//SQLconnection
labelUser2.Text = labelUser.Text.ToLower();
SqlConnection con2 = new SqlConnection(cs);
con.Open();
string strCmd2 = "select * from tbl_Login where UserName = 'labelUser2.Text' ";
SqlCommand cmd2 = new SqlCommand(strCmd2, con);
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, con);
DataSet ds2 = new DataSet();
using (SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
string IsAdmin = rdr["IsAdmin"].ToString();
labelisAdmin.Text = IsAdmin;
}
}
cmd.ExecuteNonQuery();
con.Close();
}
My first thought was to identify what user, by using my labelUser which is a visible label showing the user currently logged in taken directly from the sqldatabase. (reason for the .ToLower is that the sql db has the users in all small case).
First part of the sql is populating a combobox with items from another db tree.
It's this part that is causing me issues;
//SQLconnection
labelUser2.Text = labelUser.Text.ToLower();
SqlConnection con2 = new SqlConnection(cs);
con.Open();
string strCmd2 = "select * from tbl_Login where UserName = 'labelUser2.Text' ";
SqlCommand cmd2 = new SqlCommand(strCmd2, con);
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, con);
DataSet ds2 = new DataSet();
using (SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
string IsAdmin = rdr["IsAdmin"].ToString();
labelisAdmin.Text = IsAdmin;
}
}
cmd.ExecuteNonQuery();
con.Close();
}
IsAdmin or column [3] is either 0 for false or 1 for true. but with this search, it doesnt return anything.
This is wrong
string strCmd2 = "select * from tbl_Login where UserName = 'labelUser2.Text' ";
because you are actually looking for someone with a username of labelUser2.Text and not what that label's text property contains.
You were probably meaning to concatenate that into your string but that too is wrong. Although it would work, it is a very unsafe practice to get started with. Instead you would place a parameter into your sql statement and give it the value of your label.
string strCmd2 = "select * from tbl_Login where UserName = #un ";
SqlCommand cmd2 = new SqlCommand(strCmd2, con);
cmd2.Parameters.Add("#un", SqlDbType.VarChar).Value = labelUser2.Text
SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, con);
...
Here we put a parameter in place to take in user inputted value, we then create the command object and define the parameters values from the user input controls.

Assign SQL query result to session variable

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
}
}
}
}

how can I store all of the database records from a username(from registration) but it is based on the user input?

Here is my log in page code. What I want to do is when the user inputs his/her username, it will then get all of the database records "based on that username input" of the customer and store it in a single session.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
I have set the Session["Username"] to the user input(txtUser.text), but what I want to do is to get all of the database records on that username that the customer will enter.
Afterwards, I am planning to call on that specific database record and bind it to the order .aspx page. I have tried this code below but its only showing me the Session["Username"], since I have called it on the login page.
txtCustomerName.Text = Session["Username"].ToString();
txtCustomerPhoneNo.Text = Session["Contact"].ToString();
txtCustomerEmailID.Text = Session["Email"].ToString();
txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
You can create a data structure to store the information you need.
public class Person
{
public string Username { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
using (SqlCommand command = new SqlCommand(
"SELECT * FROM databaseTablename where username = " + txtUser.Text, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Person person = new Person();
person.Username = reader.GetString(reader.GetOrdinal("username"));
person.Contact = reader.GetString(reader.GetOrdinal("contact"));
person.Email = reader.GetString(reader.GetOrdinal("email"));
person.Password = reader.GetString(reader.GetOrdinal("password"));
}
}
}
}
You can then store this object in a session like so:
Session["username"] = person;
Later on, if you want to access the contents of the session, say in the Order.aspx page, you can do like so:
Person person = (Person)Session["username"];
get the records from the database. Store it in a comma separated string.
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
SqlDataAdapter da=new SqlDataAdapter(scm);
DataSet ds=new DataSet();
da.Fill(ds);
conn.Close();
string userdata="";
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
userdata+=","+row[i].ToString();
}
}
userdata=userdata.TrimStart(',');
Session["username"]= userdata;
for getting all the records just get this string from session and split it
If(Session["username"]!=null)
String user=Session["username"].ToString();
string[] udat=user.Split(',');
you can get all data in this string array.
Im kind of new to programming so please excuse any error.
This is for storing your all values in single session
DataBaseConnection db = new DataBaseConnection();
DataTable dt = new DataTable();
dt = db.executeNonQuery("Your Query that retrieves all user's data goes here");
if(dt.Rows.Count > 0)
{
List<string> lst = new List<string>();
foreach(DataRow dr in dt.Rows)
{
lst.Add(dr["Cloumn_1"].ToString());
lst.Add(dr["Column_2"].ToString());
.
.
Session["YourSessionName"] = lst;
}
}
here DataBaseConnection is class that returns connection string of database, so now you know what to do.
i hope this helps. Let me know

Alert on gridview edit based on permission

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...

How to extract individual column data from C# MySQL query?

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!
}
}
}
}

Categories