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.
Related
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.
I am having a trouble with LINQ query for sort of a complicated selection.
I am trying to create simply social network, where user can post posts and other users can comment on them.
For some statistic I want to find out who are the user who left comments on all posts of currently logged on user.
This are the tasks I am trying to preform:
Find currently logged on user.
Get all other registered user (except currently logged on).
Get all comments on all posts that currently logged on user has.
Since every comment has UserId which presents ID of a user who has left the comment, I want to compare this UserIds with all other registered users and get list of users who were commenting to currently logged on user.
It sound bit complicated, but it is not actually.
This is my code:
public ActionResult ListAllUsersThatCommentedPostsToCurrentUser()
{
ApplicationDbContext db = new ApplicationDbContext();
//Get ID from current user
var currentUserId = User.Identity.GetUserId();
var user = db.Users.SingleOrDefault(x => x.Id == currentUserId);
var comments = new List<Comment>();
if (user != null)
{
//Get all posts of current user
var postsOfCurrentUser = db.Posts.Where(x => x.UserId == user.Id).ToList();
foreach (var post in postsOfCurrentUser)
{
//Get all comments on posts which belong to current user
comments = db.Comments.Where(x => x.PostId == post.PostId).ToList();
}
}
var usersThatCommentedPosts = new List<ApplicationUser>();
if (comments != null)
{
//Get all user except current one
var otherUsers = db.Users.Where(u => u.Id != currentUserId).ToList();
foreach(var comment in comments)
{
//Filter all users except current one according to UserIds in Comment list
usersThatCommentedPosts = otherUsers.Where(u => u.Id == comment.UserId).ToList();
}
}
return View(usersThatCommentedPosts);
}
The problem is in this line:
usersThatCommentedPosts = otherUsers.Where(u => u.Id == comment.UserId).ToList();
I always get last user how left the comment to current user, instead of list of all users who have left comments.
I guess the problem is in foreach loop, but I have a mess in my head and no idea how can I implement this in a different and more efficient way.
As well, if somebody see something that can be refactored comments are more than welcome, because I have feeling that I have made unnecessary mess here.
you're replacing usersThatCommentedPosts every iteration of that loop. If you want to append to the loop, use AddRange
var users = otherUsers.Where(u => u.Id == comment.UserId).ToList();
usersThatCommentedPosts.AddRange(users );
or better yet, do a join in a proper query. (this way you don't have db queries in a loop)
var userQry =
from post in db.Posts
join comment in db.Comments on post.PostId equals comment.PostId
join otherUser in db.Users on comment.UserId equals otherUser.Id
where post.UserId == currentUserId
where otherUser.Id != currentUserId
select otherUser;
var users = userQry.ToList();
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();
}
I have written some dirty code that retrieves user email in MVC. As you can see I´m using linq queries to retrieve info from my user database.
List<string> emails = new List<string> {ConstantHelper.AdminEmail, ConstantHelper.OwnerEmail};
DataContext mDataContext = new DataContext();
User user =
(from allUsers in mDataContext.Users.Where(u => u.UserName == User.Identity.Name)
select allUsers).FirstOrDefault();
string userEmail =
(from allMemberships in mDataContext.Memberships.Where(u => user != null && u.UserId == user.UserId)
select allMemberships.Email).FirstOrDefault();
if(userEmail == null)
{
return false;
}
emails.Add(userEmail);
//TODO: senda email
What I want to know if there is any other "shorter" or cleaner way to retrieve user email (of the user who is currently logged in)?
I googled this and found some suggestions regarding this code but I never got that to work for me.
MembershipUser u = Membership.GetUser(username);
My code works, it´s just that I would rather have cleaner code with this, any suggestions would be well appreciated :)
MembershipUser u = Membership.GetUser(username); is definitely a much better and shorter way to achieve that. You just need to write a custom membership provider to replace the default one in order to be able to customize the behavior of the GetUser and other methods to suit your needs.
I have a table Users. Users has a column rating. How i can get information about user place using linq2sql? I want method like:
var userPlace =
GetUserPlaceById(userId);
Table Users may contains a few thousands users.
Sorry guys. Users DOESNT contain place column. Real example: Rating is chess elo rating. if you have high rating then you on 1st place. If you have lower rating then you on the last place.
Did you mean something like this?
int userRating = users.Single(user => user.Id = userId).Rating;
int userPlace = users.Where(user => user.Rating < userRating).Count() + 1;
I have a table Users. Users has a column rating. How i can get information about user place using linq2sql?
I'm not sure what "userPlace" is, but assuming it is a column in that table...
var userPlace = (from user in db.Users
where user.Id == userId
select user)
.First()
.UserPlace;
Be aware that calling .First() will throw an exception if no match is found, so if you expect that sometimes this user will not exist use FirstOrDefault, check for null, and then grab the UserPlace property.
You would use something like:
string GetUserPlaceById(int userId)
{
IQueryable<User> users = GetUsers(); // Get users queryable reference
return users.Single(user => user.Id == userId).Place;
}
You could do something like this:
var userPlace = _db.Users.Where(x => x.UserId == userId).Select(x => x.Place).SingleOrDefault();