Creating Custom ChangePassword - .net Identity - c#

little help on how I can create my own changepassword? The challenge is with passwordhashing. Tried with some examples found on stack but did not work.
This is my code:
var currentPassword = _userManager.PasswordHasher.HashPassword(changePassword.CurrentPassword);
ApplicationUser user = (from x in _context.AspNetUsers
where x.Id == changePassword.UserId && x.PasswordHash == currentPassword
select new ApplicationUser()
{
FirstName = x.FirstName,
LastName = x.LastName,
RoleId = x.RoleId,
LocationId = x.LocationId,
IsActive = x.IsActive,
CreatedOn = x.CreatedOn,
CreatedBy = x.CreatedBy,
ModifiedOn = x.ModifiedOn,
ModifiedBy = x.ModifiedBy
}).SingleOrDefault(); //_userManager.FindById(changePassword.UserId);
if (user == null)
{
//does not exist
return 0;
}
user.PasswordHash = _userManager.PasswordHasher.HashPassword(changePassword.NewPassword);
var result = _userManager.Update(user);

Well, I dont think this question is formatted the right way but ill guess ill answer it anyways.
Hashing is one way so when a user types in a password for the first time you hash it and store in a database. So when a user logs in you hash the input and compare it with the hash value stored in the database.
Change password works exactly the same. Either you do a raw function which checks if the user typed in the existing one as old and then just update with the new password.
You can also do it by email but thats not what you asked.

Related

I am trying to save information to two data tables using one service method using c#

Writing an app and I am trying to add on to the method where a user creates a new gift card. I added another column in my applicationuser table called TotalBalance that adds in the balances of each cards created. So I can get a new card to save to the gift card table but I want the gift card balance to be added to the 'Users total donation balance' in the application user table. The code I'm working with is below.
public bool CreateGiftCard(GiftCardCreateViewModel model)
{
using (var context = new ApplicationDbContext())
{
var company = context
.Company
.Where(e => e.CompanyName == model.CompanyName)
.FirstOrDefault();
var companyId = company.CompanyId;
var entity =
new GiftCard()
{
OwnerId = _userId,
Amount = model.Amount,
CardNumber = model.CardNumber,
DonationUtc = DateTime.Now,
CompanyId = companyId,
// Optional
ExpirationDate = model.ExpirationDate,
AccessNumber = model.AccessNumber
};
company.CompanyAmount = company.CompanyAmount + entity.Amount;
context.GiftCard.Add(entity);
return context.SaveChanges() == 1;
}
}
You might be doing this in entirely the wrong place. Rather than handling it in the application at the time of update, you could look at creating this as a calculated column in the database itself.
The details will depend upon which RDBMS you're using, you might like to add a tag to indicate this.
To more directly answer your question, it is not possible to update two tables in a single select statement.
Try adding this code to your method (I guessed at some of the attribute names, but you can get the idea):
var appuser = context
.ApplicationUser
.Where(e => e.UserId == _userId)
.FirstOrDefault();
appuser.TotalBalance += model.Amount;
context.ApplicationUser.Update(appuser);

Linq query and multiple where clauses with OR only first condition gets evaluated

I give a user flexibility by providing either username or user id, which are different database fields, both strings. Here is my Linq query below:
var usr = ctx.Users.Where(a => (a.Username.Equals(id) || a.UserID.Equals(id))).ToList();
The thing is if I call it with username: "johndoe", I get a record back, but if I user UserID: "12345" then I do not get any records back even though there is a user "johndoe" with id "12345" in the database.
Also if I change it to:
var usr = ctx.Users.Where(a => a.UserID.Equals(id)).ToList();
It works fine with UserID; "12345". So it seems that only first condition gets evaluated. Can't figure out what am I doing wrong...
Just to make things clear: I want to check both fields for the given id value and return the record where either field matches the id.
The final result I want to get is to have a record(s) returned in my usr variable regardless of which field, Username or UserID matches the input id.
Your linq query looks ok to me
public class Users
{
public string Username {get;set;}
public string Userid {get;set;}
}
void Main()
{
var users = new List<Users>{new Users {Username="johndoe",Userid="123"},
new Users {Username="stevejobs",Userid="456"}
};
var filter = users.Where(a => (a.Username.Equals("123") || a.Userid.Equals("123"))).ToList();
filter.Dump();
var filter2 = users.Where(a => (a.Username.Equals("456") || a.Userid.Equals("456"))).ToList();
filter2.Dump();
}

