Link to home
Start Free TrialLog in
Avatar of Sheritlw
SheritlwFlag for United States of America

asked on

Membership.GetUser returns nothing after moving app.

Hi EE,

I had to move my web app to another machine and since this move I can't return the userid from the membership provider.
I made sure the connection string is right (I am using sql server 2005, developer edition), and the users are in the db.
Everything looks right, but I still get nothing when I try to get the userid.
I am using Linq to sql and all the classes are fine.
What am I missing?
Avatar of CyberSoft
CyberSoft
Flag of United States of America image

Hi there,

It sounds like ASP.Net Membership needs to be re-applied to the database on the SQL Server of the machine you've moved your application and database too. I'm assuming you also don't see any exception errors.

Try re-applying the membership to the database - see here for reference:
http://msdn.microsoft.com/en-us/library/ms229862(v=vs.80).aspx

You can try running the tool with the -W parameter to run through the Wizard if you don't feel comfortable adding all the parameters on the command line.

HTH
Deems
--->I made sure the connection string is right (I am using sql server 2005, developer edition), and the users are in the db.
Make sure this is not the case:
http://weblogs.asp.net/scottgu/archive/2006/04/22/Always-set-the-_2200_applicationName_2200_-property-when-configuring-ASP.NET-2.0-Membership-and-other-Providers.aspx
Assuming the tables are setup, as CyberSoft indicates, you need to make sure that the applicationName in your web.config file matches the applicationName in the aspnet_applications table. This ApplicationId is a foreign key used on all of the aspnet_ tables. You may have a new key that isn't matching up with the records already in your other tables.

If this is your issue, you can correct it by updating the ApplicationId in the aspnet_applications table to the key specified in the records in the aspnet_users, aspnet_mempbership, etc. tables.
Avatar of Sheritlw

ASKER

I did check the application key when I was checking the users and it was also okay.
I am going to try some of the tips tonight.  
Thanks
Use the same applicationName attribute of your membership configuration
This is strange.  
I did find under roles that the app name was set to "/".  I changed it to the applicationname "/Salon"  and verified that applicationname was set correctly throughout.
I then went into the db and checked the application, users, roles, and users in roles, to make sure the keys matched.
Since they matched I went into the asp.net web application administration tool and it shows my user, roles etc.
I ran debug and it still returns nothing.
Any ideas?
Thanks
<membership defaultProvider="SalonSqlMembershipProvider">
			<providers>
				<clear/>
				<add name="SalonSqlMembershipProvider" 
             type="System.Web.Security.SqlMembershipProvider,&#xA;                   
             System.Web, Version=2.0.0.0, Culture=neutral,&#xA;                  
             PublicKeyToken=b03f5f7f11d50a3a" 
             connectionStringName="LocalSqlServer" 
             enablePasswordRetrieval="false" 
             enablePasswordReset="true" 
             requiresQuestionAndAnswer="true" 
             applicationName="/Salon" 
             requiresUniqueEmail="false" 
             passwordFormat="Hashed" 
             maxInvalidPasswordAttempts="5" 
             minRequiredPasswordLength="6"
             minRequiredNonalphanumericCharacters="0" 
             passwordAttemptWindow="10" 
             passwordStrengthRegularExpression="^.*(?=.{6,})(?=.*\d).*$"/>
			</providers>
		</membership>
		<roleManager enabled="true" defaultProvider="SalonNetRoleProvider">
			<providers>
				<clear/>
				<add name="SalonNetRoleProvider" 
             connectionStringName="LocalSqlServer" 
             applicationName="/Salon" 
             type="System.Web.Security.SqlRoleProvider, 
             System.Web,&#xA;                    Version=2.0.0.0,&#xA;                    
             Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
			</providers>
		</roleManager>


          If (Membership.ValidateUser(Me.Login1.UserName.ToString, Me.Login1.Password.ToString)) Then
               Dim u As New SalonUtilities
               u.GetUserID()



    Public Shared Function GetUserID() As Object
        Dim currentUser As MembershipUser = Membership.GetUser()
        ' Determine the currently logged on user's UserId value  
        If Not currentUser Is Nothing Then
            Return CType(currentUser.ProviderUserKey, Guid)
        Else
            Return Nothing
        End If
    End Function

Open in new window

If you can, I would set a breakpoint and trace your code to make sure the MembershipProvider is actually using the provider settings (and connection string) that you specified. Since you have the <clear /> tags in the config file, that should be working. Otherwise I would suspect it is picking up settings from the machine.config file.

