So I'm trying to create simple button that decides if you are admin or user.
But I cant get it to work properly. I'm connected to MySQL db but when I click button with either admin/user account (stored in db) I get:
"you are an admin"
So I guess I have mistake somewhere but cant see where:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection cn = new MySqlConnection("Server=;Database=;Uid=;Pwd=;");
MySqlCommand cmd = new MySqlCommand("SELECT usertype FROM table1 ", cn);
cmd.Parameters.AddWithValue("usertype", usertype.Text);
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
cn.Close();
}
If you don't add a WHERE statement to your sql command you will always retrieve the value from the first column of the first row returned by the database engine. You should change your code to something like this
private void button1_Click(object sender, EventArgs e)
{
// I assume you have a field named UserID as the primary key of your table1
string sqlCmd = #"SELECT usertype FROM table1 WHERE UserID=#id";
using(MySqlConnection cn = new MySqlConnection("....."))
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, cn))
{
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = currentUserid;
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
}
}
Now the problem is how to define the variable currentUserId This is something that you need to retrieve when the user logs in and conserve at the class level to reuse when needed. Notice also that connections are disposable objects and as such your need to dispose them as soon as you have finished to use them. The using statement helps to do this
Related
I'm creating a forms application which needs a login function. I have set up the MySqL connection and have applied it to my form. It does answer to my to responses, giving me a respons with a pass or no pass, BUT this is only when I ask for it to only match the input with passwords in the database. I cannot get it to match both the usernames and the passwords, even though I seem to have configurated my table as it should be. I've got 3 columns with ID, username(brugernavn) and password.
I can get it to accept both credentials if I match the ID's with the right password, fx SELECT * FROM bruger WHERE password =#pass AND id=#usn
I'm still very new to programming so if I'm confused please let me know.
Is anyone able to help?
I've tried to change my parameters to something else, but that didnt do the trick. There didnt seem to be a problem with the actual table, as it could acces my information about the passwords and the ID's, so I tried changing some values and stuff from the username column, but it did no good. I have both the username and password using varchar(100) and the ID is using INT(11) as a primary.
MySqlConnection connection = new MySqlConnection("server=localhost;port=3306;username=root;password=;database=bruger");
public void openConnection()
{
if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
public MySqlConnection GetConnection()
{
return connection;
}
private void Loginbutton_Click(object sender, EventArgs e)
{
DB db = new DB();
string username = textBoxBrugernavn.Text;
string password = textBoxPassword.Text;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM bruger WHERE password =#pass AND brugernavn =#usn", db.GetConnection());
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = username;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = password;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
MessageBox.Show("YES");
}
else
{
MessageBox.Show("NO");
}
I was hoping this would let me run my forms apps and then let me login with already created users in my database. This however is not the case, as I am unable to match these two informations in the application.
Keep you data objects local. Then you can be sure they are closed and disposed. The using blocks take care of that even if there is an error. Since we only need one piece of data (the count) we can use ExecuteScalar which returns the first column of the first row in the result set. Of course, in a real application, you would never store passwords as plain text. They would be salted and hashed.
private void Loginbutton_Click(object sender, EventArgs e)
{
Int64 RecordCount = 0;
using (MySqlConnection cn = new MySqlConnection("server=localhost;port=3306;username=root;password=;database=bruger"))
{
using (MySqlCommand command = new MySqlCommand("SELECT Count(*) FROM bruger WHERE password =#pass AND brugernavn =#usn", cn))
{
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = textBoxBrugernavn.Text;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = textBoxPassword.Text;
cn.Open();
RecordCount = (Int64)command.ExecuteScalar();
}
}
if (RecordCount > 0)
{
MessageBox.Show("YES");
//Add code to proceed to your next form
}
else
{
MessageBox.Show("NO");
}
}
I'm using C# with an ASP.Net table. I'm trying to check when a user accesses my web app, that their User ID is listed in the column called UserID in a table that is displayed in the web app. If it is not, then I want to redirect them to an error page.
I need this to check when the page is loaded so obviously it needs to be in Page_Load. I just don't know how to call the column in my table and to have it check the User ID.
This is what I have so far:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
SQLUserID();
if (UserID != //'Whatever values are in the UserID column'//)
{
Server.Transfer("ErrorPage.aspx");
}
SQLCmd = SqlDataSource1.SelectCommand;
GridView1.DataBind();
}
}
The string UserID gives me the User ID of the user. SQLUserID() = SELECT UserId FROM Info. I know the way I called that isn't correct but I'm not sure how to do it.
It can help you:
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand check_User_Name ("SELECT COUNT(*) FROM tblUser WHERE (UserID=#UserID)",conn);
check_User_Name.Parameters.AddWithValue("#UserID,UserID);
int userExist=(int)check_User_Name.ExecuteScalar();
if(userExist>0)
{
//Login
}
else
{
Server.Transfer("ErrorPage.aspx");
}
just write your connection string and enjoy it.
So here is how I got it to work below Page_Load
{
string connectionString = "Data Source=###;Initial Catalog=###;Integrated Security=True";
if (!Page.IsPostBack)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(UserID) from Info WHERE UserID like #UserID", sqlConnection))
{
string UserID = HttpContext.Current.Request.LogonUserIdentity.Name.Substring(4);
sqlCommand.Parameters.AddWithValue("#UserID", UserID);
int userCount = (int)sqlCommand.ExecuteScalar();
if (userCount == 0)
{
Server.Transfer("ErrorPage.aspx");
}
SQLCmd = SqlDataSource1.SelectCommand;
GridView1.DataBind();
}
}
}
In my application I have a login system. It's basic so I don't need any encryption. The problem is that when I want to login, I insert the credentials (username and password) but it doesn't make anything. My code is:
public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
string txtuser = textusername.Text;
string txtpass = textlogin.Text;
MySqlCommand cmd = new MySqlCommand("SELECT password FROM empregados WHERE user='" + txtuser + "';", mConn);
mConn.Open();
MySqlDataReader login = cmd.ExecuteReader();
login.Read();
string getpass = login["password"].ToString();
if (getpass == txtpass)
{
mConn.Close();
MessageBox.Show("Sessão iniciada");
Admin adm = new Admin();
this.Hide();
adm.Show();
}
else
{
mConn.Close();
MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
}
}
I'd like to propose some fixes mentioned in the comments along with some general improvements. See my comments in the code for the issues addressed:
public void iniciarsessaobutton_Click(object sender, EventArgs e)
{
string txtuser = textusername.Text;
string txtpass = textlogin.Text;
// Put your connection into a using() block
using (MySqlConnection conn = new MySqlConnection(variableWithYourConnectionStringHere))
{
// Put your commend into a using() block
// enclose your column names in backticks to avoid conflict with MySql reserved keywords
// add a placeholder (#username) for your parameter
// use LIMIT 1 if you only expect 1 row matching your condition
using(MySqlCommand cmd = new MySqlCommand("SELECT `password` FROM empregados WHERE `user` = #username LIMIT 1", conn))
{
mConn.Open();
// add a parameter with your TextBox value
cmd.Parameters.AddWithValue("#username", txtuser);
// If you only retrieve 1 value, use ExecuteScalar to return only 1 value
// cast the returned object as string
string getpass = cmd.ExecuteScalar() as string;
if (getpass == txtpass)
{
MessageBox.Show("Sessão iniciada");
Admin adm = new Admin();
this.Hide();
adm.Show();
}
else
{
MessageBox.Show("Não foi possivel iniciar sessão. Insira a password corretamente.");
}
}
}
}
I have a log in page that checks with a database for current registered users. At the moment my code will tell me me the user does not exist, when in fact they are on the database, or the page will remain the same if they aren't, when the text corresponding to the problem should come up.
So the name 'Tom' is already on the database, when i type 'Tom' i get the message
"user does not exist".
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void Button_LogIn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[#"\\MAC\HOME\DESKTOP\NIMV1.MDFConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where UserName= '" + TextBoxLogIn.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
if (checkuser == TextBoxLogIn.Text)
{
Session["New"] = TextBoxLogIn.Text;
Response.Write("User name is correct");
}
else
{
Response.Write("user does not exist");
}
conn.Close();
}
}
You're comparing your SQL string against the user name that has been passed in.
string checkuser = "select count(*) from [Table] where UserName= '" + TextBoxLogIn.Text + "'";
//...
if (checkuser == TextBoxLogIn.Text)
{
Session["New"] = TextBoxLogIn.Text;
Response.Write("User name is correct");
} else {
Response.Write("user does not exist");
}
I assume this will always evaluate to false unless the user has an SQL query for a name :D
[EDIT] Actually even if their name was an SQL query the code would never get to that point because you wouldn't find their name in the database in the first place.
You are comparing records using user name in database with entered text.
string checkuser = "select count(1) from [Table] where UserName= '" +
TextBoxLogIn.Text + "'";
After executing query instead of:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
if (checkuser == TextBoxLogIn.Text)
///
///
Use following code:
if (temp >= 1)//if there is any user we will get temp >= 1
{
//conn.Open(); //No need to open connection again
//checkuser is SQL query so will never be equal to
//what user enters (like joe#example.com)
//if (checkuser == TextBoxLogIn.Text)
//{
Session["New"] = TextBoxLogIn.Text;
Response.Write("User name is correct");
//}
else //if no user with given name, temp will be 0
{
Response.Write("user does not exist");
//}
//conn.Close();
}
Peope already told you about the error you've made about comparing the variable that holds the query agains the value you typed (doh!!) but i want to DISCOURAGE you against writing the queries the way you do: it isn't a good practice to write query the way you've done because you are vulnerable to SQL Injection or at least nasty bugs if you don't escape correctly your variables.
I invite you to read about how to use what the .Net framework gives to you: use Parameters!
here you can find another answer with code that you can use or at least understand: https://stackoverflow.com/a/11905249/1716620
I'm using ASP.Net/C# and I have a form that allows people to add information into a table and along with it I want to collect the Current Users GUID and insert it.
I have a field setup (UserID) as a unique identifier and I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser currentUser = Membership.GetUser();
Guid temp = (Guid)(Membership.GetUser(User.Identity.Name).ProviderUserKey);
Guid #currentUserID = temp;
}
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd;
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values('" + #currentUserID + "')", con);
cmd.ExecuteNonQuery();
}
I basically want to link the variable to the Database any idea how as the above gives errors.
You should never insert values directly into a SQL statement like that, no matter what type they are, as that opens you up to a SQL Injection attack. Instead, you should use parameters in your query, through which System.Guid values will be automatically translated to the SQL Server uniqueidentifier type. This is how I would do it:
Guid currentUserId = (Guid)(Membership.GetUser(User.Identity.Name).ProviderUserKey);
using (var connection = new SqlConnection("..."))
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Accom (UserID) VALUES (#UserID)";
var param = command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier);
param.Value = currentuserId;
connection.Open();
command.ExecuteNonQuery();
}
Guid #currentUserID = temp;
You are defining a variable currentUserID in local scope - you must save this variable in the Session so you can access it in the Button1_Click method:
Session["UserId"] = currentUserID;
Now you can retrieve it in Button1_Click:
Guid currentUserID = (Guid)Session["UserId"];
Also the # is not needed nor should it be there, you only should need it if you want to define variables with a name that matches a C# keyword - this is bad style anyway. Also you want to put the SqlConnection specific code all within the button click handler - otherwise this variable is instantiated evertime the page loads, not just when the button click handler is used. Finally you also want to use SqlParameters instead of strings in your SQL insert statement.
Edit:
As #pst pointed out, the more "ASP.NET way" would be to just use an instance variable
Guid currentUserID;
that you declare as part of the class, not within a method - then you can use this variable throughout the page. This means however, the user id will not be available on other pages (with a session it could be retrieved through the life time of the session on any page).
I dont know if SQL server supports GUID as a datatype, in MysQL I would go with a char, but that is not important, just a comment. The important part is that in the method:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values('" + #currentUserID + "')", con);
cmd.ExecuteNonQuery();
}
You don't specify the actual value for #currentUserID
you must rewrite it to something like:
protected void Button1_Click(object sender, EventArgs e)
{
SqlParameter param = new SqlParameter();
con.Open();
cmd = new SqlCommand("insert into Accom (UserID) values(#currentUserID)", con);
//this are the important lines that I'm talking about
param.ParameterName = "#currentUserID";
param.Value = valueOfUserId;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}
Hope that helps.
In the original code above the currentUser variable is unused. Also if the user is not logged on the call to Membership.GetUser(User.Identity.Name) will return a null reference and trying to retrieve ProviderUserKey code will throw a NullReferenceException. It would be better to have something along these lines;
public partial class Default : System.Web.UI.Page
{
MembershipUser currentUser;
protected void Page_Load(object sender, EventArgs e)
{
currentUser = Membership.GetUser();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (null != currentUser)
{
Guid currentUserID = currentUser.ProviderUserKey;
// database code here
}
}
}