c# LinqtoTwitter getting ScreenName/UserID from connection context

I've read nearly every post with a code example in the LinqToTwitter documentation.
I want to get the UserID or the User's ScreenName to make a call like this for the user who is logged in.
var friendList =
await
(from friend in twitterCtx.Friendship
where friend.Type == FriendshipType.FriendIDs &&
friend.ScreenName == "JoeMayo"
select friend)
.SingleOrDefaultAsync();
But all I can find are queries like above who have a hardcoded string for ScreenName.
Where can I get my own ScreenName/UserID out of the twitterCtx?
Cheers,
Chris
When you first authorize, the ScreenName and UserID of the IAuthorizer will be populated:
var credentials = auth.CredentialStore;
string oauthToken = credentials.OAuthToken;
string oauthTokenSecret = credentials.OAuthTokenSecret;
string screenName = credentials.ScreenName;
ulong userID = credentials.UserID;
If you're pre-loading all 4 credentials, LINQ to Twitter short-circuits to save time, bandwidth, and user annoyance by not going through the authorization process again. The side-effect is that you don't get the ScreenName and UserID, because those are a product of authorization. So, if you save someone's keys after initial authorization, so you can use them again on subsequent queries, then grab ScreenName and UserID at that time too.
Of course you have another way to obtain ScreenName and UserID. You can do a VerifyCredentials query, like this:
try
{
var verifyResponse =
await
(from acct in twitterCtx.Account
where acct.Type == AccountType.VerifyCredentials
select acct)
.SingleOrDefaultAsync();
if (verifyResponse != null && verifyResponse.User != null)
{
User user = verifyResponse.User;
Console.WriteLine(
"Credentials are good for {0}.",
user.ScreenNameResponse);
}
}
catch (TwitterQueryException tqe)
{
Console.WriteLine(tqe.Message);
}
The ScreenName and UserID are in the User entity of the User property on the Account entity returned from the VerifyCredentials query. They are named ScreenNameResponse and **UserIDResponse** properties, respectively.

How to add condition to LINQ query based on Id

