I'm having problems loading information from my database into labels and pictureboxes. I think my code is correct to do what i'm wanting but i'm guessing not since it's not working. Below is the code i'm using. For the picture column in my database, I store the picture's path, not the actual blob. If you need anymore relevant information, please ask.
Code:
private void AirSpace_Shown(object sender, EventArgs e)
{
string connectionString = "datasource=localhost;port=3306;username=Admin;password=August211989";
Login login = new Login();
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
string select = "SELECT username, email, premium, picture FROM userinfo.users WHERE username = #username;";
// (1) (2) (3) (4)
conn.Open();
cmd.CommandText = select;
cmd.Parameters.AddWithValue("#username", login.UsernameTextBox.Text);
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
//Set the user's profile picture to the user's profile picture.
ProfilePicture.Load(Reader.GetString(4));
//Set the username to the user's username
Username.Text = Reader.GetString(1);
//Set the app version to the user's version
if (Reader.GetString(3) == "1")
{
AppVersionLabel.Text = "Premium";
}
else
{
AppVersionLabel.Text = "Free";
}
}
}
}
}
You might try this. This looks to be a log in code as well so I would add logic to where if you loop more than one it throws an error cause there should only be 1 result.
While(Reader.Read()){
//Set the user's profile picture to the user's profile picture.
string UserProfilePictureLocation = Reader.GetString(3);
ProfilePicture.Load(UserProfilePictureLocation);
//Set the username to the user's username
Username.Text = Reader.GetString(0);
//Set the app version to the user's version
if (Reader.GetString(2) == "1")
{
AppVersionLabel.Text = "Premium";
}
else
{
AppVersionLabel.Text = "Free";
}
}
Related
I am doing a simple project for school where I have to create a login form and make it so when a person logs in it then shows their profile with all their user information. So how would I code the textboxes in windows forms C# so when a person logs in the textboxes show information gathered from database of person who just logged in.
This is the code for the login form.
OleDbConnection connection = new OleDbConnection(); connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from tblUser where Username= '"+username.Text+"' and Password= '"+password.Text+"'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username and password is correct");
var profile = new profile();
}
if (count > 1)
{
MessageBox.Show("Duplicate username and password");
}
else
{
MessageBox.Show("Username or password incorrect");
}
connection.Close();
As I said in the comments, always use parameters in your query strings. Also, since OleDbDataReader is forward reading only, what I would do is create a new user and add to a list for each record returned. Then, if you only get one record, use that user data to populate the form. One other major flaw in your code... You are storing passwords as plain text in the database. The best practice is to encrypt/hash the password using one-way encryption and only store the hash in the database. Everytime the user enters a password at login, hash it using the same algorithm and compare it against the hash stored in the DB.
Here's an example incorporating Using (suggested by #Flydog57) and Parameters. But I'm not showing how to hash and store encrypted passwords.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
public class Program
{
public static void Main()
{
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\RAV21001310\\OneDrive\\Database1.accdb;"))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand("SELECT * FROM tblUser WHERE Username=#Username AND Password=#Password", connection))
{
command.Parameters.AddWithValue("#Username", username.text);
command.Parameters.AddWithValue("#Password", password.text);
using (OleDbDataReader reader = command.ExecuteReader())
{
int count = 0;
List<User> UserList = new List<User>();
while (reader.Read())
{
count = count + 1;
User user = new User() {
Username = reader.GetString(1),
FirstName = reader.GetString(2),
LastName = reader.GetString(3),
DateCreated = reader.GetDateTime(4)
};
UserList.Add(user);
}
if (count == 1)
{
//Alert User
MessageBox.Show("Username and password is correct");
//Create an instance of the ProfileForm and populated it with the User data.
var ProfileForm pf = new ProfileForm(UserList[0]);
//Show the Profile Form as a modal window.
pf.ShowDialog();
}
if (count > 1)
{
MessageBox.Show("Duplicate username and password");
}
else
{
MessageBox.Show("Username or password incorrect");
}
}
}
connection.Close();
}
}
}
//This is a class to hold user data.
public class User {
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public DateTime DateCreated { get; set; } = DateTime.MinValue;
}
This is a quick sample of the code-behind for a "ProfileForm". When you verify the user is authenticated, then create an instance of the ProfileForm, populate it with the userdata, then show the form to the user. There are many other ways to populate a profile form and handle updates to user data, this is just one example.
public class ProfileForm : Form
{
public User User
{
get
{
//When you get the User, update all the user data from text boxes.
User.FirstName = firstnameTextBox.Text;
User.LastName = lastnameTextBox.Text;
//return the newly updated User variable.
return User;
}
set
{
//When we write new data to the form User variable,
//populate each relevant text box on the form.
usernameTextBox.Text = User.Username;
firstnameTextBox.Text = User.FirstName;
lastnameTextBox.Text = User.LastName;
}
}
public ProfileForm(User User) {
this.User = User;
}
}
I am currently programming a C# program that lets students log into an interface, check grades, etc.. Admins can create new users. The student IDs are 9-digit codes that all begin with "95." When an admin is creating a new user, I want to go through the database to make sure that the ID number they have entered isn't already taken.
To do this, I have the following code:
connection.Open();
readerUsers = commandUsers.ExecuteReader();
while (readerUsers.Read())
{
MessageBox.Show(readerUsers[2].ToString());
if(readerUsers[2].ToString() == IDNum)
{
userAlreadyExists = true;
break;
}
}
connection.Close();
And in my Users table, which readerUsers and commandUsers are connected to, I have the following:
IDuser Username 95Number Password Active Admin
-------------------------------------------------------------
1 sward 951619984 uo99lb True True
... ... ... ... ... ...
Now, when I went to test my code by creating a user with the ID number of 951619984 (a number already entered in the database), userAlreadyExists would still remain false. So I made the program show a message box of each item in the 95Number column (which is of type Ntext). Every time, the message box would only show "95".
I am very new to programming with databases, so I apologize if this is a very newby question, but I'm not sure what to do to get the whole string from this ntext column. Could someone explain what I'm doing wrong? Thank you for your time.
Here is a better way of doing that:
var connstr = ConfigurationManager.ConnectionStrings["your key"].ConnectionString;
var sql = "SELECT COUNT(*) FROM Users WHERE [95number]=#num";
using (var conn = new SqlConnection(connstr))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("num",SqlDbType.Int).Value = IDNum;
conn.Open();
var result = cmd.ExecuteScalar();
userAlreadyExists = result > 0;
}
I did mines this way.
string Qstring = "Select 95number where 95number = '95#########'";
using (SqlConnection Con = new SqlConnection(Form1.ConnectionStringGen))
using (SqlCommand Com = con.CreateCommand())
{
Com.CommandText = Qstring;
con.Open();
using (SqlDataReader Reader = Com.ExecuteReader())
{
if(Reader.Read())
{
string 95Numb = Reader["95Number"].ToString();
Messagebox.show(95Numb);
userAlreadyExists = true;
//meaning if the reader reads an item it will prompt
}
else
{
userAlreadyExists = false;
}
}
con.Close();
}
}
catch (Exception)
{
throw;
}
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");
}
}
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 need to get the user current name after a log in. I need to display the name in the page, like welcome user . Please help me, my current code is given below
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
con.Open();
SqlCommand cmdr = new SqlCommand("Select name,password From registration", con);
SqlDataReader dr = cmdr.ExecuteReader();
while (dr.Read())
{
if (txt_name.Text == dr[0].ToString() && txt_pass.Text == dr[1].ToString())
{
Response.Redirect("logout.aspx");
}
else
{
label4.Text ="Invalid Username/Password";
}
}
}
If you're using the ASP.NET membership:
string userName = Membership.GetUser().UserName
However, obviously you are not using it (i strongly recommend). Why do you redirect to logout.aspx when the user successfully provided his username and password?
Apart from that you're not using the provided informatiuons at all in your query.
SqlCommand cmdr = new SqlCommand("Select name,password From registration", con);
So you should use parameters to filter for the correct record:
using(var cmdr = new SqlCommand("Select name,password From registration where name=#name and password=#password", con))
{
cmdr.Parameters.AddWithValue("#name", userName);
cmdr.Parameters.AddWithValue("#password", password);
if(cmdr.ExecuteReader().HasRows)
{
// user + password correct
}
else
{
// user or password incorrect
}
}
Membership.GetUser().UserName in a membership provider. Under no circumstances should you run the code you have there. It is asking for a hack. You should not be loading the passwords into memory and you are going to have performance issues as you gain more users because of your loop through all users!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
con.Open();
SqlCommand cmdr = new SqlCommand("Select name,password From registration", con);
SqlDataReader dr = cmdr.ExecuteReader();
while (dr.Read())
{
if (txt_name.Text == dr[0].ToString() && txt_pass.Text == dr[1].ToString())
{
Session["UserName"]=dr[0].ToString(); // OR Session["UserName"]=txt_name.Text;
Response.Redirect("logout.aspx");
}
else
{
label4.Text ="Invalid Username/Password";
}
}
}
You can fetch the session values in HTML(if your using it in your application)
<div>
Welcome <%=HttpContext.Current.Session["UserName"]%>
</div>
You should be able to get the identity of the user from the User property in code-behind.
myLabel.Text = User.Identity.Name;
The full namespace etc. for this is HttpContext.Current.User.Identity.Name.
Reference for HttpContext.User property: http://msdn.microsoft.com/en-us/library/system.web.httpcontext.user.aspx
put the username in a session
Session["username"] = dr[0].ToString();
then on the other page
if Session["username"] != null
{
String username = Session["username"].ToString();
}
else
{
Page.Redirect("login.aspx");
}
You can check each different page
You should ideally use built-in ASP.NET Forms Authentication - see this article for quick start. Coming to your question, on successful login, you should use line such as
FormsAuthentication.RedirectFromLoginPage(txt_name.Text, true);
This would store the user name into authentication cookie and which can be subsequently retrieved using code such as User.Identity.Name that you can user anywhere in your pages.
You can store the username in session object and get username anywhere in the application if session is present
But you have to update your query also, The way you are calling is not good approach
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con1"].ConnectionString);
con.Open();
SqlCommand cmdr = new SqlCommand("Select name From registration where name = #username and password = #password", con);
cmdr.Parameters.Add("#username", txt_name.Text.trim());
cmdr.Parameters.Add("#password", txt_pass.Text.trim());
SqlDataReader dr = cmdr.ExecuteReader();
if(cmdr.ExecuteReader().HasRows)
{
Response.Redirect("logout.aspx");
Session["userName"] = txt_name.Text.trim();
}
else{
//Error page path
}
//DOn't forget to close the connection when you Open it
con.Close();
}
You should learn more from some tutorials:
http://csharp-station.com/Tutorial/AdoDotNet/Lesson01
MSDN
..and if you're just wanting to use the User object:
var username = User.Identity.Name;