If you can't trace the code, you could add some debugging code to output some of the values.

Make sure the record in the aspnet_applications table includes the forward slash: "/Salon" not just "Salon"

I'll look at some other possibilities, but right now I'm not thinking of anything else to check.
I have walked through the code and the / is included in the name and table.
I replace this line in Machine.config
    <!--<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>-->

with
   <add name="LocalSqlServer" connectionString="server=Sheri; database=Salon; integrated security=sspi; providername=System.Data.SqlClient"/>

It still returns nothing.  
This line is true
  If (Membership.ValidateUser(Me.Login1.UserName.ToString, Me.Login1.Password.ToString)) Then

so its validating the user.  I can see the user in the database, in the administrative tool, but it will not return the UserID.

Any other ideas?
Thanks

Have you tried running the sqlreg wizard against your database again to re-apply asp.net membership and roles?

 I also suggest defining your own connection string entry in the connectionStrings section and not use the localsqlserver one.

HTH
Deems
yes, I did run the sql reg on the database but it didn't do any good.
I have a different connection that I will use when I upload it.  
I will create another one to use locally and see if that works.
Thanks,
-->but it will not return the UserID.
When you say not returning UserId, you mean the GUID from user's table?
Can you share your login code and the place you are trying to retrieve that UserID?
In one of my reply's, I included the log in code.
It used to work before I moved the program to a different computer.

Thanks
Sorry, I didn't scroll all way but now i see the login code.
I would like you to try this:
1: Create a new user using CreateUserWizard.
2: Try using that user as login.

One another thing to note is that Membership.GetUsre() will try to fetch currently logged-in user. So for any reason your user is not logged-in or i should say your authentication cookie is not valid, GetUser will return null.
So put a check in before calling GetUser and set breakpoint to see if user is authenticated or not.

If Not Request.IsAuthenticated Then
   'Something wrong, user is not authenticated
End If
The user is not authenticated.  
I am going to go through my web.config to see if something got changed without me realizing it.
I haven't created the createuserwizard page yet, but it won't take long to create and try logging on that way.
Thanks
-->The user is not authenticated.  
Your authentication cookie won't be set until next page load. Since you are trying to access it inside your Login Page, I would suggest you to pass username to your GetUserID method like:

          If (Membership.ValidateUser(Me.Login1.UserName.ToString, Me.Login1.Password.ToString)) Then
               Dim u As New SalonUtilities
               u.GetUserID(Login1.UserName)

Then use it like:

 Public Shared Function GetUserID(username as String) As Object
        Dim currentUser As MembershipUser = Membership.GetUser(username)
....
....
I tried adding the FormsAuthentication.SetAuthCookie(Me.Login1.UserName, False) with no luck.

Thanks
Simply setting FormsAuthentication.SetAuthCookie won't work, as you still need a page_Load before user context is refreshed.

When you say, it was working before, what it used in some different scenario or exact same code?
Try my last suggestion and see if that's working.
It was the exact same code.
The program sees the database, I just can no longer return the userid.

Thanks
I just thought of something I did different, but I am not sure how that would affect anything.
In the database, I set cascade delete on the tables created by the membership provider.

Could that cause the problem?
You don't want to change those tables. But as long as the data is still in the table, the cascade delete hasn't hurt you. And it shouldn't hurt you down the road either. If you deleted your application record, you would lose basically everything else, but of course, without the application record, you couldn't access the users and other data anyway. So no, I don't think that is related.
First I went through and took off all the cascades.  No luck, didn't work.
Next I re-created my linq to sql classes... Still no luck
Any ideas?
Thanks
I would suggest you to create a test page with a textbox, button and a label.
In the button click event place this code:

Dim user As MembershipUser = Membership.GetUser(txtUserName.Text)
If user IsNot Nothing Then
      lblMessage.Text = user.ProviderUserKey.ToString()
Else
      lblMessage.Text = "User Not Found"
End If
I have tried that, but it still returns nothing.
I just replaced the login control to see if something was corrupt, but no luck.

Thanks
Ok so you are getting User Not Found?
And did you try creating a brand new user and see if that works?
I am creating that form now.
I successfully created a user with the createuserwizard.
I then logged off, then logged back on as the new user, and it still doesn't return the key.

