How to Get UserID from Custom Table - c#

i would like to be able to get the ID of the Current user logged in on my Site.
The thing is that i'm not trying to get the Guid, but The User_ID, that is a field that i have on a custom table of mine called Users. On that table i have User_ID that is the PK and UserId that is a FK from the table aspnet_Users.
The reason i want this field is because i have a table Purchase that every time an User LOGGED IN presses the button saying (Buy), a new saleId is incremented and the User_ID that bought it. On my table Users the User_ID is of int type that starts at 1 and also increments every time a newUser registers on the site.
So it's easier to check an user by ID of (1,2,3) that an unique Identifier with 30 characters
What i have in mind is something like this:
protected void Button1_Click(object sender, EventArgs e)
{
string InsertSql = "INSERT INTO [Purchase] (User_ID) VALUES (#User_ID)";
using (Connection)
{
Connection.Open();
SqlCommand com = new SqlCommand(InsertSql, Connection);
com.Paramaters.AddWithValue("#User_ID", ????);
com.ExecuteNonQuery();
cn.Close();
}
}
Where is ???? i need to get somehow the User_ID of the current User logged in that is on my custom table Users.
Thanks for the help

After Log-in into your application you should maintain the userid into session variable ..so that later on you can use that directly.
Example:-
//while user logged-in,push userid into session variable:-
Session["userid"] = 12;
//And later on in oyur page you can use it like :-
com.Paramaters.AddWithValue("#User_ID", (int)Session["userid"]);

Assuming as you say that using is logged in
Use User.Identity.Name.
You check if user is authenticated using:
User.Identity.IsAuthenticated
If will give you the name of the current logged user in your asp.net application.
com.Paramaters.AddWithValue("#User_ID", User.Identity.Name);

