I have a data able that has the three columns: Username Password and Name.
I have a login in screen that checks that checks the username and password to allow for access or not. I am trying to display the Name of the user onto another Form, but what I have is not working.
The program runs until i press login and then an IndexOutOfRangeException is shown. I feel like I am not calling the correct cell that the data is located in, but I can not figure it out. I am very new to data tables.
Login Form:
namespace Inventory_Program
{
public partial class Login : Form
{
public string name;
public Login()
{
InitializeComponent();
}
/*
* Used when user accepts to login. username and password must be correct or error message will display
* Using a table in sql form.
*/
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\brand\Documents\Data.mdf; Integrated Security = True;");
SqlDataAdapter adapter = new SqlDataAdapter("Select Count(*) From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'", connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
name = dt.Rows[0][3].ToString();
this.Hide();
MainGUIPanel mainview = new MainGUIPanel();
mainview.Show();
}
else
{
MessageBox.Show("Username or Password Incorrect! Try Again!");
}
} //end of login button
//can canel out of login in screen, closes window.
private void cancelButton_Click(object sender, EventArgs e)
{
this.Close();
} //end of cancel button
public string getName()
{
return name;
}
}
}
MainGuiView:
namespace Inventory_Program
{
public partial class MainGUIPanel : Form
{
Login login = new Login();
public MainGUIPanel()
{
InitializeComponent();
//runs the current time and data
currentTime.Start();
}
//Method is adding a horizontal line to the top panel
private void topControlPanel_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Pen pen = new Pen(Color.Black, 1);
graphics.DrawLine(pen, 1091, 93, 00, 93);
graphics.Dispose();
nameLabel.Text = login.getName();
}
//allows for the current time and date to be displayed in the top panel
private void currentTime_Tick(object sender, EventArgs e)
{
DateTime dateTime = DateTime.Now;
}
private void inventoryButton_Click(object sender, EventArgs e)
{
}
}
}
Select Count(*) From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'"
Puts only one item in your adaptor: a table in it with nothing more than a number (from Count(*) at dt.Rows[0][0].
You would want something like:
Select UserName From Login where Username='" + usernameTextfield.Text + "' and Password = '" + passwordTextfield.Text + "'"
See Below! This is very vulnerable to all them hackers out there!
and
name = dt.Rows[0][0].ToString();
A word of caution, and this is important: I really encourage you to look up sql server injection attacks. Your code is very vulnerable to this. A marginally experienced programmer could log into your application or wipe out your database without credentials, just by typing some code in your username or password field.
The error is located at: name = dt.Rows[0][3].ToString();.
You select: count(*), which only will return
1column.
You need to select the columns you want to show.
you don't need to count the results since your where clause should select distinct results. Instead check if the datatables rows.count is larger than 1.
Related
I want create a small project in M V C pattern and I want to separate my code into three parts.
I used Model in one part and view Controller in another but now I want to separate controller as well.
this is from event now i want to use this in controller and just call it here:
public void button1_Click(object sender, EventArgs e)
{
try
{
string query = "Select * from [UserTbl] where username='" + txtusername.Text + "' and password='" + txtpassword.Text + "'";
DBConnect db = new DBConnect();
DataTable dt = db.GetData(query);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login successful");
}
else
{
MessageBox.Show("Username and Password Incorrect");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
this is control class
public class LoginControl
{
}
In its simplest, most literal form,
public class Authentication
{
public void Login(string userName, string password)
{
try
{
string query = "Select * from [UserTbl] where username='" + userName + "' and password='" + password + "'";
DBConnect db = new DBConnect();
DataTable dt = db.GetData(query);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login successful");
}
else
{
MessageBox.Show("Username and Password Incorrect");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public void button1_Click(object sender, EventArgs e)
{
var authentication = new Authentication();
authentication.Login(txtusername.Text, txtpassword.Text);
}
I'm sidestepping the fact that this doesn't seem to do anything other than display a result. Presumably you're doing something else not seen in this code. Also, creating SQL by concatenating the user ID and password creates a serious SQL injection risk, so you should use parameters instead.
This might be sufficient if the method is absolutely only intended to be used in the context of this single application. But what if you want this to be usable in some context where MessageBox.Show isn't available? Maybe you want to be able to reuse this login code outside of any Windows Forms app. (It's good if we can minimize the amount of our code that is tied to any UI.)
You can separate that by having your method return a result. That way the method indicates whether something was successful, and your UI code determines if or how to communicate that to a user. In that case your method could look more like this:
public bool Login(string userName, string password)
{
string query = "Select * from [UserTbl] where username='" + userName + "' and password='" + password + "'";
DBConnect db = new DBConnect();
DataTable dt = db.GetData(query);
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
// or, just
// return dt.Rows.Count > 0;
}
In many cases it would make sense to return some sort of Result class with more detail, but for this example, a bool representing success of failure is enough.
Now your UI code can do this:
public void button1_Click(object sender, EventArgs e)
{
try
{
var authentication = new Authentication();
var success = authentication.Login(txtusername.Text, txtpassword.Text);
if (success)
{
MessageBox.Show("Login successful");
}
else
{
MessageBox.Show("Username and Password Incorrect");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you needed to reuse the above code and didn't want to duplicate it you could create a separate control, moving both the button and the click handler into it.
I'm assuming this is WinForms?
You could add a public function to LoginControl and just call it from the button1_Click event handler.
You won't have access to the form's controls within LoginControl, so you'll have to pass the values you need from the form's controls to the function you write. Your function could return something to indicate whether the login was successful or not, that way you can show the correct message from the button1_Click event handler.
I'm currently making a windows form login system and I've worked out how to set up a general everyone can see the main page system but for the admin i want it to open a new form (form3) which will contain customer orders.
i need it to open up from Login Button.Click just like form2 opens to show the store page for generalised users. i don't have a column in my table for user roles either.
I've tried if else statements and run into issues with bools not excepting strings etc.
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Aliena_Store
{
public partial class Form1 : Form
{
//string ConnectionState = "";
public Form1()
{
InitializeComponent();
}
MySqlConnection connection = new MySqlConnection("server=localhost;user=root;database=Aliena_Store;port=3306;password=Blackie");
MySqlDataAdapter adapter;
DataTable table = new DataTable();
private void UsernameLogin_TextChanged(object sender, EventArgs e)
{
}
private void PasswordLogin_TextChanged(object sender, EventArgs e)
{
}
private void LoginButton_Click(object sender, EventArgs e)
{
adapter = new MySqlDataAdapter("SELECT `username`, `password` FROM `User_Details` WHERE `username` = '" + UsernameLogin.Text + "' AND `password` = '" + PasswordLogin.Text + "'", connection);
adapter.Fill(table);
var usernameSaved = UsernameLogin.Text;
var passwordSaved = PasswordLogin.Text;
Panel panel1 = new Panel();
if (table.Rows.Count <= 0)
{
panel1.Height = 0;
var result = MessageBox.Show("Username/Password Are Invalid or does not exist. Please sign up or retry your details");
}
else
{
panel1.Height = 0;
this.Hide();
if (table.Rows.Count >= 0)
{
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
object user = UsernameLogin.Text;
object password = PasswordLogin.Text;
if (user = "root" & password = "Pa$$w0rd")
{
nextForm = new Form3();
}
else
{
nextForm = new Form2();
}
nextForm.ShowDialog();
}
//Form2 f2 = new Form2();
//f2.ShowDialog();
//if login is successful needs to lead to another screen - if matches my account standard store screen or make root account just for the admin page
}
table.Clear();
}
private void EmailSignUp_TextChanged(object sender, EventArgs e)
{
}
private void UsernameSignUp_TextChanged(object sender, EventArgs e)
{
}
private void PasswordSignUp_TextChanged(object sender, EventArgs e)
{
}
private void SignUpButton_Click(object sender, EventArgs e)
{
//connection.Open();
string Query = "insert into User_Details (Email,Username,Password) values('" + this.EmailSignUp.Text + "', '" + this.UsernameSignUp.Text + "','" + this.PasswordSignUp.Text + "');";
//string insertQuery = "INSERT INTO User_Details(Email,Username,Password)VALUES('" + EmailSignUp.Text + "','" + UsernameSignUp.Text + "'," + PasswordSignUp.Text + ")";
MySqlCommand command = new MySqlCommand(Query,connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data Inserted");
connection.Close();
}
else
{
MessageBox.Show("Data Not Inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}
}
A couple of things.
You need a User object in your application that stores user properties. This object can have an IsAdmin property that you can use later in your code.
Alternately, if you don't want to create and maintain a User object, you make another call to the database to see whether or not the user is an admin and store the result local to your method.
You then instantiate Form3 instead of Form2 based on whether or not the user is an admin.
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
if (user.IsAdmin) {
nextForm = new Form3();
} else {
nextForm = new Form2();
}
nextForm.ShowDialog();
PS: I hope you are not storing passwords in plain text in your database like it seems you are.
I'm creating a school project. One of my ideas is to after the Login Form the Main Form will show on a label the user connected and the RM (user code basically), but i don't know how to get the Username and RM from the Login Screen and get the RM from the database.
Login Screen Code:
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=ROCHA-PC\SQLSERVER2014;Initial Catalog=Usuarios;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from users where usuario = '" + textBox1.Text + "' AND senha = '" + textBox2.Text + "'" , con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
frmTelaInicial nform = new frmTelaInicial();
nform.Show();
}
else
{
MessageBox.Show("Erro ao logar");
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
How can I get the current user connected and show it on the label?
Go to the constructor of the main window and add the parameters you want for example
step 1)
here pass the parameters you want
frmTelaInicial nform = new frmTelaInicial(LoggedUseName,RM);
step 2)
at the constructor of the frmTelaInicial add the two parameters like below
public frmTelaInicial(string LoggedUserName,string RM)
{
//here you have the passed values
}
step 3)
add two labels on the frmTelaInicial window and update their values with the passed values LoggedUserName and RM
I'm making a login window with username and password. I have a data table which has the user information and I am using an else..if statement when a user tries to login (towards the end of the code). It's suppose to check the username and password and verify that it matches what's in the table. If it doesn't, than a messagebox was suppose to appear. Also, towards the last else...if statement the user JANITOR doesn't login at all! What can be causing this issue? They all login fine except that last user JANITOR and my messagebox isn't showing up!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LOGINPAGE
{
public partial class Room : Form
{
public Room()
{
InitializeComponent();
PassText.PasswordChar = '*';
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
FloorSelection ss = new FloorSelection();
ss.Show();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
private void EXIT_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
private void xButton1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mohamed\Documents\UserData.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From dbo.[LOGIN] where username='" + UserText.Text + "' and Password ='" + PassText.Text + "'", con);
FloorSelection ss = new FloorSelection();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select TYPE From dbo.[LOGIN] where username='" + UserText.Text + "' and Password ='" + PassText.Text + "'", con);
FloorSelection ss1 = new FloorSelection();
DataTable dt1 = new DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "FACULTY")
{
this.Hide();
FACULTY ff = new FACULTY();
ff.Show();
}
else if (dt1.Rows[0][0].ToString() == "ADMINISTRATOR")
{
this.Hide();
ADMINISTRATOR Ad = new ADMINISTRATOR();
Ad.Show();
}
else if (dt1.Rows[0][0].ToString() == "JANITOR")
{
this.Hide();
JANITOR jt = new JANITOR();
jt.Show();
}
else
{
MessageBox.Show("Please check your username and password");
}
}
}
private void label3_Click(object sender, EventArgs e)
{
label3.BackColor = Color.Transparent;
}
private void UserText_TextChanged(object sender, EventArgs e)
{
UserText.BackColor = Color.Empty;
}
private void PassText_TextChanged(object sender, EventArgs e)
{
PassText.BackColor = Color.Empty;
}
}
}
PICTURE OF MY TABLE DATA
There is nothing wrong with the logical flow. My guess is that you have white space in your input. Try this:
string userName = UserText.Text.Trim();
string passwrd = PassText.Text.Trim();
This will remove spaces and tabs from the input. Now replace all the places you use UserText.Text with userName and also replace PassText.Text with passwrd.
You might also want to try creating a variable for that TYPE field like this:
string userType = dt1.Rows[0][0].ToString().Trim();
For example:
private void xButton1_Click(object sender, EventArgs e)
{
string userName = UserText.Text.Trim();
string passwrd = PassText.Text.Trim();
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mohamed\Documents\UserData.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From dbo.[LOGIN] where username='" + userName + "' and Password ='" + passwrd + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
I hope that helps.
I assume this is a learning project that won't be used in a real world scenario. If not please rethink what you are doing. You really shouldn't be rolling your own security system. You have a classic SQL injection attack vulnerability in your code that would compromise your entire system.
If this is a school project continue with what you are doing, but you might want to ask you professor what a SQL injection attack is.
Good luck!
I'm working with c#, in vs 2008, framework 3.5, I need to save the username and when
the user log in, it shows he/her first and last name, at this point can save it, and
that is what I want but need to show to the user not his/her username just the first and
last name. here is my code, thanks in advance.
//code in the login
ClPersona login = new ClPersona();
bool isAuthenticated = login.sqlLogin1((txtUsuario.Text), (txtPassword.Text));
if (isAuthenticated)
{
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
//code in the form where shows the username but I want the first and last name
public partial class menu2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
if (!IsPostBack)
//ClPersona class
public Boolean sqlLogin1(string nombreUsuario, string password)
{
string stSql = "select * from usuarios where usuario='" + nombreUsuario + "' and
pass='" + password + "'and id_rol='1'";
Bd miBd = new Bd();
DataTable dt = miBd.sqlSelect(stSql);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//return ds;
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
Modify two sections
First
if (isAuthenticated)
{
Session["YouObject"] = login;//<--
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
Second
protected void Page_Load(object sender, EventArgs e)
{
if(Session["YouObject"] != null)
{
ClPersona obj = (ClPersona )Session["YouObject"];
lblNombreUsuario.Text = string.Format("{0}-{1}", obj.FirstName, obj.LastName )
}
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
....
}