I am trying to call the following get method in web api but I am currently experiencing an compiling error - 'bool' does not contain a definition for 'password' and no extension method 'password' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) -- error
User class:
public class User : iUser
{
private cdwEntities db;
public User()
{
db = new cdwEntities();
}
public User(cdwEntities context)
{
db = context;
}
public bool Validate(string username, string password)
{
var query = from t in db.Trial_Try
join u in db.UserDetails on t.tUID equals u.uID
where t.tExpiryDate >= DateTime.Now &&
t.tPublication.Value == 163 &&
u.uUsername == username &&
u.uPassword == password
select u; //
// "execute" the query
return query.FirstOrDefault() != null;
}
Test class:
public HttpResponseMessage GetValidate(string username, string password)
{
User layer = new User();
var result = layer.Validate(username, password);
***if (result.username != null && result.password != null)***
{
var mes = string.Format("Success");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, mes);
}
else
{
//var mis = string.Format("User {0} not found");
//return Request.CreateErrorResponse(HttpStatusCode.NotFound, mis, result);
return null;
}
}
Validate is returning a Boolean, not the result of the query. As #ekad stated, check result as a Boolean directly.
As an additional optimization, consider using .Any instead of FirstOrDefault since you don't need the hydrated result and can optimize the SQL to an Exists query rather than select top 1. Your validate method could then be:
public bool Validate(string username, string password)
{
var query = from t in db.Trial_Try
join u in db.UserDetails on t.tUID equals u.uID
where t.tExpiryDate >= DateTime.Now &&
t.tPublication.Value == 163 &&
u.uUsername == username &&
u.uPassword == password
select u; //
// "execute" the query
return query.Any();
}
The problem is result is a bool and it doesn't have username or password property, so you need to replace this line
if (result.username != null && result.password != null)
with this
if (result)
Related
I Have string model in my viewmodel i want to convert GetRolesAsync to string.
var string = await _userManager.GetRolesAsync(item);
>
'string' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'string'
I found the answer
var rolename = await _userManager.GetRolesAsync(model);
user1.RoleName = rolename[0].ToString();
Its works fine for me.
var user = await _userManager.Users.Where(x => x.Id == request.UserId).FirstOrDefaultAsync();
if (user != null)
{
Task<IList<string>> roles = _userManager.GetRolesAsync(user);
var returnUser = _mapper.Map<AspNetUser, AspNetUserDto>(user);
if (returnUser != null)
{
if (roles != null && roles.Result != null)
returnUser.Roles = roles.Result.ToList();
return returnUser;
}
}
I have a problem with WCF Service operation. I get passwod value from database and when it should pass it return false value. What am I doing wrong?
public bool LogIn(string userId, string passwd)
{
bool prompt;
ProgDBEntities context = new ProgDBEntities();
IQueryable<string> haslo = (from p in context.UserEntity where p.UserID == userId select p.Passwd);
bool passOk = String.Equals(haslo, passwd);
if (passOk == true )
{
prompt = true;
}
else
{
prompt = false;
}
return prompt;
}
It seems like you want to compare a single retrieved entry with the password that was passed in (as opposed to any IQueryable/IEnumerable). For that, try using the FirstOrDefault method:
public bool LogIn(string userId, string passwd)
{
bool prompt;
ProgDBEntities context = new ProgDBEntities();
var haslo = (from p in context.UserEntity where p.UserID == userId select p.Passwd).FirstOrDefault();
// No need to use String.Equals explicitly
bool passOk = haslo == passwd;
if (passOk == true )
{
prompt = true;
}
else
{
prompt = false;
}
return prompt;
}
haslo represents a collection of strings, not an individual string. This means String.Equals(haslo, passwd) will always return false since you're comparing a collection of strings to an individual string - they're two different types of objects.
You could try modifying the code as follows. FirstOrDefault() will return the first string in the collection, or NULL if it's empty.
bool passOk = String.Equals(haslo.FirstOrDefault(), passwd);
We have the following code to check if the given username and password exists in database:
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
return Mapper.Map(context.UserEntities.Single(u => u.UserName == userName && u.UserPassword == userPassword));
}
}
If we have the username and password in database this works fine but throws an error if username or password is wrong and no records found.
This might be simple but as I am new to lambda could not get get it right.
How can I change the lambda query so we can handle nulls?
Thanks
Use SingleOrDefault, which will return only one record or null if none exists.
return Mapper.Map(context.UserEntities.SingleOrDefault(u => u.UserName == userName && u.UserPassword == userPassword));
Later you can check:
User returnedObject = GetUserByUserNameAndPassword(username,password)
if(returnedObject == null)
{
//User doesn't exist
}
Remember Single/SingleOrDefault will throw an exception if multiple records exist against the criteria.
You should change from Single to SingleOrDefault, it returns null when no data match
context.UserEntities.SingleOrDefault(u => u.UserName == userName &&
u.UserPassword == userPassword)
.Any() will return true if a matching record is found or false if no record is found.
So a slight modifcation to you existing code will work.
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
if (context.UserEntities.Any(u => u.UserName == userName && u.UserPassword == userPassword))
{
return Mapper.Map(context.UserEntities.Single(u => u.UserName == userName && u.UserPassword == userPassword));
}
else
{
//Deal with no user here through chosen method
}
}
}
Make use of FirstOrDefault or SingleOrDefualt and check for null like as below
var user =context.UserEntities.SingleOrDefault(u => u.UserName == userName
&&
u.UserPassword == userPassword);
if(user!=null)
{
//do code
}
Use SingleOrDefault and check for Null prior to calling Map
public User GetUserByUserNameAndPassword(string userName, string userPassword)
{
using (var context = DataObjectFactory.CreateContext())
{
var user = context.UserEntities.SingleOrDefault(u => u.UserName == userName && u.UserPassword == userPassword);
return user !=null ? Mapper.Map(user) : null;
}
}
I get an error not all code paths return a value?
public string Authentication(string studentID, string password) // this line?
{
var result = students.FirstOrDefault(n => n.StudentID == studentID);
//find the StudentID that matches the string studentID
if (result != null)
//if result matches then do this
{
//----------------------------------------------------------------------------
byte[] passwordHash = Hash(password, result.Salt);
string HashedPassword = Convert.ToBase64String(passwordHash);
//----------------------------------------------------------------------------
// take the specific students salt and generate hash/salt for string password (same way student.Passowrd was created)
if (HashedPassword == result.Password)
//check if the HashedPassword (string password) matches the stored student.Password
{
return result.StudentID;
// if it does return the Students ID
}
}
else
//else return a message saying login failed
{
return "Login Failed";
}
}
if the result is not null but the result.Password != HashedPassword you're not returning anything.
You should change to something like:
...
if (HashedPassword == result.Password)
{
return result.StudentID;
// if it does return the Students ID
}
return "Invalid Password";
...
The problem is that your first if statement doesn't ensure the returning of a value, due to the nested if statement. Imagine you have result set to a value (not null) and your hashed password and supplied password do not match, if you follow that logic through you will fail to hit a return statement.
You should either add an else clause to your nested if statement like so:
if (HashedPassword == result.Password)
//check if the HashedPassword (string password) matches the stored student.Password
{
return result.StudentID;
// if it does return the Students ID
}
else
{
return "Login Failed";
}
or more desirably, remove the else statement you already have so the function ends with returning the login failed:
if (result != null)
{
//....
}
return "Login Failed";
...with this second approach you do no need to worry about using the else because if all your other conditions are satisfied, the nested return statement will end the function anyway. Try to think of this final return as the default action if any of the authentication steps fail
Another note to make on your code is that it is not ideal practise to be returning a mix of data in such a way. i.e. the result could be a student ID or it could be an error message. Consider creating a dedicated result class with multiple properties that the calling code can check to see the status of the logic validation. A class something like the following would be a good start:
public class LoginResult
{
//determines if the login was successful
public bool Success {get;set;}
//the ID of the student, perhaps an int datatype would be better?
public string StudentID {get;set;}
//the error message (provided the login failed)
public string ErrorMessage {get;set;}
}
(saying all that though, your calling code already appears to be aware of the studentID anyway)
remove the else. Just do
if(result != null) {
...
}
return "Login Failed";
you should also return something in case of:
if (HashedPassword != result.Password)
put an else in the inner if
i have made some changes in your code. try it.
public string Authentication(string studentID, string password)
{
var result = students.FirstOrDefault(n => n.StudentID == studentID);
var yourVar;
if (result != null)
{
byte[] passwordHash = Hash(password, result.Salt);
string HashedPassword = Convert.ToBase64String(passwordHash);
if (HashedPassword == result.Password)
{
//return result.StudentID;
yourVar = result.StudenID;
// if it does return the Students ID
}
}
else
//else return a message saying login failed
{
yourVar = "Login Failed";
}
return yourVar;
}
How come my code is showing a syntax error on this block of code
public string getPassword()
{
DataClasses1DataContext myDbContext = new DataClasses1DataContext(dbPath);
var password = (from user in myDbContext.Accounts
where user.accnt_User == txtUser.Text
select user.accnt_Pass).First();
if (password == 0)
{ }
return password;
}
I want to know if the result of query is 0, if it is 0 I will close the operation or something like that. but It keeps showing an error how would I know if the result is 0? also if you have suggestions regarding my approach feel free to put it in
Calling .First() will result in an exception if there is no data returned...
Calling .FirstOrDefault() will return null if there is no data
public string getPassword()
{
DataClasses1DataContext myDbContext = new DataClasses1DataContext(dbPath);
var password = (from user in myDbContext.Accounts
where user.accnt_User == txtUser.Text
select user.accnt_Pass).FirstOrDefault();
if (password == null)
{
// no data found - do whatever is needed in that case...
}
return password;
}