How can I get UserName or UserId from loginName control? - asp.net

I'm wondering is there any way i could get UserName or UserId for current User from LoginName control in ASP.NET ?

You could use the User property of the Page class:
string userName = Page.User.Identity.Name;

You could just read from Page.User.Identity.Name or HttpContext.Current.User.Identity.Name.

Related

How do I log a user back in after change of Email/Username? - Asp.net/VB.Net

I found this code on a site which was written for me and works, and I'm trying to use it on a new site. The code checks that a emailAddress doesn't already exist when a user edits their account details, and because the emailAddress is also used as the underlying .NET membership username it needs to change that too. So far I've managed to get it to change the email address in tblAccounts which is done with this call:
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
Then it needs to check if the user changing the email is the logged in user and re-log them back in. This doesn't seem to work as I get this error from the siteMaster when it tries to redirect to the homepage:
System.NullReferenceException: Object reference not set to an instance of an object.
The error is caused in the siteMaster when it tries to check messages for logged in user and it flags up the last line of this as where the error occurs:
If HttpContext.Current.User.Identity.IsAuthenticated Then
hypSettings.visible=true
Dim counter As Integer = messaging.CheckUnreadMessages(Membership.GetUser.ProviderUserKey)
It therefore looks like the email address is being updated where it should, but the site isn't logging the user back in correctly. As I say, it works on the site where I took the code from and there isn't much difference between the sites, but I don't understand memberships and cookies too well so I'm not sure if something needs altering elsewhere?
Here's the code for changing the users email address:
'Check if the Role has been changed
Membership.ApplicationName = "/OCBS"
Dim userID As Guid = Guid.Parse(Request.QueryString("aID"))
Dim usr As MembershipUser = Membership.GetUser(userID, False)
'Now check if the email address has been changed, because the email address is used for the username then the underlying .NET membership username needs changing
If txtEmailAddress.Text <> lblEmailAddress.Text Then
'Email has been changed, update the username for this user
Dim acc As New accounts(Guid.Empty)
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
'Check if the user changing the email is the logged in user and re-log them back in
If User.Identity.Name = lblEmailAddress.Text Then
'FormsAuthentication.SetAuthCookie(txtEmailAddress.Text, False)
Response.Cookies.Clear()
Dim expiryDate As DateTime = DateTime.Now.AddDays(100)
Dim ticket As New FormsAuthenticationTicket(2, txtEmailAddress.Text, DateTime.Now, expiryDate, True, [String].Empty)
Dim encryptedTicket As String = FormsAuthentication.Encrypt(ticket)
Dim authenticationCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
authenticationCookie.Expires = ticket.Expiration
Response.Cookies.Add(authenticationCookie)
End If
End If
Oooh, I've managed it.. I added this..
Session.Abandon()
FormsAuthentication.SignOut()
after line: Response.Cookies.Clear()

How do I trigger a reset password?

