How do i sets GetRolesAsync to string model? - c#

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;
}
}

Related

Set LockOutEndDate to null ASP.NET MVC

I'm trying to unlock a user account from the admin panel:
public async Task<ActionResult> EnableAccount(string id)
{
var user = UserManager.Users.FirstOrDefault(x => x.Id == id);
if(user != null)
{
await UserManager.ResetAccessFailedCountAsync(user.Id);
await UserManager.SetLockoutEndDateAsync(user.Id, null );
}
return RedirectToAction("Users");
}
I'm getting this error:
cannot convert from '<null>' to 'DateTimeOffset' in
await UserManager.SetLockoutEndDateAsync(user.Id, null);
Ended up doing it this way:
var user = UserManager.Users.FirstOrDefault(x => x.Id == id);
user.LockoutEndDateUtc = null;
user.LockoutEnabled = false;

Unable to cast object of type 'System.Int64' to type 'System.Int32'

Getting the error when asking for equal type of string in
var orderTransferFromDb = await context.OrderTransfer.FirstOrDefaultAsync(t =>
t.ToMemberMobilePhone.ToUpperInvariant().Equals(mobilePhone.ToUpperInvariant()));
public async Task<bool> UpdateOrderTransferToMemberId(string mobilePhone, string memberid)
{
if (mobilePhone != null)
{
using (var context = ContextManager.ClubContext())
{
var orderTransferFromDb = await context.OrderTransfer.FirstOrDefaultAsync(t => t.ToMemberMobilePhone.ToUpperInvariant().Equals(mobilePhone.ToUpperInvariant()));
if (orderTransferFromDb != null)
{
context.Attach(orderTransferFromDb);
orderTransferFromDb.ToMemberId = memberid;
await context.SaveChangesAsync();
}
return true;
}
}
throw new Exception("MobilePhone is null. (UpdteOrderTransferByEmail)");
}
The arguments are both string, and in SQL Server nvarchar(13)
What can cause it?
There's nothing wrong with your code. You need to double check your context whether is mapped correctly with your object.
To Compare string without case, use this
var orderTransferFromDb = await context.OrderTransfer.FirstOrDefaultAsync(t => string.Equals(t.ToMemberMobilePhone, mobilePhone, StringComparison.OrdinalIgnoreCase));

Calling get method using linq query?

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)

Check Nulls in Lambda

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;
}
}

String comparison throws null reference exception

I am trying to find a user in my database, searching for email and phonenumber.
How ever, if I use a List or IEnumerable I'm getting a null refence exception. If I don't use any of those, an "Not supported by SQL ... " is thrown.
My method:
public List<tblMember> getAllMembers()
{
return db.tblMembers.ToList();
}
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault(x => x.email.Equals(email, StringComparison.OrdinalIgnoreCase) && x.phoneNumber == phoneNumber); //This line throws exception, around email.Equals()
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
If I perform the search like this, no exception is thrown:
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault(x => x.email == email && x.phoneNumber == phoneNumber);
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
How can this be?
In the first case you are calling Equals() on an object that is null.
x.email.Equals(...)
This throws an exception.
In the second case you are comparing two things one of which might be null
x.email == email
Here is the most current based on comments:
private void confirmMembership(string email, int phoneNumber)
{
tblMember member = tblMembers.FirstOrDefault((x) => {
if (x.email == null) return false;
return SqlMethods.Like(x.email,email) && x.phoneNumber == phoneNumber);
}
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
Here is another way that won't throw an exception:
private void confirmMembership(string email, int phoneNumber)
{
//var allMembers = db.tblMembers.AsEnumerable(); throws same exception
tblMember member = getAllMembers().FirstOrDefault((x) => {
if (x.email == null) return false;
return x.email.Equals(email, StringComparison.OrdinalIgnoreCase) && x.phoneNumber == phoneNumber);
}
if (member != null)
{
member.isConfirmed = true;
db.SubmitChanges();
}
else
throw new Exception("Member not found");
}
This is probably because x.email is null. If it is null, calling a member of it throws an exception.
x.email.Equals(...) ==> exception
However, you are allowed to compare two values that may be null
x.email == email ==> OK.
I suspect it's because x.email is null for some value of x.
Try:
tblMember member = db.tblMembers
.FirstOrDefault(x => x.email != null
&& x.email.Equals(email, StringComparison.OrdinalIgnoreCase)
&& x.phoneNumber == phoneNumber);
EDIT: I've only just noticed that getAllMembers() returns a List<T> so you don't have to worry about the expression tree conversion I was talking about before - but your current code is fetching all the data from the database each time you call this method. Do you really want that? The code I've provided above will do the filtering in the database which is surely what you'd be interested in.

Categories