Insert records by user who's connected Winforms - c#

I have a form (F1) where user will provide their respective credentials username and password .
After a sucessfull login , the controls moves to the Client Form (F2) and display welcome username in a label on it.
Client Form contains:
labels and textboxes(name, address, function , ...)
Button Insert
DataGridView bind to DB (name, address, function ,.., UserId)
Now , I want to insert a Client.
After filling textboxes, I want to add a Client a show it added by user who's connected.
Ex: if I logged with Username Rose after that add a client, in my datagridView , show me my row of insert added by Rose.
Code of my Login and passing username to Client Form
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
//textBox2.Text = Encrypt(textBox2.Text);
SqlConnection con = new SqlConnection("Data Source=User-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("select Username from [User] where Username='" + textBox1.Text + "' and Password='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Client c = new Client(dt.Rows[0][0].ToString());
v.Show();
}
else if (dt.Rows.Count > 1)
{
MessageBox.Show("Nom d'utilisateur et Mot de passe dupliqué !");
}
else
MessageBox.Show("Nom d'utilisateur ou Mot de passe incorrecte !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my code of Insert:
public Client(string username)
{
InitializeComponent();
lblUser.Text = username;
DisplayData();
FillData();
}
private void button1_Click(object sender, EventArgs e)
{
if ( comboBox2.SelectedValue != null && textBox1.Text != string.Empty && textBox2.Text != string.Empty && textBox4.Text != string.Empty)
{
string cmdStr = "Insert into Client (idUser,name,address,function,telephone,commentaire)values (#idUser,#name,#,address,#function,#telephone,#commentaire)";
SqlConnection con = new SqlConnection("Data Source=User-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
//The problem in the line below how Can I get the id of username,Error cannot convert string Rose to int.
cmd.Parameters.AddWithValue("#idUser",label.Text);
cmd.Parameters.AddWithValue("#name", (comboBox2.SelectedValue));
cmd.Parameters.AddWithValue("#,address", textBox1.Text);
cmd.Parameters.AddWithValue("#function", textBox2.Text);
cmd.Parameters.AddWithValue("#telephone", textBox4.Text);
cmd.Parameters.AddWithValue("#commentaire",txtArchive.Text);
int LA = cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Le Client a été ajouter avec succés !","Saisie Rendez-vous", MessageBoxButtons.OK, MessageBoxIcon.Information);
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Vérifier que tous les champs sont remplis !","Erreur",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
I am not able to figure out how to do this, I am very new to c# and trying to learn.
Thanks in Advance.

When checking for login, write your query this way:
SELECT [Id], [UserName] from [Users] WHERE [UserName]=#UserName AND [Password]=#Password
Then store both [Id] and [UserName] which you get from the query when the login is successful (the resultset contains one record). This way you can use username and id of the logged-in user every time you need.
For example:
var cmd = #"SELECT [Id], [UserName] FROM [Users] " +
#"WHERE [UserName] = #UserName AND [Password] = #Password";
var cn = #"Data Source=User-PC\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True";
var da = new SqlDataAdapter(cmd, cn);
da.SelectCommand.Parameters.AddWithValue("#UserName", textBox1.Text);
da.SelectCommand.Parameters.AddWithValue("#Password", textBox2.Text);
var dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
int id = dt.Rows[0].Field<int>("Id");
string userName = dt.Rows[0].Field<string>("UserName");
//...
}
Note:
You should used parametrized query to prevent SQL Injection attacks.

First and foremost, parameterize your queries for login! At the moment you are VERY susceptible to SQL Injection attack! Lest you get a visit from Little Bobby Tables.
In answer to your question, change the query on your login form to return both the user's Id and their username.
SqlDataAdapter sda = new SqlDataAdapter("select Id, Username from [User] where Username=#Username and Password=#Password", con);
Now, when you read the single result you can get Id from field 0 and username from field 1.
if (dt.Rows.Count == 1)
{
this.Hide();
var row = dt.Rows[0];
int userId = (int)row[0];
string username = (string)row[1];
Client c = new Client(userId, username);
v.Show();
}
Note also in that code, I'm passing both to the Client form. Update the constructor to save both pieces of information in local variables:
public class Client : Form
{
private int _userId;
public Client(int userId, string username)
{
InitializeComponent();
_userId = userId;
lblUser.Text = username;
DisplayData();
FillData();
}
}
Thereafter, you can use _userId anywhere you like in Client form. E.g. in the save button click:
cmd.Parameters.AddWithValue("#idUser",_userId);

Related

Login IF statement , the else always getting displayed, possible wrong written script

I always get the "else", even though I add the correct username and password
Photo with the script
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CONSTRing);
con.Open();
string q = "select * from LOGG where username = '" + tbu.Text + "' and password = '" + tbp.Text + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter Da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
Da.Fill(DT);
if (DT.Rows.Count == 1)
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
}
Photo with dbo.LOGG
I will try to be helpful with an answer since I can't yet comment ;_;
Below is some code I compiled as an improvement to the one you posted.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string q = "select 1 from LOGG where username = #username and password = #password";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("#username", tbu.Text); //
cmd.Parameters.AddWithValue("#password", tbp.Text); // using parameters to avoid intentional or accidental SqlInjection by the user
using (SqlDataReader reader = cmd.ExecuteReader())
{
try
{
con.Open();
if (reader.Read())
{
Form Main = new Form();
MessageBox.Show("Welcome " + tbu.Text);
this.Hide();
Main.Show();
}
else
{
MessageBox.Show("Check your Username and Password");
}
con.Close();
cmd.Dispose();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Oops something went wrong. Error: " + ex.Message);
}
}
}
This is how I would write a quick version of what you wanted. Now, it might not help you out with your issue but it fixes some of the more obvious issues that might come up.
The Try and Catch block are there just for basic error handling to let the user know something went wrong.
The SqlDataReader is enough to notify you if a user with the given parameters exists in the database.
The check you used before
if (Dt.Rows.Count == 1)
{
//...
}
would fail to trigger if your query returned more than 1 row, which should not happen if the Table is created correctly. Check for duplicate entries in your table.

