How do you display data that is retrieved from database according to the current login user? I know that I should declare the id, but I don't really know how...
I have 2 tables in SQL.
User:
ID || Name || Last_Name || date ||
List
ID || Product || description || user_id
private void BindGridView()
{
string constr = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = #"SELECT * From List where ID = #ID";
cmd.Parameters.AddWithValue("#ID", ?);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
according to your table the query should be
select * from list where user_id = id
here id is the userid passed to the method
e.g private void BindGridView(int id)
another way is to use session
and to store id after login you have to store it in session
session["UserId"] = userid;
and you can use it in function like
int userid = Convert.ToInt32(session["UserId"]);
cmd.CommandText = "SELECT * FROM list where user_id = " + userid + "";
and also dont forget to use conn.Open() and conn.Close() after executing query
Related
I am creating a WPF application with a MySQL database, I wrote the following code so that the username would be displayed in the Lable, but for some reason it gives me only the last user in my database. How can I make it so that I would log into the account and see information only on it? Those. I go under user 1 and I will see user 1 in the field, and for example not user 101
"server=; username=; password=; database=u1831430_excurtion";
MySqlConnection connectionString = new MySqlConnection(conn);
MySqlCommand command = connectionString.CreateCommand();
command.CommandText = $"SELECT `FirstName` FROM `Login` WHERE 1";
command.CommandText = $"SELECT `LastName` FROM `Login` WHERE 1";
//command.CommandText = $"SELECT `ID` FROM `Login` WHERE 1";
MySqlDataReader myReader;
try
{
connectionString.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
//ID_Label.Content = myReader[0].ToString();
FN_Label.Content = myReader[0].ToString();
LN_Label.Content = myReader[0].ToString();
}
}
I tried to add a field with an ID, but after I did that, all my Labels began to fill in with the last ID from the table
To make it possible to display the last name and first name, you need:
Create a class where variables will be stored:
user ID
Username
public class global
{
public static int userid;
public static string username;
}
Next, when checking strings for fullness, you need to declare variables and translate them into a string
DB db = new DB();
string userName = TB_Name.Text;
string userPass = PB_Password.Password;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM Login WHERE Login = #uL AND Password = #uP AND Role = 2" , db.GetConnection());
command.Parameters.Add("#uL", MySqlDbType.VarChar).Value = userName;
command.Parameters.Add("#uP", MySqlDbType.VarChar).Value = userPass;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
global.userid = Convert.ToInt32(table.Rows[0]["ID"].ToString());
global.username = table.Rows[0]["Login"].ToString();
UserPanel();
}
After that, in the user line, you need to assign the value of the user ID to your label with the ID
string query = $"SELECT FirstName, LastName, ID, img FROM Login WHERE ID = {ID_Label.Content = global.userid}";
MySqlCommand cmd = new MySqlCommand(query, db.GetConnection());
db.openConnection();
MySqlDataReader myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
FN_Label.Content = myReader.GetString("FirstName");
LN_Label.Content = myReader.GetString("LastName");
}
}
To make it possible to display the last name and first name, you need:
Create a class where variables will be stored:
user ID
Username
public class global
{
public static int userid;
public static string username;
}
Next, when checking strings for fullness, you need to declare variables and translate them into a string
DB db = new DB();
string userName = TB_Name.Text;
string userPass = PB_Password.Password;
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT * FROM Login WHERE Login = #uL AND Password = #uP AND Role = 2" , db.GetConnection());
command.Parameters.Add("#uL", MySqlDbType.VarChar).Value = userName;
command.Parameters.Add("#uP", MySqlDbType.VarChar).Value = userPass;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
global.userid = Convert.ToInt32(table.Rows[0]["ID"].ToString());
global.username = table.Rows[0]["Login"].ToString();
UserPanel();
}
After that, in the user line, you need to assign the value of the user ID to your label with the ID
string query = $"SELECT FirstName, LastName, ID, img FROM Login WHERE ID = {ID_Label.Content = global.userid}";
MySqlCommand cmd = new MySqlCommand(query, db.GetConnection());
db.openConnection();
MySqlDataReader myReader = cmd.ExecuteReader();
try
{
while (myReader.Read())
{
FN_Label.Content = myReader.GetString("FirstName");
LN_Label.Content = myReader.GetString("LastName");
}
}
I Created a program which will check into a hotel and update the back-end.
I am having a problem connecting and changing the UserID on my Rooms Table.
Tables are :
Users:
UserID - PK, Auto Number
Username - Short Text
Password - Short Text
Rooms
RoomID - PK, Auto Number
Room_Number - Number
UserID - FK, Number
Updatable Query
PARAMETERS parUsername Short, parRoom_Number Short;
UPDATE Rooms SET UserID = (SELECT UserID FROM Users WHERE Username = [parUsername])
WHERE Room_Number=[parRoom_Number];
C# Code
Form1
MessageBox.Show("Login Successful");
Home home = new Home();
home.Show();
home.LabelText = this.txtUsername.Text;
Home Form
public string LabelText
{
get
{
return this.lblUsername.Text;
}
set
{
this.lblUsername.Text = value;
}
}
CheckIn Usercontrol
Home home = new Home();
try
{
string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/Hotel.accdb";
using (var con = new OleDbConnection(ConnString))
{
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Query2";
cmd.Parameters.Add("parUsername", home.LabelText);
cmd.Parameters.Add("parRoom_Number", lbRooms.SelectedItem);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Instead of using a sub-query, try this
PARAMETERS parUsername Text ( 255 ), parRoom_Number Long;
UPDATE Rooms, Users SET Rooms.UserID = Users.UserID
WHERE Rooms.Room_Number = [parRoom_Number] AND Users.Username = [parUsername];
First I altered the Query2 stored procedure. Passing the User ID and Room number (changed this to a Number datatype to match the table definition (not a Short as in you question.)
PARAMETERS parUserID Number, parRoom_Number Number;
UPDATE Rooms SET UserID = [parUserID]
WHERE Room_Number=[parRoom_Number];
Then I modified your code to a separate query to get the UserId.
Home home = new Home();
int userID;
try
{
string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/Hotel.accdb";
using (var con = new OleDbConnection(ConnString))
{
con.Open();
//Passing the query and the connection directly to the constructor
using (OleDbCommand cmd1 = new OleDbCommand("SELECT UserID FROM Users WHERE Username = #UserName;", con))
{
cmd1.Parameters.Add("#UserName", OleDbType.VarChar).Value = home.LabelText;
userID = (int)cmd1.ExecuteScalar();
}
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Query2";
cmd.Parameters.Add("parUserID", OleDbType.Numeric).Value = userID;
cmd.Parameters.Add("parRoom_Number",OleDbType.Numeric ).Value = (int)lbRooms.SelectedItem;
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Please try the below option, it should work
UPDATE Rooms A,(SELECT UserID FROM Users WHERE Username = 'Test') B SET A.UserID = B.UserID WHERE Room_Number=1;
i have table where have 5 columns :
i wrote the code like this :
String SQLQuery = "SELECT count(*) FROM aspnet_Users where Username=#uname AND Password = #pwd";
using(SqlConnection sqlConnection = new SqlConnection(strConnection))
using(SqlCommand command = new SqlCommand(SQLQuery, sqlConnection))
{
sqlConnection.Open();
command.Parameters.AddWithValue("#uname", Username);
command.Parameters.AddWithValue("#pwd", Password);
int result = Convert.ToInt32(command.ExecuteScalar());
boolReturnValue = (result > 0);
}
here few more extra information i needed,if above Username and password is correct,
what i need is : userid, and role column data
Why you aren't doing that instead ?
string SQLQuery = "SELECT UserId FROM aspnet_Users where Username=#uname AND Password = #pwd";
[...]
object result = command.ExecuteScalar();
if (result == null)
{
boolReturnValue = false;
}
else
{
long userId = Convert.ToInt64(result);
boolReturnValue = true;
}
String SQLQuery = "SELECT Top 1 UserId, role FROM aspnet_Users where Username=#uname AND Password = #pwd";
using(SqlConnection sqlConnection = new SqlConnection(strConnection))
using(SqlCommand command = new SqlCommand(SQLQuery, sqlConnection))
{
sqlConnection.Open();
command.Parameters.AddWithValue("#uname", Username);
command.Parameters.AddWithValue("#pwd", Password);
SqlDataReader Reader = null;
if (sqlConnection.State == ConnectionState.Closed || sqlConnection.State == ConnectionState.Broken)
sqlConnection.Open();
Reader = command.ExecuteReader();
if (Reader.Read())
{
int UserId = Convert.ToInt32(Reader["UserId"]);
string Role = Convert.ToString(Reader["role"]);
}
}
Why don't you just get the UserId instead of the Count(*) so your query should look like this :
SELECT UserId FROM aspnet_Users where Username=#uname AND Password = #pwd
Username should be unique so you shouldn't retrieve more than one row...you can add a Top 1 in case you have multiple same username with same password.
Try this Code
SELECT count(*),userid,role FROM aspnet_Users where Username=#uname AND Password = #pwd Group by userid,role
Bussiness Access Layer :
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
id = cmd.ExecuteNonQuery();
cmd = null;
con.Close();
return id;
}
Login.cs
protected void Button1_Click(object sender, EventArgs e)
{
int id = BusinessAccessLayer.login(userlogin.Text.Trim(), pwdlogin.Text.Trim());
if (id > 0)
{
message.Text = " valid";
}
else
{
message.Text = "in valid";
}
}
Okay, there are multiple things wrong here:
1) You should use using statements to make sure you close your connection and command even if exceptions are thrown
2) You should use parameterized SQL instead of putting the values directly into your SQL statement, to avoid SQL Injection Attacks
3) You appear to be storing passwords in plain text. Don't do that. Use a salted hash or something similar (ideally something slow to compute).
4) You're ignoring .NET naming conventions; methods should be in PascalCase
5) Your SQL never looks at any field which appears to be related to the user ID. It's not clear what you expect ExecuteNonQuery to return, but if you want the actual ID, you'll need to refer to it in the SQL. (Even if initially you just want to know whether or not the user's password is valid, I strongly suspect that at some point you'll want to user the real user ID, so you should make your code return it. If you really only want to know whether or not the password is valid, you should change the method's return type to bool.)
6) You're using ExecuteNonQuery when your command clearly is a query. Either use ExecuteReader or ExecuteScalar instead. (ExecuteNonQuery is meant for insert, delete and update statements, and it returns you the number of rows affected by the command.)
So something like:
public static int Login(string user, string password)
{
using (var conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
string sql = "select Id, PasswordHash from logins where Username=#Username";
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
using (var reader = command.ExecuteRead())
{
if (reader.Read())
{
int id = reader.GetInt32(0);
string hash = reader.GetString(1);
// TODO: Hash provided password with the same salt and compare
// results
if (CheckPassword(password, hash))
{
return id;
}
}
return 0; // Or use an int? return type and return null
}
}
}
}
The ExecuteNonQuery is used for For UPDATE, INSERT, and DELETE statements.
For SELECT statements, use ExecuteReader
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserName, Password FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id++;
}
cmd = null;
reader.Close();
con.Close();
return id;
}
You can't use .ExecuteNonQuery if you want a result. Use .ExecuteReader.
public static int login(string userlogin, string pwdlogin)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = GetConnectionString();
con.Open();
int id = 0;
string selectstr = "SELECT UserId FROM Registration WHERE UserName = '" + userlogin.Trim() + "' AND Password = '" + pwdlogin.Trim() + "'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = selectstr;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
id = reader.GetInt32("UserId");
reader.Close();
con.Close();
return id;
}
I have the following database design for an employee table:
Username
Name
Job
etc ..
And a role table:
RoleID
RoleName
Finally, a UserRole table:
UserRoleID
Username
RoleID
I am developing an Intranet web-based application for my department in the company. This application should be accessible only by my department employees and it should the username of the employee with his role (access type) at the top of the website. I have four different roles; Manager, Contribute, Assisstant and User. What I want now is to do the following:
check the user if he is one of the department employees or not.
if not, he will see an error page
if yes, he will be able directly to access the website, and this is his first time in accessing the website, then he should get a User role and this role should be displayed at the top with the username immediately unless the Admin adds him and gives him one of the other roles.
Everything works well and fine except that the used doesn't get the User Role and the role doesn't show at the top if the user is new to the system unless the Admin determines his access in the database
So, how I can give the new user the default role and display it immediately at the top of the website besides his username?
My code-behind is as following:
private bool CheckUsername(string username)
{
if (Service.GetPerson(username).GetProperty("RES_NETID").Equals("-"))
return false;
else if (Security.isPMODMember(username))
return true;
else
return false;
//string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";
//string cmdText = "SELECT Count(*) FROM employee WHERE Username = '" + username + "'";
//using (SqlConnection conn = new SqlConnection(connString))
//{
// conn.Open();
// // Open DB connection.
// using (SqlCommand cmd = new SqlCommand(cmdText, conn))
// {
// int count = (int)cmd.ExecuteScalar();
// // True (> 0) when the username exists, false (= 0) when the username does not exist.
// return (count > 0);
// }
//}
}
protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
string username = TextBox1.Text;
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";
switch (Wizard1.WizardSteps[e.NextStepIndex].ID)
{
case "WizardStep2":
//For checking the user
if (!String.IsNullOrEmpty(username) && CheckUsername(username))
{
try
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string cmdText = #"SELECT dbo.employee.Username, dbo.employee.Name, dbo.employee.JobTitle, dbo.employee.BadgeNo,
ISNULL(dbo.Roles.RoleID, 3) AS RoleID, dbo.Divisions.DivisionName, dbo.Roles.RoleName
FROM dbo.Divisions INNER JOIN dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode
LEFT OUTER JOIN dbo.Roles RIGHT OUTER JOIN dbo.UserRole ON dbo.Roles.RoleID = dbo.UserRole.RoleID ON
dbo.employee.Username = dbo.UserRole.Username
WHERE (dbo.employee.Username = #Username)";
SqlCommand myCommand = new SqlCommand(cmdText, conn);
myCommand.Parameters.AddWithValue("#Username", username);
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(table);
ObjectUser user = new ObjectUser(username, true);
string Name = user.Name;
string Username = user.ID;
string DivisionName = user.Org.Title;
string JobTitle = user.GetProperty("EMP_TITLE");
string BadgeNo = user.GetProperty("EMP_BADGE_NUMBER");
string role = "User";
string roleid = "3";
if (table.Rows.Count > 0)
{
role = table.Rows[0]["RoleName"] as string;
roleid = table.Rows[0]["RoleID"].ToString();
}
lblName.Text = Name;
lblUsername.Text = Username;
lblDivision.Text = DivisionName;
lblJobTitle.Text = JobTitle;
lblBadgeNo.Text = BadgeNo;
lblRole.Text = role;
radio1.SelectedValue = roleid;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
else
{
//If the user does not exist or a blank value has been entered
//Cancel the nextstep redirection and display an error message in a span
e.Cancel = true;
errorSpan.InnerText = "The username specified is blank or does not belong to PMOD";
}
break;
case "WizardStep3":
break;
}
}
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
//If one of the items is selected AND a username exists in the Username session object update the user role
string username = TextBox1.Text;
if (!String.IsNullOrEmpty(radio1.SelectedValue) && !String.IsNullOrEmpty(username))
{
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdb;Integrated Security=True";
//This for adding the new PMOD user to the system
string insertUserCommand = "INSERT INTO employee (Name, Username, JobTitle, BadgeNo, EmpOrgType, DivisionCode) values (#Name, #Username, #JobTitle, #BadgeNo, #EmpOrgType, #DivisionCode)";
string cmdText = "SELECT Count(*) FROM employee WHERE Username = '" + username + "'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
if ((int)cmd.ExecuteScalar() == 0)
{
//An object from ObjectUser class to get the user information from the Secure system and insert them to the database
ObjectUser user = new ObjectUser(username, true);
SqlCommand cmd2 = new SqlCommand(insertUserCommand, conn);
cmd2.Parameters.AddWithValue("#Name", user.Name);
cmd2.Parameters.AddWithValue("#Username", username);
cmd2.Parameters.AddWithValue("#JobTitle", user.GetProperty("EMP_TITLE"));
cmd2.Parameters.AddWithValue("#BadgeNo", user.GetProperty("EMP_BADGE_NUMBER"));
cmd2.Parameters.AddWithValue("#EmpOrgType", user.GetProperty("EMP_EMPTYPE"));
cmd2.Parameters.AddWithValue("#DivisionCode", user.Org.Division.SapCode);
cmd2.ExecuteNonQuery();
}
}
}
//For updating the role of the user by deleting its current role and inserting a new role
string deleteCommand = "DELETE FROM UserRole where Username=#Username";
string insertCommand = "INSERT INTO UserRole (RoleID,Username) values(#RoleID,#Username)";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
//using (SqlCommand cmd = new SqlCommand(cmdText, conn))
using (SqlCommand cmd = new SqlCommand(deleteCommand, conn))
{
cmd.Parameters.AddWithValue("#Username", username);
cmd.ExecuteNonQuery();
//Now the insert
cmd.CommandText = insertCommand;
cmd.Parameters.Clear(); //need this because still has params from del comm
cmd.Parameters.AddWithValue("#RoleID", radio1.SelectedValue);
cmd.Parameters.AddWithValue("#Username", username);
cmd.ExecuteNonQuery();
//infoSpan.InnerText = String.Format("The users role has been updated to - {0}", radio1.SelectedValue);
//cmd.ExecuteScalar();
//infoSpan.InnerText = String.Format("The users role has been updated to - {0}", radio1.SelectedValue);
}
}
Wizard1.Visible = false;
wizard.InnerHtml = #"<p><b>The task has been done successfully.</b> <br /> <a href='UserManagement.aspx'>Edit Another User</a></p>";
}
}
I think I already did it in Wizard Step#2 as shown above, but it did now work and I don't know why. Any help please?