I have a table namedUsersin SQL server which retains password,email and UserID which is the primary key.
Then in my project I have two forms,first form gets password and name of users and then if entered password and email exist in the table it connects to second form and if not it does not.
then to connect to bank I am using Entity Framework. this is my connection string:
int UserID = 2;
UsersEntities db = new UsersEntities();
var find = db.CalUsers.Find(UserID);
if (find.Email == txtEmail.Text && find.Password == txtPassword.Text)
{
SmallCalculator example = new SmallCalculator();
example.ShowDialog();
}
I know I must use UserID as primary key but I dont know how to write UserIDto get all rows?now it just gets row2
int UserID = 2; // you don't actually know this value since user is not giving it to you
UsersEntities db = new UsersEntities();
//hopefully email address has a unique constraint:
var find = db.CalUsers.FirstOrDefault(x=>x.Email == txtEmail.Text.Trim());
if(find == null) return; //do something else
if (find.Email == txtEmail.Text && find.Password == txtPassword.Text)
{
SmallCalculator example = new SmallCalculator();
example.ShowDialog();
}
Related
if (tbsitename.Text != null)
{
tbsitecode.Text = dm.GetData("select nvl(max(to_number(id)),0)+1 from setups_setup").ToString();
//string code = dm.GetData("select lpad(nvl(max(to_number(code)),0)+1,2,0) from setups_setup where type = 'ISITE'").ToString();
MessageBox.Show(dm.GetData("select max(id) from setups_setup").ToString());
//int suc = dm.SetData("Insert into setups_setup(id) values (id)");
//if (suc > 0)
//{
// tbsitecode.Text = dm.GetData("select max(code) from setups_setup where type = 'ISITE'").ToString();
// MessageBox.Show("Record Saved.....");
//}
}
Dear ALL,
I am new in this group as well as in c#/asp.net.
I want to insert record in oracle, there is a primary key ID which I want to generate but the query isn't giving me new ID.
If I am running this query in oracle it is working fine.
any suggestion please...
I think sequence do it for you,
This is sample how to insert with getting value from sequence
Remember - use parameters instead pure query (SQL Injection)
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 !
}
NET Entity Data Model to get data form Users table which has a foreign key usertypeid from table Usertypes
the code works fine i just want the code to get data form tow tables which the tow tables have a foreign key called usertypeid
ex table1(foreign key usertypeid) table2((foreign key usertypeid))
var result = _datamoel.Users.FirstOrDefault(i => i.UserName.Equals(txtuser.Text) && i.Password.Equals(txtpass.Text));
if (result != null )
{
result.UserTypeReference.Load();
Session["Username"] = txtuser.Text;
if (result.UserType.TypeName.Equals("Admin"))
Response.Redirect("Admin/AdminHomePage.aspx");
else if (result.UserType.TypeName.Equals("Clerk"))
Response.Redirect("Clerk/ClerkPage.aspx");
}
else
lblmsgw.Text = "UserName/Passsword Not Correct! Please Change UserName/Passsword and Try again";
I am creating a login system using c#. I want to check if the username the user enters is already part of the database. This is the code that connects to a data adapter and then updates this once I have taken the data from the check boxes.
NorthwindDataSetTableAdapters.CustomersTableAdapter north = new NorthwindDataSetTableAdapters.CustomersTableAdapter();
NorthwindDataSet.CustomersDataTable northtable = north.GetData();
NorthwindDataSet northwindDataSet1 = new NorthwindDataSet();
NorthwindDataSet.CustomersRow newCustomersRow =
northwindDataSet1.Customers.NewCustomersRow();
newCustomersRow.Username = TextBox1.Text.ToString();
newCustomersRow.Password = TextBox2.Text.ToString() ;
newCustomersRow.FirstName = TextBox3.Text.ToString();
newCustomersRow.Surname = TextBox4.Text.ToString();
northwindDataSet1.Customers.Rows.Add(newCustomersRow);
north.Update(northwindDataSet1.Customers);
northwindDataSet1.Customers.AcceptChanges();
if (Page.IsValid)
Response.Redirect("thankyou.aspx");
What is the best way to check the Username field for duplicate data?
Call me crazy, but I'd just do something like (using "dapper")
string username = ...
int existingId = connection.Query<int?>(
#"select top 1 Id from Users where UserName = #username",
new { username }).FirstOrDefault();
if(existingId.HasValue) {
// not available - do something
}
Note that there is a race condition here so you should still have a unique constraint on the column itself. You might also want to thing about case sensitivity: is "Fred" the same username as "fred"?
Why not to mark the table Column as primary key or unique? Then you handle the exception inside a try{}catcht{} statement.
Have you tried using DataTable.Select? Something like:
var UserFound = NorthTable.Select("UserName = '" + TextBox1.Text + "'");
if(UserFound.Length != 0)
{
// do something...
}
I have a table users which stores three values i.e username ,the password and the member type .I want to ensure that the username stored in the table is unique and hence there is a primary key on it.However I want to do the validation at the client side itself instead of sending a insert request to the database and then catching the error .
So how can I retrieve the single record from the database which would contain both username and password so that I can use it for the comparison purposes in the code and then throw a validation error if needed.
My manager wants me to use stored procedures so inputs along those lines would be great
public static bool IsUserExists(string userName, string hashedPassword)
{
bool result = false;
using (MyEntities entityContext = new MyEntities())
{
result = (entityContext.User.Count(u => u.username == userName &&
u.password == hashedPassword) == 1);
}
return result;
}