ASP.NET MVC4 Get email of logged user - asp.net

I am making asp.net mvc4 web application. I wrote contact form function in my controller which sends feedback from users. I am using System.Net.Mail class.
I am using Simplemembership and I extended UserProfile with string Email property.
How to get logged in user Email? I want to include it it sended message, so I Could answer.
I tried to use:
var em = from m in db.UserProfiles.Where(a => a.UserName.Contains(User.Identity.Name)) select m.Email;
string email = em.ToString();
but in the sent mail I have:
SELECT
[Extent1].[Email] AS [Email]
FROM [dbo].[UserProfile] AS [Extent1]
WHERE [Extent1].[UserName] LIKE #p__linq__0 ESCAPE N'~'

To retrieve a single entry of the database, you have to select the first row returned with the First() method:
string email = db.UserProfiles
.Where(a => a.UserName.Contains(User.Identity.Name))
.First().Email;
Hope it helps !

You already have the correct answer, so I am just throwing this up here for future searchers to see the shorter syntax.
string email = db.UserProfiles
.FirstOrDefault(a => a.UserName.Contains(User.Identity.Name)).Email;
However in your scenario, I would be concerned about User1 receiving emails intended for User11. To prevent this, you need to be more specific in your query
string email = db.UserProfiles
.FirstOrDefault(a => a.UserName == User.Identity.Name).Email;

Related

ASP.NET Get Username for Logged-In User

I have a class named Store which happens to have a property named User.
This User can later log-in into the application.
The Problem:
What I attempt is to create a list of the Stores based on the User that is currently logged-in
Example of Store table: Last column Usuario a.k.a. User
What I have tried:
var Tiendas = await _context.Stores
.Where(t => t.Usuario= User.Identity.Name.ToString()).ToListAsync();
Is it a close attempt? I'm getting an error:
Can't convert the type string into bool.
var Tiendas = await _context.Stores
.Where(t => t.Usuario == User.Identity.Name).ToListAsync();
Change your t.Usuario = User.Identity.Name.ToString() to t.Usuario == User.Identity.Name
You're using an assignment operator when you should be using a comparison operator. Also you can remove the .ToString() since User.Identity.Name is a string already.

ASP.NET Identity : Cannot sign-in existed user

I use ASP.NET Identity 2 in an MVC 5 project and there are some users in AspNetUsers table. Although these users have been created and validated, it is impossible to retrieve any of them bu using:
var user = await UserManager.FindByNameAsync(model.Email);
Please note that I used email addressed for UserName as Email fields and it is ok to use email address for retrieving users.
On the other hand, I can retrieve the users by:
ApplicationUser user = db.Users.FirstOrDefault(m => m.Email == model.Email);
But, I cannot make sign-in the user with the following code and the result is always Failure.
var result = await SignInManager.PasswordSignInAsync(user.Email,
model.Password, model.RememberMe, shouldLockout: false);
Any idea to fix the problem?

How to read symfony fetched data from database

I am very new to symfony and got knowledge in php. On my project my end result of db query is $user.\
if i use print_r($user) i get this result
xxx\xxxx\Article Object ( [username:xxxx\xxxx\Article:private] => asdfasdf [passsword:xxxx\xxxx\Article:private] => [usertype:xxxx\xxxx\Article:private] => gaeafsdfa)
how can i fetch the username to check against a specific user and if condition passes change password to other.
All i need to how to read the username and how to set the password.
I found the answer
I got to call as
$user->getUsername(); // to see the user name
$user->setPassword($generatedPassword); // to update the password.

Create chat group in SignalR

How can I create a chat group in SignalR? I tried to find some examples and they weren't helpful. Any help would be appreciated. Here is what I've come up with so far:
public void CreateGroup(string currentUserId, string toConnectTo)
{
string strGroupName = GetUniqueGroupName(currentUserId, toConnectTo);
string connectionId_To = OnlineUser.userObj.Where(item => item.userId == toConnectTo).Select(item => item.connectionId).SingleOrDefault();
if (!string.IsNullOrEmpty(connectionId_To))
{
Groups.Add(Context.ConnectionId, strGroupName);
Groups.Add(connectionId_To, strGroupName);
Clients.Caller.setChatWindow(strGroupName, toConnectTo);
}
}
It's not such easy to create a user friendly chat group that I'm currently working on.
I use sql database, user can register, login, logout, close browser or phone app without logout.
user can create own group, add members to group, delete member from group.
when user send message, call signalr Server method and store message in sql, then Server send message to all users in the same group. if some users are offline, they read message from sql when online again.
the input for the message can be a 'contenteditable div' so that user can add images and formatted text to the message.
something like that!

