OK - I'm done ... I used the recommendations in this thread to make changes that allow me to simply refer to the user id, name, or email throughout my application using: UserInfo.ID(context.user.identity.name) or UserInfo.Name(context.user.identity.name) or
UserInfo.Email(context.user.identity.name) I had the same desire/need to use more than an email to refer to a user, i.e., I wanted access to the User ID, Email, and Name throughout my application (e.g., display name instead of email in banner, use id as foriegn
key in db tables rather than email, use email for notifications, etc.) I initially used a cookie for user name that I set in the signin.ascx.vb file but wanted to use something in the context.user.identity session properties - I want to limit use of cookies
for my mobile users and I feel that the id, name, and email are related and should 'travel' together. My approach (based in large part on the guidance of other posts - thanks!): 1) In the security.vb component, I added the following parameter to the usersDB.login
method: Dim parameterUserID As New SqlParameter("@UserID", SqlDbType.Int) parameterUserID.Direction = ParameterDirection.Output myCommand.Parameters.Add(parameterUserID) 2) I modified the UserLogin sproc to select and return the UserID from the users table
(I added the '@UserID integer output' param in at the end of the param list and '@UserID = UserID' in the select list) 3) In the security.vb component (at the bottom right below the UsersDB.login method), I added a new abstract class with only shared methods
to bundle the logic to build and parse a UserInfo string that contains the user id, name, and email delimited by pipes (as suggested by Brian). This class allows me to access any userInfo field easily, e.g., UserInfo.Name(context.user.identity.name) or UserInfo.Email(context.user.identity.name)
Public Class UserInfo Public Shared Function InfoString(ByVal ID As String, ByVal Name As String, ByVal Email As String) As String Return ID + "|" + Name + "|" + Email End Function Public Shared Function ID(ByVal UserInfo As String) As String Dim items() As
String items = UserInfo.Split("|") Return items(0) End Function Public Shared Function Name(ByVal UserInfo As String) As String Dim items() As String items = UserInfo.Split("|") Return items(1) End Function Public Shared Function Email(ByVal UserInfo As String)
As String Dim items() As String items = UserInfo.Split("|") Return items(2) End Function End Class 4) In the security.vb component, I added the following method call to the new UserInfo.InfoString method at the end of the usersDB.login method to return the
UserInfo string: Return UserInfo.InfoString(parameterUserID.Value, CStr(parameterUserName.Value).Trim(), CStr(parameterEmail.Value).Trim()) 5) In Signin.ascx.vb, I changed the references to userID to userInfo to more accurately reflect reality and I changed
the userName parameter in the setauthcookie from email.text to the userInfo field returned by usersDB.login: FormsAuthentication.SetAuthCookie(userInfo, RememberCheckbox.Checked) 6) Now you can change references in other IBS files/modules from context.user.identity.name
(or just user.identity.name) to UserInfo.Email(context.user.identity.name). I just did a "search in files" and replaced each occurance (about 12 of them). At a minimum, change the two occurances in the global.asax file. ***** DONE! Now I can simply refer to
UserInfo.ID(context.user.identity.name) or UserInfo.Name(context.user.identity.name) or UserInfo.Email(context.user.identity.name) anywhere. For example, in the DesktopPortalBanner, I was simply able to change the welcome message text to: WelcomeMessage.Text
= "Welcome " & UserInfo.Name(Context.User.Identity.Name) & "! <" & "span class=Accent" & ">|<" & "/span" & ">" I'm new to ASP and ASP.NET, but I think this is very clean. Thoughts? Critique?
One more change - I missed this at first (thanks to Anthony Fisher) ... In the Register.aspx.vb file, you also need to make the following quick changes (change lines have an '***** after them: Private Sub RegisterBtn_Click(ByVal sender As Object, ByVal E As
EventArgs) Handles RegisterBtn.Click ' Only attempt a login if all form fields on the page are valid If Page.IsValid = True Then ' Add New User to Portal User Database Dim accountSystem As New ASPNetPortal3.UsersDB() ' ibschange - add user id/name to user.identity
- set userName in AuthCookie to UserInfo ***** ' 1. dim userid and set to new user id returned by AddUser ***** ' 2. in IF statement, check userId vs. accountSystem.AddUser(Name.Text, Email.Text, Password.Text) ***** ' 3. change email.text to userInfo.InfoString(...)
in SetAuthCookie ***** Dim UserID As Integer '***** UserID = accountSystem.AddUser(Name.Text, Email.Text, Password.Text) '***** If UserID Then '***** ' Set the user's authentication name to the userId '***** FormsAuthentication.SetAuthCookie(UserInfo.InfoString(UserID,
Name.Text, Email.Text), False) '***** ' Redirect browser back to home page' Response.Redirect("~/DesktopDefault.aspx") Else Message.Text = "Registration Failed! <" & "u" & ">" & Email.Text & "<" & "/u" & "> is already registered." & "<" & "br" & ">" & "Please
register using a different email address." End If End If End Sub
Mike, would it be possible for you to post a more complete example of of Global.aspx.vb and register.aspx.vb. I have made extensive changes to my userDb class and my entire registration process and it seems that I am just missing something with this. I have
the code working in Security.vb and I can call UserInfo.whatever,but I seem to still have a bug with the registration part. If I could see the entire code of these files I know I will see my problem. Any help would be appreciated. Bruce
Here is my entire global.asax and register.aspx.vb files (I also attached my UserInfo class): GLOBAL.ASAX Imports System.Security Imports System.Security.Principal Imports System.Web.Security Namespace ASPNetPortal3 Public Class Global Inherits System.Web.HttpApplication
'********************************************************************* ' ' Application_BeginRequest Event ' ' The Application_BeginRequest method is an ASP.NET event that executes ' on each web request into the portal application. The below method ' obtains
the current tabIndex and TabId from the querystring of the ' request -- and then obtains the configuration necessary to process ' and render the request. ' ' This portal configuration is stored within the application's "Context" ' object -- which is available
to all pages, controls and components ' during the processing of a single request. ' '********************************************************************* Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) Dim tabIndex As Integer =
0 Dim tabId As Integer = 0 ' Get TabIndex from querystring If Not (Request.Params("tabindex") Is Nothing) Then tabIndex = CInt(Request.Params("tabindex")) End If ' Get TabID from querystring If Not (Request.Params("tabid") Is Nothing) Then tabId = CInt(Request.Params("tabid"))
End If ' ibsextra 14 - Support root folder - build Application("AppPath") to replace "~" or Request.ApplicationPath If Application("AppPath") = Nothing Then Dim sAbsUri As String = Request.Url.AbsoluteUri Dim sRawUrl As String = Request.RawUrl If Request.ApplicationPath
= "/" Then Application("AppPath") = Left(sAbsUri, Len(sAbsUri) - Len(sRawUrl)) Else Application("AppPath") = Left(sAbsUri, Len(sAbsUri) - Len(sRawUrl)) & Request.ApplicationPath End If End If Context.Items.Add("PortalSettings", New PortalSettings(tabIndex,
tabId)) End Sub '********************************************************************* ' ' Application_AuthenticateRequest Event ' ' If the client is authenticated with the application, then determine ' which security roles he/she belongs to and replace the
"User" intrinsic ' with a custom IPrincipal security object that permits "User.IsInRole" ' role checks within the application ' ' Roles are cached in the browser in an in-memory encrypted cookie. If the ' cookie doesn't exist yet for this session, create it.
' '********************************************************************* Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) If Request.IsAuthenticated = True Then Dim roles() As String ' Create the roles cookie if it doesn't
exist yet for this session. If Request.Cookies("portalroles") Is Nothing Then ' Get roles from UserRoles table, and add to cookie Dim _user As New UsersDB() ' todo 9c - change from user email to user id? roles = _user.GetRoles(UserInfo.Email(User.Identity.Name))
' Create a string to persist the roles Dim roleStr As String = "" Dim role As String For Each role In roles roleStr += role roleStr += ";" Next role ' Create a cookie authentication ticket. ' version ' user name ' issue time ' expires every hour ' don't persist
cookie ' roles ' todo 9c - change from user email to user id? Dim ticket As New FormsAuthenticationTicket(1, _ UserInfo.Email(Context.User.Identity.Name), _ DateTime.Now, _ DateTime.Now.AddHours(1), _ False, _ roleStr) ' Encrypt the ticket Dim cookieStr As
String = FormsAuthentication.Encrypt(ticket) ' Send the cookie to the client Response.Cookies("portalroles").Value = cookieStr Response.Cookies("portalroles").Path = "/" Response.Cookies("portalroles").Expires = DateTime.Now.AddMinutes(1) Else ' Get roles
from roles cookie Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(Context.Request.Cookies("portalroles").Value) 'convert the string representation of the role data into a string array Dim userRoles As New ArrayList() Dim role As String
For Each role In ticket.UserData.Split(New Char() {";"c}) userRoles.Add(role) Next role roles = CType(userRoles.ToArray(GetType(String)), String()) End If ' Request.Cookies("portalroles") Is Nothing ' Add our own custom principal to the request containing
the roles in the auth ticket Context.User = New GenericPrincipal(Context.User.Identity, roles) If Request.Cookies("portaluserinfo") Is Nothing Then Else End If ' Request.Cookies("portaluser") Is Nothing End If ' Request.IsAuthenticated = True End Sub End Class
End Namespace REGISTER.ASPX.VB Imports System.Web.Security Namespace ASPNetPortal3 Public Class Register Inherits System.Web.UI.Page Protected WithEvents Name As System.Web.UI.WebControls.TextBox Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents Email As System.Web.UI.WebControls.TextBox Protected WithEvents RegularExpressionValidator1 As System.Web.UI.WebControls.RegularExpressionValidator Protected WithEvents RequiredFieldValidator2 As System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents Password As System.Web.UI.WebControls.TextBox Protected WithEvents RequiredFieldValidator3 As System.Web.UI.WebControls.RequiredFieldValidator Protected WithEvents ConfirmPassword As System.Web.UI.WebControls.TextBox Protected WithEvents
RequiredFieldValidator4 As System.Web.UI.WebControls.RequiredFieldValidator Protected WithEvents CompareValidator1 As System.Web.UI.WebControls.CompareValidator Protected WithEvents RegisterBtn As System.Web.UI.WebControls.LinkButton Protected WithEvents Message
As System.Web.UI.WebControls.Label #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub RegisterBtn_Click(ByVal sender As Object, ByVal E As EventArgs) Handles RegisterBtn.Click
' Only attempt a login if all form fields on the page are valid If Page.IsValid = True Then ' Add New User to Portal User Database Dim accountSystem As New ASPNetPortal3.UsersDB() ' ibsextra 9 - add user id/name to user.identity - set userName in AuthCookie
to UserInfo ' 1. dim userid and set to new user id returned by AddUser ' 2. in IF statement, check userId vs. accountSystem.AddUser(Name.Text, Email.Text, Password.Text) ' 3. change email.text to userInfo.InfoString(...) in SetAuthCookie Dim UserID As Integer
UserID = accountSystem.AddUser(Name.Text, Email.Text, Password.Text) If UserID Then ' Set the user's authentication name to the userId FormsAuthentication.SetAuthCookie(UserInfo.InfoString(UserID, Name.Text, Email.Text), False) ' Redirect browser back to home
page' Response.Redirect("~/DesktopDefault.aspx") Else Message.Text = "Registration Failed! <" & "u" & ">" & Email.Text & "<" & "/u" & "> is already registered." & "<" & "br" & ">" & "Please register using a different email address." End If End If End Sub End
Class End Namespace USERINFO '********************************************************************* ' ' ibsextra 9 - add user id/name to user.identity - UserInfo Class ' ' The UserInfo class is used to build and parse a string of user information ' for storage
in the context.user.identity.name property (this is populated ' via the forms authentication ticket created during signin) ' '********************************************************************* Public Class UserInfo Public Shared Function InfoString(ByVal
ID As String, ByVal Name As String, ByVal Email As String) As String Return ID + "|" + Name + "|" + Email End Function Public Shared Function ID(ByVal UserInfo As String) As String Dim items() As String items = UserInfo.Split("|") Return items(0) Dim s As
String = HttpContext.Current.User.Identity.Name End Function Public Shared Function ID() As String Dim items() As String items = HttpContext.Current.User.Identity.Name.Split("|") Return items(0) End Function Public Shared Function Name(ByVal UserInfo As String)
As String Dim items() As String items = UserInfo.Split("|") Return items(1) End Function Public Shared Function Name() As String Dim items() As String items = HttpContext.Current.User.Identity.Name.Split("|") Return items(1) End Function Public Shared Function
Email(ByVal UserInfo As String) As String Dim items() As String items = UserInfo.Split("|") Return items(2) End Function Public Shared Function Email() As String Dim items() As String items = HttpContext.Current.User.Identity.Name.Split("|") Return items(2)
End Function end class
One reason is running multiple portals from one db (as I do). You would want unique registrations per portal. You would not want to key off of the email address.
For anyone that is interested here is the code in c#: The User Info Class to add to the bottom of Secrity.cs: public class UserInfo { public string InfoString(string Id , string Name, string Email) { return Id + "|" + Name + "|" + Email ; } public string Id(string
UserInfo) { string []items; items = UserInfo.Split(new Char[] {'|'}) ; return items[0] ; } public string Name(string UserInfo) { string []items; items = UserInfo.Split(new Char[] {'|'}) ; return items[1] ; } public string Email(string UserInfo) { string []items;
items = UserInfo.Split(new Char[] {'|'}) ; return items[2] ; } } *************************************************************** The code at the bottom of The login method to return the string if ((parameterUserName.Value != null) && (parameterUserName.Value
!= System.DBNull.Value)) { UserInfo Info = new UserInfo(); string UserString = Info.InfoString((parameterUserId.Value).ToString(), ((string)parameterUserName.Value).Trim(), ((string)parameterEmail.Value).Trim()) ; return UserString; } *****************************************************************
The method to add the email to the context: if (Request.IsAuthenticated == true) { String[] roles; // Create the roles cookie if it doesn't exist yet for this session. if ((Request.Cookies["portalroles"] == null) || (Request.Cookies["portalroles"].Value ==
"")) { // Get roles from UserRoles table, and add to cookie UsersDB user = new UsersDB(); UserInfo Info = new UserInfo(); roles = user.GetRoles(Info.Email(Context.User.Identity.Name)); // Create a string to persist the roles String roleStr = ""; foreach (String
role in roles) { roleStr += role; roleStr += ";"; } // Create a cookie authentication ticket. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // version Info.Email(Context.User.Identity.Name), // user name DateTime.Now, // issue time DateTime.Now.AddHours(1),
// expires every hour false, // don't persist cookie roleStr // roles ); // Encrypt the ticket String cookieStr = FormsAuthentication.Encrypt(ticket); // Send the cookie to the client Response.Cookies["portalroles"].Value = cookieStr; Response.Cookies["portalroles"].Path
= "/"; Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1); } ************************************************************** This Should help you to get it going if you follow the VB post above and use this c# code as reference Cheers Anthony
Anthony, I have implemented the C3 version which youmentioned and also Mike's instructions. On doing so , in the DesktopPortalBanner.ascx I replaced the line WelcomeMessage.Text = "Welcome " + Context.User.Identity.Name + "! <" + "span class=Accent" + ">|<"
+ "/span" + ">"; replaced with UserInfo Uname = new UserInfo(); WelcomeMessage.Text = "Welcome " + Uname.Name(Context.User.Identity.Name) + "! <" + "span class=Accent" + ">|<" + "/span" + ">"; and I am getting this err could you pls suggest Server Error in
'/portalcsvsmc' Application. -------------------------------------------------------------------------------- Index was outside the bounds of the array. Description: An unhandled exception occurred during the execution of the current web request. Please review
the stack trace for more information about the error and where it originated in the code. Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array. Source Error: An unhandled exception was generated during the execution
of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [IndexOutOfRangeException: Index was outside the bounds of the array.] ASPNetPortal.UserInfo.Name(String
UserInfo) ASPNetPortal.DesktopPortalBanner.Page_Load(Object sender, EventArgs e) System.Web.UI.Control.OnLoad(EventArgs e) System.Web.UI.Control.LoadRecursive() System.Web.UI.Control.LoadRecursive() System.Web.UI.Control.LoadRecursive() System.Web.UI.Page.ProcessRequestMain()
Folks, there's a more elegant way of achieving this. I had the same requirements (wanting to store additional information besides just the name (like an ID, a 'friendly' name for display purposes, etc.). To solve this, I created a new identity object (inherited
the GenericIdentity object, which is what the Context.User object is). I added new properties to store the data I was interested in (friendly name, user id, etc.) and use this object to store in the cookie. I can post code if anyone is interested.
mbeller
Member
255 Points
51 Posts
Re: Extending Context.User.Identity.Name to add USERID
Sep 03, 2002 02:06 AM|LINK
Lightship Partners LLC
mbeller
Member
255 Points
51 Posts
Re: Extending Context.User.Identity.Name to add USERID
Sep 10, 2002 03:53 PM|LINK
Lightship Partners LLC
bhopkins
Star
9191 Points
1843 Posts
MVP
Re: Extending Context.User.Identity.Name to add USERID
Oct 10, 2002 12:10 PM|LINK
mbeller
Member
255 Points
51 Posts
Re: Extending Context.User.Identity.Name to add USERID
Oct 10, 2002 03:21 PM|LINK
Lightship Partners LLC
bhopkins
Star
9191 Points
1843 Posts
MVP
Re: Extending Context.User.Identity.Name to add USERID
Oct 10, 2002 03:35 PM|LINK
dev68
Member
75 Points
15 Posts
Re: Extending Context.User.Identity.Name to add USERID
Oct 10, 2002 04:33 PM|LINK
ShadowDanser
Participant
1581 Points
437 Posts
Re: Extending Context.User.Identity.Name to add USERID
Nov 03, 2002 05:56 PM|LINK
TonyK
Member
20 Points
4 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 09, 2003 11:05 AM|LINK
SpaceWorld
Member
10 Points
2 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 11, 2003 03:01 PM|LINK
davidbarrett
Member
155 Points
31 Posts
Re: Extending Context.User.Identity.Name to add USERID
Jan 11, 2003 03:57 PM|LINK