System.Data.SqlClient.SqlException: 'Incorrect syntax near '`'.'

I'm trying to create a login field using ASP.NET which will take input from the textbox fields and check them against the "user" table in my database. The columns are User ID and Password. But an error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '`'
appears when the login form is used. I don't see any issue with the syntax...
I'm new to this so please excuse me if the error is obvious!
public partial class Login_Page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblErrorMessage.Visible = false;
SqlConnection con = new SqlConnection("Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True");
con.Open();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True";
con.Open();
string userid = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
SqlCommand cmd = new SqlCommand("select `user id`,`password` from user where `user id`='" + txtUsername.Text + "'and `password`='" + txtPassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["username"] = txtUsername.Text.Trim();
Response.Redirect("Homepage.aspx");
}
else
{
lblErrorMessage.Visible = true;
}
con.Close();
}
}
Just remove the '`' characters to make it work.
Your code is vulnerable to injection try to add values with SqlCommand.Parameters.Add() method.
Use this code:
SqlCommand cmd = new SqlCommand("select userid, password from user where user id = #id and password = #password", con);
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = txtPassword.Text;
And as #marc_s mentioned, user id is not a valid column name, it should be like userid or if it has space in it is should be like: [user id]
there are many issues with your code :
Do not store plain text password in your program or app config.
Do not embed connection string into your program
` is not SQL Server Syntax.
never use string concatenation in your queries specifically if inputs are coming from users. Use Parameterized queries.
.
using (SqlCommand cmd = new SqlCommand("select 1 from tbl where id=#id", conn))
{
var idParameter = new SqlParameter()
idParameter.ParameterName = "#id";
idParameter.Value = 1234;
cmd.Parameters.Add(idParameter);
....
}
always dispose objects when you finish your work with them. For this use using(SqlConnection conn = new SqlConnection()).
all methods which implements IDisposable can be used within using statement

Admin and User Login C#

I'm using Access db. I need to validate if its Admin or user because I want to open different forms for them. But I can't find a way to do it. I used a checkbox to register if the employee is admin or not like this:
private void button2_Click(object sender, EventArgs e)
{
string strincon = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\flavi\Desktop\Pet&Shop.2\PetShop\TelaAbertura\bin\Debug\DatabasePS.mdb;Persist Security Info=True";
string comando = "INSERT INTO Funcionario (Nome, Login, Senha, Email, Cargo, Admin) Values (#Nome, #Login, #Senha, #Email, #Cargo, #Admin) ";
OleDbConnection con = new OleDbConnection(strincon);
OleDbCommand com = new OleDbCommand(comando, con);
com.Parameters.Add("#Nome", OleDbType.VarChar).Value = txtNome.Text;
com.Parameters.Add("#Login", OleDbType.VarChar).Value = txtLogin.Text;
com.Parameters.Add("#Senha", OleDbType.VarChar).Value = txtSenha.Text;
com.Parameters.Add("#Email", OleDbType.VarChar).Value = txtEmail.Text;
com.Parameters.Add("#Cargo", OleDbType.VarChar).Value = txtCargo.Text;
com.Parameters.Add("#Admin", OleDbType.Boolean).Value = checkBox1.Checked;
This is working fine, but in the login form there's no difference because I don't know how to validate the checkbox with the login and password, so it's like this.
OleDbDataAdapter da;
DataTable dt = new DataTable();
da = new OleDbDataAdapter("Select * from Funcionario where Login='" + txtLogin.Text + "'and Senha= '" + txtSenha.Text + "'", con); //Senha = Password
da.Fill(dt);
if (dt.Rows.Count > 0)
{
FrmPrincipal frm = new FrmPrincipal();
frm.Show();
this.Visible = false;
}
else
{
MessageBox.Show("Login ou Senha Inválidos", "Ocorreu um Erro de Autenticação", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLogin.Clear();
txtSenha.Clear();
}
if (dt.Rows.Count > 0)
{
// you should have one row in the table. check for admin.
if(dt.Rows[0]["Admin"] == true)
{
etc.
As stated in the comments, add parameters to your adapter's query. Always use parameters. They are used to "clean" user input, if someone is trying to hack your database.

How to get value of DataTable Row in C# asp.net

i am learning asp.net with c# by myself, and i have a problem with DataRows,
in db i have users table and there is isadmin column which value is int,
i want to redirect users to different page and admins to admin page, but the problem is all users redirects to admin page.
Here is my code;
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT username, pass FROM users
where username = '"+txtUser.Text+"'
and pass='"+txtPass.Text+"'"
, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
SqlCommand cmd1 = new SqlCommand("Select username, isadmin From users", conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
conn.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt1.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
/*Response.Write("<script>
alert('Please enter valid Username and Password')
</script>"); */
}
Can you please tell me what is wrong?
Use the first query with dt as it's based on a single user. The problem is dt1 gets all users and the first record in that datatable is an admin
if (dt.Rows[0]["isadmin"].ToString() == "1") {
Remove the second query with dt1 and make sure you add isadmin to the first SQL query.
SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = #UserName and pass= #Pass", conn);
See how I use parameterized username and password, that is to protect against SQL injection, definitely read up on that!!!
Please Try this
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd =
new SqlCommand(
"SELECT username, pass, isadmin FROM users where username = '" + txtUser.Text + "' and pass='" + txtPass.Text +
"'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
//Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
In your first query you need to get isadmin also and on the base of that result you can check either it is 1 or not and can redirect to what ever page you like. So it will be as follow:
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(conString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = '"+txtUser.Text+"' and pass='"+txtPass.Text+"'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
//Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
There are several things wrong with your code:
All users are redirected to the admin page since you are checking the isAdmin in the wrong query.
Your second query has no where clause which means it will return all the users in the table. The first user it returns has the isAdmin value of 1.
You don't actually need two queries, just one.
You must use parameterized queries, otherwise you are leaving an open door to SQL injection attacks.
wrap all IDisposable instances in a using statement.
Your code should look more like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection(conString))
{
using(SqlCommand cmd = new SqlCommand("SELECT username, pass, isadmin FROM users where username = #UserName and pass=#Pass", conn))
{
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = txtUser.Text;
cmd.Parameters.Add("#Pass", SqlDbType.VarChar).Value = txtPass.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}
if (dt.Rows.Count > 0)
{
Session["id"] = txtUser.Text;
if (dt1.Rows[0]["isadmin"].ToString() == "1")
{
Response.Redirect("~/admin.aspx");
}
else
{
Response.Redirect("~/default.aspx");
}
//Response.Redirect("~/default.aspx");
Session.RemoveAll();
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
//lblMsg.Text= msg ;
//Response.Write("<script>alert('Please enter valid Username and Password')</script>");
}
}
Your second query lacks the filter on a user name:
Select username, isadmin From users
So whatever it fetches - if the first row contains 1 as IsAdmin, all users will be redirected to the admin page.

Create a login application with local database in visual studio

Please I am really having trouble creating a simple login application in C#. I just want to create a login form and whenever I enter the username and password it checks from the database if it exists or not, and since I don't have much knowledge about this, I can't manage to do it!
I created a windows form in VS express, and set the design with textboxes for username and password and a login button. Then I added a new element to my project and chose local database ( dataset). In the left, I have two areas: one named data connection with "database1.sdf" in it, and "datasource" with "database1" in it.I have no idea what those two mean, I just created a new user table in the "database1.sdf" and added id,username and password columns. But after that, having only those two elements, I have no clue how to perform what I want to do. What code should I write to connect to the database in order to check the values, and where do I write this code?
I tried many codes online, but it doesn't work :/
I am sorry if my questions seem stupid, but I really need your help ! Thanks !
this is the snippets for visual studio c# coding that i am doing for a system project in our major subject as a programmer
private void btnLogin_Click(object sender, EventArgs e)
{// you can have the database location at your own database
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=H:\school\copro3\EnrollmentSystemProgram\EnrollmentSystemProgram\Login.mdf;Integrated Security=True;");
//you can use your database table and its contents for the DataAdapter
SqlDataAdapter sda = new SqlDataAdapter("SELECT COUNT (*) FROM tblLogin WHERE Username= '" + txtUser.Text + "' AND Password= '" + txtPass.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
new frmDashboard().Show();
}
else
{
lblNotify.Show();
lblNotify.Text = "Login Unsuccessful";
txtUser.Text = "";
txtPass.Text = "";
}
}
private void frmLogin_Load(object sender, EventArgs e)
{
lblNotify.Hide();
}
Do not do this
SELECT COUNT (*) FROM tblLogin WHERE Username= '" + txtUser.Text + "' AND Password= '" + txtPass.Text + "'"
This opens for exploits
Store the Username in a varible like Username = #Username and then use
sqlCommand.Parameters.AddWithValue("#Username", txtUser.Text);
This is the code that I inserted for our program thesis for the login button
string select = #"Select * From tblUsers Where Username = #Username and Password = #Password and PositionInTheCompany = #Privilege";
using (con)
{
con.Open();
using (cmd = new SqlCommand(select, con))
{
cmd.Parameters.AddWithValue("#Username", txtLoginUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtLoginPassword.Text);
cmd.Parameters.AddWithValue("#Privilege", cmbLoginUsertype.Text);
using (read = cmd.ExecuteReader())
{
if (read.HasRows)
{
// you can also use the else if statements here for the user privileges
read.Read();
this.Hide()
dashboard.Show();
txtLoginPassword.Text = "";
txtLoginUsername.Text = "";
cmbLoginUsertype.Text = "";
}
else
{
lblLoginMessage.Show();
lblLoginMessage.Text = "Access Denied!";
txtLoginPassword.Text = "";
txtLoginUsername.Text = "";
cmbLoginUsertype.Text = "";
}
}
}
}
For the SqlConnection, i used a class called ConnectionString
public partial class frmLogin : Form
{
ConnectionString cs = new ConnectionString();
frmDashboard dashboard = new frmDashboard();
public SqlConnection con = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public SqlDataReader read;
public frmLogin()
{
InitializeComponent();
}
private void frmLogin_Load(object sender, EventArgs e)
{
lblLoginMessage.Hide();
con = new SqlConnection(cs.conStr);
}
I don't know if using class for the connection causes errors, but i used it because I don't want to make my code have lots of snippets.
For the ConnectionString class
class ConnectionString
{
public string conStr = // the connection source of the database
}
I use one database for multiple tables

Categories

Resources