Storing DotNetOpenAuth information and user info retrieval

This question is a bit of a structural/design question as I'm having trouble working out the best way to perform the task.
In my MVC app, I am using DotNetOpenAuth (3.4) as my login information provider and just using the standard FormsAuthentication for cookies etc.
The current user table in the DB has:
UserId (PK, uniqueidentifier)
OpenIdIdentifier (nvarchar(255))
OpenIdDisplay (nvarchar(255))
Displayname (nvarchar(50))
Email (nvarchar(50))
PhoneNumber (nvarchar(50))
As the UserId is the clear identifier for a user (they should be able to change their OpenId provider at a later date), it is the key that other tables link to (for a user).
This is the current code, that on a successfull authentication, creates a temporary user and redirects to Create Action.
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
var users = new UserRepository();
if (!users.IsOpenIdAssociated(response.ClaimedIdentifier))
{
var newUser = new DueDate.Models.User();
newUser.OpenIdIdentifer = response.ClaimedIdentifier;
newUser.OpenIdDisplay = response.FriendlyIdentifierForDisplay;
TempData["newUser"] = newUser;
return this.RedirectToAction("Create");
}
And now for the crux of the question:
Is the response.ClaimedIdentifier the correct piece of information to be storing against a user?
Is FormAuthentication.SetAuthCookie the preferred way to forms authentication? Or is there a better way?
When I call SetAuthCookie, there is no data relating to the user except for the ClaimedIdentifier. If I'm consistently referring to their UserId, is a better idea to create the user, then store that UserId in the cookie instead of the ClaimedIdentifier?
If I'm using that UserId in a number of places, how do I either retrieve it from the cookie, or store it somewhere else more logical/useful?
A bit long winded but I've been having trouble trying to work out the best way to do this/
1.Is the response.ClaimedIdentifier the correct piece of information to be storing against a user?
Yes. And make sure the column you store it in the database with is case sensitive. Here is a table schema that demonstrates how to make sure it is case sensitive. This comes out of the DotNetOpenAuth project template's database schema. The "CS" bit of the specified collation stand for Case Sensitive.
CREATE TABLE [dbo].[AuthenticationToken] (
[AuthenticationTokenId] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[OpenIdClaimedIdentifier] NVARCHAR (250) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
[OpenIdFriendlyIdentifier] NVARCHAR (250) NULL,
[CreatedOn] DATETIME NOT NULL,
[LastUsed] DATETIME NOT NULL,
[UsageCount] INT NOT NULL
);
2.Is FormAuthentication.SetAuthCookie the preferred way to forms authentication? Or is there a better way?
For MVC apps it definitely is, since you still can return your preferred ActionResult from the method.
3.When I call SetAuthCookie, there is no data relating to the user except for the ClaimedIdentifier. If I'm consistently referring to their UserId, is a better idea to create the user, then store that UserId in the cookie instead of the ClaimedIdentifier?
That sounds like personal preference. But I would typically go with user_id, since it might result in a faster database lookup every time an HTTP request comes in that requires you to look up any user information.
4.If I'm using that UserId in a number of places, how do I either retrieve it from the cookie, or store it somewhere else more logical/useful?
FormsAuthentication does provide a way to store more information in its encrypted cookie than just username, but it is harder than you'd expect to use it. This snippet comes out of DotNetOpenAuth's web SSO RP sample:
const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file
var ticket = new FormsAuthenticationTicket(
2, // magic number used by FormsAuth
response.ClaimedIdentifier, // username
DateTime.Now,
DateTime.Now.AddMinutes(TimeoutInMinutes),
false, // "remember me"
"your extra data goes here");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.SetCookie(cookie);
Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
Then you can get at that extra data in a future HTTP request with this:
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null) {
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (!string.IsNullOrEmpty(ticket.UserData)) {
// do something cool with the extra data here
}
}

Resources