Thanks
Ok so were you able to login as new user you mean ? and did you try running the test page I suggested passing this new username in the textbox?
I ran the error code below and it always ends up with the last option, password is incorrect.
    Protected Sub Login1_LoginError1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login1.LoginError
        Dim userInfo As MembershipUser = Membership.GetUser(Login1.UserName)

        If userInfo Is Nothing Then
            'The user entered an invalid username...
            LoginErrorDetails.Text = "There is no user in the database with the username " & Login1.UserName
        Else
            'See if the user is locked out or not approved
            If Not userInfo.IsApproved Then
                LoginErrorDetails.Text = "Your account has not yet been approved by the site's administrators. Please try again later..."
            ElseIf userInfo.IsLockedOut Then
                LoginErrorDetails.Text = "Your account has been locked out because of a maximum number of incorrect login attempts. You will NOT be able to login until you contact a site administrator and have your account unlocked."
            Else
                'The password was incorrect (don't show anything, the Login control already describes the problem)
                LoginErrorDetails.Text = String.Empty
            End If
        End If
    End Sub

Open in new window

--->I ran the error code below and it always ends up with the last option, password is incorrect.
Are you sure? Did you set the breakpoint on that LoginErrorDetails.Text = String.Empty ?
How about changing the message:

LoginErrorDetails.Text = "Something else was wrong"

Because if that would be the case then, the test page code I gave shouldn't return "User Not Found" message.
I was able to create a new user, but not log in.
yes, I walked through the code.
ASKER CERTIFIED SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It gets through the validate user and sets Authenticated = true but returns nothing for the user id.
I've attached the code behind and my class to set the session.
thanks
     Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
        If (Membership.ValidateUser(Me.Login1.UserName.ToString, Me.Login1.Password.ToString)) Then


            e.Authenticated = True
            Dim u As New SalonUtilities
            u.SetUserIDSession()

        Else
            e.Authenticated = False
            Me.LoginErrorDetails.Text = "Login was unsuccessful. Please try again"


        End If

    End Sub



Imports Microsoft.VisualBasic

Public Class SalonUtilities
     Inherits System.Web.UI.Page
    Public Shared Function GetUserID() As Object
        Dim currentUser As MembershipUser = Membership.GetUser()
        ' Determine the currently logged on user's UserId value  
        If Not currentUser Is Nothing Then
            Return CType(currentUser.ProviderUserKey, Guid)
        Else
            Return Nothing
        End If
    End Function

     Public Shared Function GetCachedUserID(ByVal UserName As String) As Guid
          ' if the UserID is not loaded , load it into cache 
          If HttpRuntime.Cache(UserName) Is Nothing Then
               HttpRuntime.Cache(UserName) = Membership.GetUser(UserName).ProviderUserKey
          End If

          Return HttpRuntime.Cache(UserName)
     End Function
     Public Sub SetUserIDSession()
          Dim s = GetUserID()

        If Not s Is Nothing Then
            Session.Add("UserID", s.ToString)
        End If
    End Sub

    ' called when the user logged out 
    Public Shared Sub RemoveCahcedUserID(ByVal UserName As String)
        HttpRuntime.Cache.Remove(UserName)
    End Sub
End Class

Open in new window

as mentioned in my comment http:#33781786 GetUser() will not return user until next page_Load. So Create another function GetUserID that takes string username parameter and use that to GetUser method.
It used to get the userid, but I will try and put it in the load event of the form that needs to open.
I need the userid to get the right data.
Thanks
I put it in the load event of the page that I am redirecting to.
It didn't work.  Same thing.
If you are getting autheticated, I don't see any reason why you can't get the UserId.
Simply place this code in the Page_Load of any page in your website:

Dim username As String ="Some Valid UserName WithWhichYouAre able to login successfully on this particular machine"
Dim user As MembershipUser = Membership.GetUser(username)
If user IsNot Nothing Then
   Response.Write("User Found " + user.ProviderUserKey.ToString())
Else
      Response.Write("User Not Found")
End If

Note: Let me know what is displayed when you run the code.
This is the subltest test, which if performed as directed, should help to diagonse the issue.
You Did It!

I have a separate master page that gets launched when a user gets logged in, so I put the code below in the master pages load event and it WORKED!!!!

Thank you, Thank you, Thank you

You have been so patient and I really appreciate your help.

Sheri
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            If My.User.IsAuthenticated Then
                Dim u As New SalonUtilities
                u.SetUserIDSession()
                'Response.Redirect("Stylist/Setup.aspx")
            End If
        End If
    End Sub

Open in new window

Very helpful and very patient.

Thanks again