i am making an application that lets a user register and login and also change their username sand passwords. when the user is signing up their details are stored in a sqlite database.my problem is that i am not able to update heir account details that are stored in the sqlite database
i have already looked up solutions to this onstack overflaw but i can tseem to find a solution
string oldusername = txtBoxoldUsername.Text;
string oldpassword = txtBoxoldPassword.Text;
string newusername = txtBoxnewUsername.Text;
string newpassword = txtBoxnewPassword.Text;
SQLiteConnection con = new SQLiteConnection("Data Source=Users.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("select * from UserInfo where UserName like #oldusername and Password = #oldpassword;", con);
cmd.Parameters.AddWithValue("#oldusername", oldusername);
cmd.Parameters.AddWithValue("#oldpassword", oldpassword);
con.Open();
SQLiteDataReader sdr = cmd.ExecuteReader();
if ((sdr.Read() == true))
{
//this is where i am trying to put the code that updats the users username and password
}
else
{
MessageBox.Show("Invalid username or password",
"Incorrect details entered");
}
i have tried everything i can but i still can seen to update my database.so it will be great if someone can code it in where i have left the comment the name for my database is Users and my table is called UserInfo
You need a seperate SQL Lite Command to make an update, somthing like:
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = "[Update SQL script]";
cmd.ExecuteNonQuery();
Related
I have a table EmployeeRank1 in SQL Server that has a column Name. Under column Name there are two pre-defined names of employees. Moreover, in the table there is a column Password, which contains a generic password, which is "123456".
In WPF I have a textbox and that asks for name and one password box that asks for password. Underneath them, there is a button that says "Login".
The questions is how do I compare the content of Name and Pasword in my table to the input in the text box and the password box?
If the Name entered exists and the Password is correct, a new WPF page will be opened. Otherwise, a message stating that either the name or the password is incorrect will be printed.
This is what I have until now:
// check if the input matches and open the new WPF Page
private void EmployeeRank1Button_Click(object sender, RoutedEventArgs e)
{
try
{
// create a query and select everything from the EmployeeRank1 table
string query = "select * from EmployeeRank1";
// create a connection to the database and run the query
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
// use the sqlDataAdapter
using(sqlDataAdapter)
{
// create a new DataTable that allows us
// to store data from tables within objects
DataTable employeeRank1Table = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the employeeRank1Table)
sqlDataAdapter.Fill(employeeRank1Table);
// TODO: compare Name and Password entered in the TextBox and PasswordBox to the data in the table
if (tbName.Text == *Name in Table* && pbPassword.Password == *Password in Table*)
{
EmployeeRank1 employeeRank1 = new EmployeeRank1();
employeeRank1.Show();
}
}
}
catch(Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
You don't need to retrieve the whole table in memory. Just use a WHERE statement in your sql command with Name = #nameparam AND Password = #passparam, use an SqlCommand to retrieve a SqlDataReader and if the reader has a row, then bingo, the user exists.
Said that, remember that storing passwords in clear text is a big NO NO in a security concerned application. See this q/a for the reasons
private void EmployeeRank1Button_Click(object sender, RoutedEventArgs e)
{
try
{
// create a query and select just the record we need
string query = "select * from EmployeeRank1 where Name = #name AND Password = #pass";
// A local sqlconnection in a using statement ensure proper disposal at the end of this code
using SqlConnection con = new SqlConnection(connectionstring);
con.Open();
// Let's the database do the work to search for the password and name pair
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = tbName.Text ;
cmd.Parameters.Add("#pass", SqlDbType.NVarChar).Value = tbPassword.Text ;
SqlDataReader reader = cmd.ExecuteReader();
// If the reader has rows then the user/pass exists in the db table
if(reader.HasRows)
{
EmployeeRank1 employeeRank1 = new EmployeeRank1();
employeeRank1.Show();
}
}
catch(Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
Note also that I used a local SqlConnection and not a global one inside a using statement. This is the correct way to use a Disposable object like a connection. Keeping a global connection is prone to resource leaks and all sorts of problems if something fails.
I just finished a database in C# with SQL. In my database I add data when I create the account for a person. I add the username, password, first and last name and the type (client or administrator).
When I am logging in all what I do is to check if username and password are correct. Here is the code.
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [dbo].[Cont] WHERE Username = #Username and Password = #Password;", con);
cmd1.Parameters.AddWithValue("#Username", this.Username.Text);
cmd1.Parameters.AddWithValue("#Password", this.Password.Text);
cmd1.Connection = con;
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd1);
da.Fill(ds);
con.Close();
bool loginSuccessful = ((ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0));
if (loginSuccessful )
{
MessageBox.Show("You logged in successfully!","Success!");
this.Visible = false;
f3.ShowDialog();
this.Visible = true;
}
else
{
MessageBox.Show("Invalid username or password!", "Error!");
}
}
And next what I want to do is to check if for this username and password the type is for client or administrator. And if is for administrator to entry in a form or if is for client to entry in another form.
How can I do? I need some ideas.
Here is the table:
You are retrieving the full row from your database table, so you have also retrieved the column that contains the usertype. You just need to check it after verifying the login
Here an example assuming that a "1" value means administrator, a "2" means normal user (of course you could change these constants to your actual values)
if (loginSuccessful )
{
string userType = ds.Tables[0].Rows[0]["Type"].ToString();
if(userType == "1")
{
// User is an administrator, go to admin form
}
else if(userType == "2")
{
// User is a normal user, go to user form
}
else
{
// Unexpected value, error message?
}
}
A side note, while you are using parameters there is still a security problem in your database/code logic. It seems that you store your password as a plain text. This could give to anyone that looks at your database table the possibility to know your users passwords. A password should never be stored in plain text. This site contains a lot of answer on how to correctly store passwords in a database
Start from here:
Best way to store passwords in a database
I'm building a user registration page that save user's info into a local database. However I get a SqlException error. Does anyone know what I'm doing wrong here? I'm developing the program in ASP.net and using the local database server.
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select count(*) from Table where userName = '" + txtUN.Text + "'";
SqlCommand comm = new SqlCommand(checkUser, conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("user already exist");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table(UserName, name, Address, e-Mail, IC, phone, password) values(#Uname, #name, #add, #mail, #ic, #phone, #pswrd) ";
SqlCommand comm = new SqlCommand(insertQuery, conn);
comm.Parameters.AddWithValue("#Uname", txtUN.Text);
comm.Parameters.AddWithValue("#name", txtName.Text);
comm.Parameters.AddWithValue("#add", txtAdd.Text);
comm.Parameters.AddWithValue("#mail", txtEmail.Text);
comm.Parameters.AddWithValue("#ic", txtIC.Text);
comm.Parameters.AddWithValue("#phone", txtPhone.Text);
comm.Parameters.AddWithValue("#pswrd", txtPsswrd.Text);
comm.ExecuteNonQuery();
Response.Redirect("Default.aspx");
Response.Write("registration was succesful");
conn.Close();
}
catch(Exception ex)
{
Response.Write("error"+ex.ToString());
}
}
You don't give the details of the exception, (ie: exception.Message and exception.InnerException.Message) but from your code I think you have the classical "Syntax Error Near ...."
This is caused by the presence of a reserved keyword in your query text. This reserved keyword is TABLE. You could fix it enclosing the word in square brackets (or better change the name of the table to somenthing more meaningful)
string checkUser = "select count(*) from [Table] where userName = ...";
A part from this, remember to use always parameterized queries also for simple tasks as looking for logins. Last but not least, storing password in clear text inside the database is a big NO-NO from a security standpoint. Everyone, having access to your database using some kind of administrative tool, could look at the passwords of your users, someone could intercept the network traffic between user pc and database server and see the credentials sent by your application. So, please, search for password hashing on this site to find a more secure approach to this problem
I have a SQL database named "administration" with usernames and roles.
What I would like to do with my ASP.NET application is:
once someone accesses my intranet site, I get their username using
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Then I check if that username is in my database. I assume I can do this with an IF EXISTS statement.
However I'm not sure how I would do the following: IF the user is in the database I want to display the Web Page as per their role (i.e. all pages are different Admin = see all content and buttons, User = all content no buttons).
However if their username is not in my database I will display a blank page or something along the lines of "Access Denied".
This is the way I have been asked to do it but I cant seem to work it out.
Is it possible?
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
after getting userName.
sqlconnection cn = new sqlconnection("give connectionstring");
cn.open();
sqlcommand cmd = new sqlcommand();
cmd.commandtext = "select * from "table"; // table name give.
cmd.connection = cn;
sqldatareader rdr = cmd.executereader();
while(rdr.read()){
if(stringName = rdr[columnnumber].toString());
flag = true;
}
if(flag)
//take decesion
else
// take decesion.
cn.close();
you can achieve it like this. u can use. it. bt there are some mistake in syntax i roughly write for u.
I'm new to C# and have a background in SQL so apologies if this is a very stupid query, but I have been trawling google for about 2 hours now and can't find what I need. If someone knows of an article they can point me to, that would be great.
I have a simple windows forms application, and I'm setting up a login box so that users have to enter their user ID to proceed.
I have a SQL Server DB (SQL 2005) with the following table:
Users
UserID (int); userName nvarchar(50)
I am using Visual Studio 2010
What I'm stymied by is how to check whether their userID exists in my SQL Table (called users...) I'm not going to put any code here because it's been rewritten from scratch so many times that a clean slate is probably best!
Ideally, I want the user to enter their user ID, and click 'login'. When they do this, if their userID is not valid in the DB table then I need it to give an error msgBox; if it is valid then it should log them in, passing their userID and userName (stored in the DB table) to a variable which I can use elsewhere in the application to populate fields.
I hope this makes sense, and I'm sure I've missed the perfect article out there which will explain it all - hopefully one of you kind people can point me in the right direction!
Thank you
You should make a simple SQL query with the userID the user entered, like
SELECT UserID from Users where userID= value. The executeNonQuery() will return the number of matches. If the returned value ==1, means that the userid exists in the database. If the returned value is different from 1, means that the userid not exists or it was registered multiple times. So, if is 1 then you cand call a different form to make different things, else you call anoter form or output a messagebox with an error message
/*table code
* create table login
(
id varchar(25),
pass varchar(25)
)
*
*
*
*
*/
string Connectstring = #"Data Source=DELL-PC;Initial Catalog=stud;Integrated Security=True";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(Connectstring);
cn.Open();
SqlCommand cmd = new SqlCommand("select * from log where id=#a and pass=#b", cn);
cmd.Parameters.AddWithValue("#a", textBox1.Text.ToString().ToUpper());
cmd.Parameters.AddWithValue("#b", textBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
if ((dr.Read() == true))
{
MessageBox.Show("The user is valid!");
Form2 mainForm = new Form2();
mainForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid username or password!");
}
}
Declare a connection string to Your database
string connString = #"Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabase;Integrated Security=True";
After this You can use a validate method below
private bool ValidateUserById(string connString, int id)
{
using (var conn = new SqlConnection(connString))
{
conn.Open();
var sqlString = string.Format("Select * From Users where Id = {0}", id);
using (var cmd = new SqlCommand(sqlString, conn))
{
return cmd.ExecuteScalar() != null;
}
}
}
Then on button click You can check the user
if (ValidateUserById(connString, Convert.ToInt32(textBox1.Text)))
{
//..
}
else
{
//..
}