This is my action method which fetches all the users with their Id.
public JsonResult GetUsers()
{
var ret = (from user in db.Users.ToList()
select new
{
UserName = user.UserName,
// i am stuck here, i want to get all those ids whom current logged user is following
Idfollowing = user.FollowTables.Contains()
Idnotfollowing =
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
the structure of FollowTable is like this:
ID UserId FollowId
1 4 11
2 4 12
2 4 13
here, current loggedin user's id is 4 and he is following 11, 12, 13 so i want to return only 11, 12 and 13 to Idfollowing and rest remaining id in the Idnotfollowing. how to get it done.
Well, i think with list or array, i will not get desired result. so, i want to add something here.
Well, with every UserName an id is also passed to view page. So, i have break them into two.Now, how to assign values to these ids.
Comapre User.Id with Current loggedin user's follow table's followId column.If match is found .i.e if id matches or found then assign that user.Id to Idfollowing and null to Idnotfollowing and vice versa in opposite case.
I have to generate follow unfollow button based on these ids returned.
public JsonResult GetUsers()
{
int currentUserId = this.User.Identity.GetUserId<int>();
var ret = (from user in db.Users.ToList()
let Id = user.FollowTables.Where(x => x.UserId == currentUserId).Select(f => f.FollowId).ToList()
let Idnot = (from user2 in db.Users
where !Id.Contains(user2.Id)
select user2.Id).ToList()
select new
{
UserName = user.UserName,
Id = Id,
//Id = user.FollowTables.Where(x => x.UserId == currentUserId)
// .Select(x => x.FollowId).Single(),
Idnot = Idnot,
It looks like you have a standard one-to-many relationship from User to FollowTable. This data model enforces that user.FollowTables only contains followers. You won't be able to fill in Idnotfollowing from the FollowTables property directly.
Something like this may work:
var query = (
from user in db.Users // note: removed ToList() here
// to avoid premature query materialization
where //TODO ADD WHERE CLAUSE HERE ?
let followIds = user.FollowTables.Select(f => f.FollowId)
let notFollowIds = (from user2 in db.Users
where !followIds.Contains(user2.Id)
select user2.Id)
select new
{
UserName = user.UserName,
Idfollowing = followIds.ToArray(),
Idnotfollowing = notFollowIds.ToArray()
})
// TODO add paging? .Skip(offset).Take(pageSize)
.ToList();
Do verify the SQL generated by this query and make sure it performs ok though...
Also, note that I removed the .ToList() from db.Users.ToList() to avoid premature query materialization. It is generally a bad idea anyway to extract all data from a table unconstrained, you will typically want to a
var ret = (from user in db.Users.ToList()
select new
{
UserName = user.UserName,
Idfollowing = user.FollowTables.Select(x=> x.Id)
Idnotfollowing = db.FollowTables.Where(x=> !user.FollowTables.Select(x=> x.Id).Contains(x.Id)).Select(x=> x.Id)
});
it's ugly but will work, there must be another better way to do.
You can simply use a Where method to filter the table and use Select to project FollowiId:-
var ret = (from user in db.Users.ToList()
select new
{
UserName = user.UserName,
Idfollowing = user.FollowTables.Where(x => x.UserId == user.Id)
.Select(x => x.FollowId).ToArray(),
Idnotfollowing = user.FollowTables.Where(x => x.UserId != user.Id)
.Select(x => x.FollowId).ToArray()
});
Assuming, Idfollowing & Idnotfollowing are array if integers (if FollowId is integer) otherwise you can replace it with ToList if its a list instead.

Linq help - sub query gives null pointer exception

I writing a email system where we have a table of users "tblUsers" and a table of messages. A user can have many messages (from other users in tblusers) in his or her inbox (one:many).
In tblUsers table, I have a column called ImageURL (string) that contains the URL to the user's avatar. In this case, I'm looping through the messages in an inbox belonging to a user and what I'm trying to do is, once I get the message, walk up the tree to the tblUser and get the value in the ImageURL column for the owner of that message as marked "SenderAvatar" below.
Here's what I tried. The problem is that the sub linq for SenderAvatar below is throwing a nullpointer exception even though I have confirmed that there is a value for ImageURL (this is dev so there's only three users). Somehow my logic and linq's logic is at odds here. Can someone please help? Thanks!
Edit
I found two bugs. The first bug is Dzienny pointed me to the right direction where I was comparing apples and oranges. The second bug is FromUserId = ux.tblUserId, where I'm setting the current user id to FromUserId Guys, thank you for all your help on this.
public List<UserInboxMsg> GetUserInboxMsg(IKASLWSEntities conx, int userid)
{
var u = (from m in conx.tblUsers where m.Id == userid select m).FirstOrDefault();
if (u != null)
{
return (from ux in u.tblInboxes
orderby ux.CreationTS descending
select new UserInboxMsg
{
CreationTS = ux.CreationTS,
ExpirationDate = ux.ExpirationDate,
FromUserId = ux.tblUserId,
HasImage = ux.HasImage,
ImageId = ux.ImageId ?? 0,
IsDeleted = ux.IsDeleted,
IsRead = ux.IsRead,
MsgId = ux.Id,
MsgSize = ux.MessageSize,
ParentId = ux.ParentId,
Title = ux.Title,
ToUserId = userid,
FromUserName = ux.Title,
SenderAvatar = conx.tblMessages.Where(mu=>mu.Id == ux.Id).FirstOrDefault().tblUser.ImageURL,
Message = ux.Message
}).ToList<UserInboxMsg>();
}
else
{
return new List<UserInboxMsg>();
}
}
}
If in the entity-framework, there is a foreign key reference between the two tables you could probably do this:
SenderAvatar = conx.tblMessages.FirstOrDefault( mu=>mu.Id == ux.Id).ImageURL,
Try this.
public List<UserInboxMsg> GetUserInboxMsg(IKASLWSEntities conx, int userid)
{
var u = (from m in conx.tblUsers where m.Id == userid select m).FirstOrDefault();
if (u != null && conx != null)
{
return (from ux in u.tblInboxes
orderby ux.CreationTS descending
select new UserInboxMsg
{
...
...
SenderAvatar = conx.tblMessages.Any(mu=>mu.Id == ux.Id) ? (conx.tblMessages.First(mu=>mu.Id == ux.Id).tblUser != null? conx.tblMessages.First(mu=>mu.Id == ux.Id).tblUser.ImageURL : null) : null,
Message = ux.Message
}).ToList<UserInboxMsg>();
}
else
{
return new List<UserInboxMsg>();
}
}
}
if you are getting null for the Avatar, it is either because there are no entries in tblMessages where mu.Id equals ux.Id or the tblMessage entry is there but the tblUser property is null
There are several problems here.
The first is that the second statement is executed in memory, while it's possible to make the whole query run as SQL:
from u in conx.tblUsers where m.Id == userid
from ux in u.tblInboxes
orderby ux.CreationTS descending
select new UserInboxMsg
{
CreationTS = ux.CreationTS,
ExpirationDate = ux.ExpirationDate,
FromUserId = ux.tblUserId,
HasImage = ux.HasImage,
ImageId = ux.ImageId ?? 0,
IsDeleted = ux.IsDeleted,
IsRead = ux.IsRead,
MsgId = ux.Id,
MsgSize = ux.MessageSize,
ParentId = ux.ParentId,
Title = ux.Title,
ToUserId = userid,
FromUserName = ux.Title,
SenderAvatar = conx.tblMessages.Where(mu => mu.Id == ux.Id)
.FirstOrDefault().tblUser.ImageURL,
Message = ux.Message
}
This has three benefits:
you fetch less data from the database
you get rid of the null reference exception, because SQL doesn't have null references. It just returns null if a record isn't found.
you can return the result of this statement without the if-else.
Second, less important, is that you should use a navigation property like Inbox.Messages in stead of joining (sort of) the inbox and its messages. This makes it less likely that you use the wrong join variables and it condenses your code:
SenderAvatar = ux.Messages.
.FirstOrDefault().User.ImageURL,
Now if there is no avatar, there is no avatar. And there's no null reference exception.
(By the way, you can see that I hate these prefixes in class and property names).
I can only guess this part of your code is wrong : SenderAvatar = conx.tblMessages.Where(mu=>mu.Id == ux.Id).FirstOrDefault().tblUser.ImageURL
I think for example you should use (mu=>mu.UserId == ux.Id) instead of (mu=>mu.Id == ux.Id). In your code, you are comparing "Id" of a table to "Id" of another table which normally in one to many relations is wrong. (only works in one to one relations)
I said I can guess because you didn't mention any information about tblInboxes and tblMessages fields. If you could provide me more information about their structure, I could answer in more detail.
By the way to make your code more clear you can use:
var u = conx.tblUsers.FirstOrDefault(m=>m.Id == userid);
instead of
var u = (from m in conx.tblUsers where m.Id == userid select m).FirstOrDefault();
OR
conx.tblMessages.FirstOrDefault(mu=>mu.Id == ux.Id)
instead of
conx.tblMessages.Where(mu=>mu.Id == ux.Id).FirstOrDefault()

Categories

Resources