Administrator exclusive page? - c#

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.

Related

How to pass value from Main WIndow textbox to other User Control?

Aim:
I am aiming to pass value from main window i.e. the log in screen to other User Control forms.
This is MainWindow.Xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["Technical_Application.Properties.Settings.ConnectionString"].ConnectionString;
string query = "SELECT count(*) from users where username = '" + txtUsername.Text + "' and password = MD5('" + txtPassword.Password + "')";
using (var conn = new MySqlConnection(connString))
{
conn.Open();
using (var cmd = new MySqlCommand(query, conn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
if(count == 1)
{
Dashboard dashboard = new Dashboard();
dashboard.Show();
this.Close();
}
else
{
MessageBox.Show("Username or Password unvalid", "Login Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
conn.Close();
}
}
}
It opens up the dashboard. I now have a ListViewMenu directed to specific User Control forms, and opens on the dashboard.
Code to open different user controls
private void ListViewMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int index = ListViewMenu.SelectedIndex;
MoveCursorMenu(index);
switch (index)
{
case 0:
GridPrincipal.Children.Clear();
GridPrincipal.Children.Add(new UserControlMain());
break;
case 1:
GridPrincipal.Children.Clear();
GridPrincipal.Children.Add(new UserControl1());
break;
default:
break;
}
}
Question:
From MainWindow the text box with name of txtUsername how can I transfer the text value to other UserControl windows?
Wouldnt it be easy to add a string property in your Dashboard class, and pass it into that - like:
Dashboard dashboard = new Dashboard();
dashboard.UserName = txtUsername.Text;
Then you can pass the same string value down to other controls. Of course, ideally, you would implement the MVVM pattern and use bindings.

Show username and user id on Label after Login Form

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

Retrieving data from a Datatable in C#

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.

Else...if statements not working in my form...? Can I use try-catch instead..?

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!

How to display the correct amount of records for a chart in visual studios c#

Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
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.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button

Categories