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
Related
I want to set isLogged to 1 after login, login work but query doesn't work.
Query :
//
public static string loginUpdate = #"UPDATE users SET isLogged = #isLogged WHERE username = #username";
//
public bool userLogin(string userName, string password)
{
SqlConnection conn = db.initializare();
UserModel user = null;
int userId ;
int isLogged = 1;
try
{
cmd = new SqlCommand(Query.loginCheck, conn);
//cmd = new SqlCommand(Query.loginUpdate, conn);
cmd.Parameters.Add(new SqlParameter("username", userName));
cmd.Parameters.Add(new SqlParameter("password", password));
cmd.Parameters.AddWithValue("#isLogged", isLogged);
reader = cmd.ExecuteReader();
while (reader.Read())
{
userName = reader["username"].ToString();
password = reader["password"].ToString();
userId = Int32.Parse(reader["userID"].ToString());
user = new UserModel(userName, password,userId);
if (user != null)
{
cmd = new SqlCommand(Query.loginUpdate, conn);
return true;
}
}
}
catch (Exception ex)
{
var mesajEroare = ex.Message + "-" + ex.InnerException; ;
}
finally
{
conn.Dispose();
conn.Close();
}
return false;
}
You may need to write two separate SqlCommands to perform two operations:
For login check
For login update
Also, always make it a habit to use the using statement when dealing with an object that eats resources such as SqlConnection and SqlCommand. so objects will be automatically disposed after using them.
This will make your code cleaner without explicitly calling the Dispose() call.
Finally, I would suggest you place your SQL operation outside your Button Click event to avoid getting your code more complex. That way it's clean and easy to manage.
To summarize that, here's how your code is going to look like:
private string GetUserPassword(string userName){
using (SqlConnection connection = db.initializare()) {
string sqlQuery = "SELECT password FROM users WHERE username = #UserName";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) {
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
var result = cmd.ExecuteScalar();
return (result == DBNull.Value) ? string.Empty : result;
}
}
}
private void UpdateLogin(string userName, int isLogged){
using (SqlConnection connection = db.initializare()) {
string sqlQuery = "UPDATE users SET isLogged = #isLogged WHERE username = #username";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection)) {
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserName", userName);
cmd.Parameters.AddWithValue("#isLogged", isLogged);
cmd.ExecuteNonQuery();
}
}
}
public bool UserLogin(string userName, string password)
{
string userPassword = GetUserPassword(userName);
if (password.Equals(userPassword)){
UpdateLogin(userName,1);
return true;
}
else{
//username or password is incorrect
}
return false;
}
I encountered a problem while trying to verify if a value exists in the database. I use Visual Studio 2017.
I wrote a function that checks if Username is in the database table:
protected bool userIsAdmin(string user)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string loginQuery = "select count(*) from AdminTable where User= #Username";
SqlCommand command = new SqlCommand(loginQuery, con);
command.Parameters.AddWithValue("#Username", user);
user = user.Trim();
int rows;
rows = (int)command.ExecuteScalar();
if (rows != 0)
{
OutputLabel.Text = "You are logged";
return true;
}
else
{
OutputLabel.Text = "Try again";
return false;
}
}
I eliminated the probability of an outside error by calling this function like this:
if(userIsAdmin("uia94881"){...}
My database table:
enter image description here
Replace your script as below,
string loginQuery = "select count(*) from AdminTable where [User]= #Username";
because User is a built in function in SQL Server, which will give you the Database username.
SqlConnection connection = new SqlConnection("PUT YOUR CONNECTION STRING HERE");
string loginQuery = "SELECT (User) FROM AdminTable WHERE User = #Username";
SqlDataAdapter adpt = new SqlDataAdapter(loginQuery, connection);
adapt.SelectCommand.Parameters.AddWithValue("#Username", user);
DataSet usr = new DataSet();
adapt.Fill(usr)
foreach(DataRow dr in usr.Tables[0].Rows)
{
string user += usr.Tables[0].Rows[0]["User"].ToString();
}
if(user != "")
{
OutputLabel.Text = "Try again";
return false;
}
else
{
OutputLabel.Text = "You are logged";
return true;
}
Try this instead!
I'm making a web api server that I need for a school project because we have to make several applications on different platforms to communicate through messages and the web api server has GET, POST and DELETE methods.
Right now I have a GET method that will return a row in a table using ID (for example http://localhost:1442/api/Users/1 will return User with ID of 1)
the code looks like this:
public User Get(int id)
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Downloads\SERVER\SERVER\App_Data\dbCoffeeBreak_.mdf;Integrated Security=True";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from tbUsers where ID=" + id + "";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
User u = null;
while (reader.Read())
{
u = new User();
u.ID = Convert.ToInt32(reader.GetValue(0));
u.Login = reader.GetValue(1).ToString();
u.Password = reader.GetValue(2).ToString();
u.Avatar = reader.GetValue(3).ToString();
u.Email = reader.GetValue(4).ToString();
u.Online = Convert.ToBoolean(reader.GetValue(5));
}
myConnection.Close();
return u;
}
but I'm not sure how to make it so that by typing for example only http://localhost:1442/api/Users the server would return ALL columns in the table. I tried setting the sqlCmd.CommandText = to just Select * from tbUsers but that just returns the last User in the table not all of them.
That's because you are only returning the last user from Reader.Read
There are couple of issues and suggestions for you
1. Make Id as optional parameter , so that if you dont pass anyId, it will query for allusers`. With this you dont need to
create separate method for getting all users.
2. Return List<User> instead of return single User
public List<User> Get(int? id = null)
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Downloads\SERVER\SERVER\App_Data\dbCoffeeBreak_.mdf;Integrated Security=True";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
if(id !=null)
sqlCmd.CommandText = "Select * from tbUsers where ID=" + id + "";
else
sqlCmd.CommandText = "Select * from tbUsers ";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
List<User> users = List<User>();
while (reader.Read())
{
u = new User();
u.ID = Convert.ToInt32(reader.GetValue(0));
u.Login = reader.GetValue(1).ToString();
u.Password = reader.GetValue(2).ToString();
u.Avatar = reader.GetValue(3).ToString();
u.Email = reader.GetValue(4).ToString();
u.Online = Convert.ToBoolean(reader.GetValue(5));
users.Add(u);
}
myConnection.Close();
return users;
}
Plus always use Parameterized queries to prevent SQL Injection Attacks
Will suggest you to update your query as
sqlCmd.CommandText = "Select * from tbUsers where ID=#Id";
sqlCmd.Parameters.AddWithValue("#Id", id);
Not sure why the following code gives me an exception. I'm trying to check if a username exists in a MySQL database, if not then I want to create a user. If I run either query by itself then it works ok but not together.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
string sql1 = String.Format("SELECT Username FROM Users WHERE Username = \"{0}\"", username);
MySqlCommand cmd1 = new MySqlCommand(sql1, cnn);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
string sql = String.Format("INSERT INTO Users(Username, Password) VALUES(\"{0}\", \"{1}\")", username, password);
MySqlCommand cmd = new MySqlCommand(sql, cnn);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
First, MySQL uses single quotes. This means your query would be:
string.format("SELECT Username FROM Users WHERE Username = '{0}' LIMIT 1", Username);
However, this is very vulnerable with SQL injection. Here's a code to use MySQL Parameters to prevent it.
int valid = -1;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
bool usernameExists = false;
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
cmd1.Parameters.AddWithValue("#username", username);
usernameExists = (int)cmd1.ExecuteScalar() > 0;
if (!usernameExists)
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO Users(Username, Password) VALUES(#username, #password)", cnn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
valid = cmd.ExecuteNonQuery();
}
}
return valid;
Could you try this?
I got it working by changing the first query from:
MySqlCommand cmd1 = new MySqlCommand("SELECT Username FROM Users WHERE Username = #username LIMIT 1", cnn);
to
MySqlCommand cmd1 = new MySqlCommand("SELECT COUNT(UserID) FROM Users WHERE Username = #username", cnn);
int valid = int.Parse(cmd.ExecuteScalar().ToString());
Thanks for the help.
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?