I work in Microsoft .NET 4.0 environment.
In my application I enable the user to get new automatic password.
So I use in my .cs file the method:
MembershipUser user = Membership.GetUser();
user.ResetPassword();
I want to trigger on reset Password, means: when the password is changed to the automatic
one, an email will be sent to the user's email address with the new password (that is returned from user.ResetPassword()).
I use standard Membership DB tables.
I wrote the following trigger:
CREATE TRIGGER MembershipChangePass ON aspnet_Membership
AFTER UPDATE,DELETE
AS
BEGIN
DECLARE #user uniqueidentifier
DECLARE #email nvarchar(256)
SELECT #user = (SELECT UserId FROM UPDATED)
SELECT #email =(SELECT LoweredEmail FROM aspnet_Membership
WHERE #user=UserId)
EXEC xp_sendmail #email, ???
END
GO
The problem is how do I get the ??? - the new automatic password I created by
the method: user.ResetPassword();
Can I define the TRIGGER to be used only with user.ResetPassword(), and not with other
methods (like: (user.ChangePassword(...))?
Maybe there is another simple way to trigger reset password?
Thank you.
The ResetPassword() method returns the new password which you can grab and send to the user
string newPassword = user.ResetPassword();
string toAddr = "user email here";
string subject = "Password reset notification";
string body = "Your new password is "+newPassword;
//mail.Send(fromAddr, toAddr, subject, body);

How to provide different pages on login for different users?

I'm working on web application which has a database
UserName|Password|UserType
Anil|Anil|Manager
ghouse|Ghouse|Admin
raghu|raghu|User
Now my task is to provide each user their own page on login...They all have a same login page.
I tried this code it's working fine for two users. What to do if I have more than two users?
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUsername.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
Response.Redirect("~/CallingAgents/CallingAgents_Login.aspx");
else
Response.Redirect("~/UserRegistrationForm.aspx");
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
I think you should create a common class where insert your user type on successful login.
In that common class redirect it to respective page.
On successful login:
Response.Redirect(clsCommon.GetDefaultPage(userType));
your commaon class code:
public static string GetDefaultPage(string userType){
//Default Redirects
Dictionary<string, string> userInfo = new Dictionary<string, string>(){
{"Manager","~/ManagerLogin.aspx"}, {"Admin","~/AdminLogin.aspx"},
{"User","~/UserLogin.aspx"}
};
return userInfo[roleName];
}
If you are using struts then you can redirect to different pages depending upon some Id. In actionforward you can achieve so. Or you can get some values from the url and try to redirect it
A simple way would be to use the Login-control and provide event handlers for the Authenticate event and the LoggedIn event. But i think it would be worth while for you to check out the capabilities of the asp.net membership system.
I assume you are not using Membership provider and make your login functionality by hand.
I do not fully understand the purpose of this customization. It make no sense for me. But there are multiple solutions for you:
convert the login page (aspx) into a user/custom control (ascx) and put in into different pages - simple, quick but not fully transparent, more info ScottGu
use IIS URL-Rewrite engine to provide multiple entry-points (urls)
to the same login page - clear, recomended, more info ScottGu
With first scenario you need to check UserType for credentials given by the user and confront it with page Url (aspx). In the second scenario, you need to obtain Request.RawUrl which contain base Url and make simple case.
Make use of sessions.
For a workaround, you can follow this:
+provide the same login page.
+Ask for username and password.
+use a drop down for selecting the usertype (ie Admin or Manager or User).
So based on the selection from drop down list you process the request.
I hope this helps.

FormsAuthentication Rememberme

I am using forms authentication and the I wanted the remember me functionality.
How can I just retain the username alone.
I wanted the username to be stored on cookies and when the user is logged out. I want to user name to be displayed on the username text box.
Is there an example that can be provided?
In the login method (Probably your "Login" button click):
Response.Cookies["userName"].Value = txtUserName.Text;
Then on the Page_Load check for that cookie and assign the textbox a value.
if (!String.IsNullOrEmpty(Request.Cookies["userName"])) {
txtUserName.Text = Request.Cookies["userName"];
}

to display username on all aspx pages

How to Dispaly the username on all aspx pages....?
Can any one help me in this context.....
am thinking that by using "session object" we can able to do this...bt am not sure
Can any send the code or links
Assuming that you have a mechanism you can use to obtain the current user's username, you could fetch that and add code to your master page(s) to display the name. There's not really much more that can be said from your question. (Ask a vague question, get a vague answer.)
And also, if you aren't using master pages, you should be using master pages.
You can use a master page if you want to display the username on all pages.
Username can be stored in a cookie, session, etc.
Code sample:
lblUsername.Text = Session["Username"]
System.Security.Principal.IPrincipal user;
user = System.Web.HttpContext.Current.User;
System.Security.Principal.IIdentity identity;
identity = user.Identity;
lblUserName.Text = identity.Name.Substring(identity.Name.IndexOf(#"\") + 1); ToString();
In First Page (Login page), store the value in Session
Session["Username"] = txtusername.text;
And rest of the pages, where you want to display the UserName
lblUser.Text = Session["Username"].Tostring();
For Logout
Session["Username"] = null;

Resources