If I understood right, you have a custom table Users, with PK User_ID and a column UserId that is a FK to the table aspnet_Users.
You already know the UserName of the logged in user, so why not simply do something like:
string InsertSql = #"
INSERT INTO [Purchase] (User_ID)
SELECT U.User_ID FROM Users U
INNER JOIN aspnet_Users AU ON U.UserId = AU.UserId
WHERE AU.LoweredUserName = LCASE(#UserName)
";
Your #UserName parameter is then the name of the current logged on user that you already know (HttpContext.Current.User.Name), and you don't need to know the User_ID.

If you are using Membership then
Gets the name if authenticated.
if (User.Identity.IsAuthenticated)
Label1.Text = HttpContext.Current.User.Identity.Name;
else
Label1.Text = "No user identity available.";
If you want to get userid then run a select query like
Select userid from tablename where username = 'pass here username';
by running this query you will get userid and use that userid when you need.
Parametrized Query:
com.Paramaters.AddWithValue("#User_ID", HttpContext.Current.User.Identity.Name);
and if you are not using Membership then at the time of login get userid from your username and use any where you want to.
Note: Make sure that you have unique username otherwise it will give you multiple userid.
Logic 2:
Use the ProviderUserKey member of the MembershipUser object, like this:
MembershipUser user = Membership.GetUser();
string userid = user.ProviderUserKey.ToString();
Hope it works..

i finally did it, i kinda moved on to other stuff that i needed to do on my Site, so i just figured it out today.
I just wanna say thanks for all the replies and leave the solution to my own problem. Basically what i was doing wrong was the Select command. I'm not very good at SQL, so i didn't know were to place it xD, but now i know.
protected void Button1_Click(object sender, EventArgs e)
{
MembershipUser usr = Membership.GetUser(HttpContext.Current.User.Identity.Name);
Guid usrid = (Guid)usr.ProviderUserKey;
String product= DropDownList1.SelectedValue.ToString();
string InsertSql= "INSERT INTO [Purchase] (Product_ID, User_ID) VALUES (#Product_ID,(SELECT User_ID from [Users] where UserId = #UserId))";
using (Connection)
{
Connection.Open();
SqlCommand com = new SqlCommand(InsertSql, Connection);
com.Parameters.AddWithValue("#Product_ID", product);
com.Parameters.AddWithValue("#UserId", usrid);
com.ExecuteNonQuery();
Connection.Close();
}
Response.Redirect("Purchase.aspx");
}
Once again, thanks for all the patience and help
Take Care

Related

Verify if username exists when updating username

In this situation, there is a form used for updating user information (username, password, mobile number, etc.).
Below is the code I used to check if the username exists in the database:
string sql = "SELECT username FROM (SELECT username FROM useraccount WHERE username != #old_uname)ua WHERE BINARY username = #new_uname LIMIT 1;";
MySqlCommand cmd = new MySqlCommand(sql, SecurityMod.dbconn());
cmd.Parameters.AddWithValue("#old_uname", old_uname);
cmd.Parameters.AddWithValue("#new_uname", new_uname);
if (cmd.ExecuteScalar() == null)
{
isValidNewUname = true;
}
It works if the user really changes his/her username. But the problem occurs when the user made changes to anything but the username field. The isValidNewUname variable remains false. Any ideas and suggestions would be a big help.
Instead of basing on fetched username, I opted instead for the uid. I solved the problem with the following code:
string sql = "SELECT uid FROM useraccount WHERE BINARY username = #new_uname;";
MySqlCommand cmd = new MySqlCommand(sql, SecurityMod.dbconn());
cmd.Parameters.AddWithValue("#new_uname", new_uname);
if (cmd.ExecuteScalar() == null || cmd.ExecuteScalar().ToString() == userID)
{
isValidNewUname = true;
}
This code is shorter and more simple hence easier to maintain. What happens here is that the query looks for the uid of the #new_uname in the database. It then compares the fetched uid to the uid of the current user. If it is the same, it means that the fetched result of the query is simply the user itself, so it doesn't really matter if their the same or not since it belongs to only one user. If the fetched uid is not equal to the uid of the current user, it means the username input by the user is already taken so isValidNewUname would be false. If the query above doesn't return results, then the #new_uname is available since it doesn't have a record in the database.

Check if username/password exists in multiple tables

I am working on a login page. I'd like to check if the username & password exists in the database. I have three database tables : Teams,Organizers,Admins with username & password field in each table respectively. I am implementing the login in three-tier architecture.
I believe that I have a problem with my SQL statement below. I tested my sql query with a distinct/valid team username and team password. The COUNT query returns more than one row, which is incorrect.
This are my codes for the data access layer :
public int getExistingAccount(string username, string password)
{
string queryStr = "SELECT COUNT(*) FROM Teams t,Organizers o,Admins a WHERE (t.teamUsername=#username AND t.teamPassword=#password) OR (o.organizerUsername=#username AND o.organizerPassword=#password) OR (a.adminUsername=#username AND a.adminPassword=#password)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int returnValue = 0;
conn.Open();
returnValue = (int)cmd.ExecuteScalar();
conn.Close();
return returnValue;
}
As for the business logic layer codes :
public string getAccount(string username, string password)
{
string returnMessage = "";
if (username.Length == 0)
returnMessage += "Username cannot empty</br>";
if (password.Length == 0)
returnMessage += "Password cannot be empty</br>";
if (username.Equals(password))
{
returnMessage += "Duplicate value. Please try again</br>";
}
//Invoke validateInput() method to validate data
if (returnMessage.Length == 0)
{
int noOfRows = 0;
LogAccounts logInd = new LogAccounts();
noOfRows = logInd.getExistingAccount(username, password);
if (noOfRows > 0)
returnMessage += "Account found";
else
returnMessage += "Invalid username/password.";
}
return returnMessage;
}
Try this, select from each table and UNION ALL the results, then count the rows.
select count(*) from
(
SELECT 1 as dummyname FROM Teams t
WHERE (t.teamUsername=#username AND t.teamPassword=#password)
union all
SELECT 1 FROM Organizers o
WHERE (o.organizerUsername=#username AND o.organizerPassword=#password)
UNION ALL
select 1 from Admnis
WHERE (a.adminUsername=#username AND a.adminPassword=#password)
)
I seems you have a really awkward database design, where fetching a single user requires a unnaturally large/long sql query.
In almost every use case you would have a single Users table, and if you need to tie the user to some additional information, you would have a reference to the user table by the UserId. You should read up on foreign keys aswell.
Quick sample:
Users:
- UserId (int or guid) (primary key)
- .... (additional fields removed for brewity)
The other tables would refer to the UserId column, and use that to pull information about the user with a join.
E.g.: SELECT T.*, U.* FROM Teams T INNER JOIN Users U ON U.UserId = T.UserId WHERE U.Username = "AwesomeCoach";
A simple validate query would be something like this:
SELECT COUNT(*) FROM Users WHERE Username = xx AND Password = xx
That would return an integer that specifies how many rows that matched the given username/password combination. It should be either 1 or 0. Put a Unique contraint on the Username column to ensure that there are only one occurence of each Username.
Footnote: I see that you have got an answer that solves the problem you were facing, but I would recommend that you read up on some database design, and try to keep it as simple as possible. Managing multiple users across multiple tables can and will be a hassle as the application grows.
Your design is really bad, you should have all users in one table. After that if you want to take user by id, you should check 3 diff tables. Anyway the problem is in the query you should write it like this:
string queryStr = #"
SELECT
COUNT(*) AS TeamsCount,
(SELECT COUNT(*) Organizers WHERE organizerUsername=#username AND organizerPassword=#password) AS OrgCount,
(SELECT Count(*) Admins WHERE adminUsername=#username AND adminPassword=#password) AS AdminCount
FROM
Teams
WHERE
teamUsername=#username AND
teamPassword=#password";
The query should look something like this. After that you need to return this in DataSet. You need:
DataSet dst = new DataSet();
using(SqlAdapter adapter = new SqlAdapter(cmd))
{
adapter.Fill(dst);
}
In this case you will have dst with 3 columns in it. Check for existing user should be:
if(dst.Tables[0].Rows[0]["TeamsCount"] > 0 ||
dst.Tables[0].Rows[0]["OrgCount"] > 0 ||
dst.Tables[0].Rows[0]["AdminCount"] > 0)
{
//user already exist !
}

How to add data from 2 tables into one using access database in c# wpf

I'm trying to add data from two tables in database into one table, but i'm having some difficulties with the code. I need to create an option for users to book a train ticket, and their ID and the ticket's ID needs to be displayed in new table (reservations)
Here is and example:
User:
ID: 5
Name: Jack
Last Name: Jones
Ticket:
ID: 9
Name: London
RESULT
Booking table:
BookingId: 1
UserId: 5
BookId: 9
This is my code so far
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "SELECT User.ID, Ticket.ID AS Reservation FROM (User INNER JOIN Ticket ON User.ID = Ticket.ID)";
cmd.CommandText = "INSERT INTO Reservation(ID_user, ID_ticket)" + "values(#User.ID, #Ticket.ID)";
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Ticket added");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Please help me out!
Assuming that Booking table and Reservation table is one and the same. If not then comment here.
If I understand your business correctly, first and foremost thing is you cannot have a join on User table and Ticket table based on their id. They are independent tables and do not have a relationship between them.
Secondly both the data i.e. userid and ticketid should be available on the UI when the user finally books the ticket.
As for userid, if you have an asp.net application, the userid will be available when s/he logs on to your website, else if it is a windows application you can save it in a public static class variable.
The ticketid will be the record the user selects when it adds the details of his/her journey.
You need to pick them and add it in the reservations table.
Hope this gives you some direction.
SELECT User.ID, Ticket.ID AS Reservation FROM (User INNER JOIN Ticket ON User.ID = Ticket.ID)
here on condition is wrong how would userid and ticketid equal?

Unable to Retrieve Microsoft Access Autonumber Values

Access 2003
VS 2010 C#
As subject title says I am having a problem with this. It's creating a new field to print date and time when it should be stamping the date and time in the current ID. I have also tried UPDATE command parameter without success.
I have a different method (btnloggedIn) which saves Usernames, Logged In Date and Logged In Time. This works as it should be. I have created another method (btnLoggedOut) which I am having problems with. The purposes is to save Logged Out Date and Logged Out Time when user who logged out, in the came column in Access where Auto ID is created when logged in.
Table Name - LoginTable
>
FieldName Data Type
UserName Text
Password Text
Table name - LoginLogTable
FieldName Data Type
ID AutoNumber
UserName Text
LoggedInDate Date/Time
LoggedInTime Date/Time
LoggedOutDate Date/Time
LoggedOutTime Date/Time
ID is PK. Its one to many relationship. User who logs in can have many details about the date and time details
If anyone can help me here I would be grateful.
private void btnLogOut_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = ?, [LoggedOutTime] = ?
WHERE ID = ?";
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
Close();
}
This the partial code for btnLogin method...
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
If you execute a SELECT ##IDENTITY query when the user clicks the "Log out" button you'll not likely get the value you're hoping for. SELECT ##IDENTITY is intended to be called immediately after the INSERT that creates the record (in this case, when the user logs in). You can then stash that value away in your application and use it to select that same record when the user logs out.
If your application inserts any other records (in other tables) that cause a new Identity (a.k.a. "AutoNumber") value to be created then SELECT ##IDENTITY will return the most recent one of those values. So, just grab the ##IDENTITY value when the user logs in and save it for when the user logs out again.
Typically, the way this is done is:
Create the new log in record.
Get its auto-generated record ID by running a new select asking for the newest log in entry for that particular user. You can sort descending to guarantee it is the first record in the recordset.
Use that record ID to specify the log in record you want to update using WHERE ID = ? instead and fill in the ID value with the record ID.
This is a very typical pattern for database record creation when you do not know what the auto-generated primary record ID will be. You create your new record, you read it back in the record ID to get its auto-generated primary key ID value, and then use the record ID from then on to refer to it.

Iterating through a column in a database

When 'login' button is clicked I would like to iterate through a column in a table and check if a match occurs. How would I go about doing this?
I have connected through to a database and I'm reading from database and writing to database fine. I am not sure how I would iterate through a database.
P.S I'm new to both c# and visual studios. I am not having much trouble with C#, since I come over from Java however I'm struggling to get into grips with Visual studios.
This is simple you'll see.
SqlConnection myConnection = new SqlConnection(#"Server = (Local); Integrated Security = True;" + "Database = insertDataBaseName"); // Assuming (Local)
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = ("SELECT UserName, Password,from Login"); // Where Login is your table . UserName and Password Columns
SqlDataReader myReader = myCommand.ExecuteReader();
bool login = false;
while (myReader.Read())
{
if (userNameBox.Text.CompareTo(myReader["UserName"].ToString()) == 0 && passwordBox.Text.CompareTo(myReader["Password"].ToString()) == 0) // A little messy but does the job to compare your infos assuming your using a textbox for username and password
{
login = true;
}
}
if (login)
{
//Your're in.
}
else
{
MessageBox.Show("Invalid UserName or Password", "Access Denied"); // Error message
}
myReader.Close();
myConnection.Close(); // Just close everything
Hope this helps.
Dont hesitate if you have any question on this code part.
in sql something like this will help
Select top(1) from Users where Id = #Id
or in linq
var user = (from u in users
where u.Id == id
select u).SingleOrDefault();
If you are chekcing for a username password validation, I think you should not get all user records and loop Iterate thru that. What if you get 100000 user registrations ? You really want to iterate 100000 times ? Really ?
You should probably query for the purticular record you are looking for
Some thing like this
SELECT TOP 1 UserID,FIRSTNAME,LASTNAME,HASHED_PASSWORD,SALT WHERE USERNAME='kristy'
Execute that query againinst your database and see whether you have any records exist, If you have one record present, now you can validate the password with the data you have.

Categories