Link to home
Start Free TrialLog in
Avatar of M.L. Martin
M.L. MartinFlag for United States of America

asked on

ASP.Net Identity and Accessing currently logged in user (ASP.Net 4.6

I have begun using ASPNet Ientity in ASP.Net 4.6. There are some differences when attempting to get the currently logged in user. The following code get the logged in user and assigns to a textbox called UserId. It assigns the UserName to the Textbox instead of UserId but that is fine for now.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If (User.Identity.IsAuthenticated) Then

            UserId.Text = User.Identity.Name
        End If

    End Sub

My problem is the old Member Provider code I was using before to insert the currently logged in User with the other records. I do not know why this will not work anymore but I am sure that it is not the correct syntax to work with the new ASP.Net Identity Membership Provider.

Dim MemUser As MembershipUser
        MemUser = Membership.GetUser()
        UserId.Text = MemUser.ProviderUserKey.ToString()

I do not know how but I feel the Syntax is incorrect now. I am hoping someone can tell me the correct way to do this with the new ASPNet Identity. I know a lot of folks are not using this version yet but I hope someone can help. The entire code behind page is below. Everything works except I am not able to submit the currently logged in user. Again, I am able to assign the logged in user to a textbox. I am just missing the other components.

----------------------------------------------------------------------------------------
Imports System.Data.SqlClient
Imports Microsoft.AspNet.Identity

Public Class member1001glf1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If (User.Identity.IsAuthenticated) Then

            UserId.Text = User.Identity.Name
        End If

    End Sub

    Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Before attempting to save the file, verify
        ' that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then
            'Check the file size
            If (FileUpload1.PostedFile.ContentLength < 88100000) Then
                'Call a helper method routine to save the file.
                SaveFile(FileUpload1.PostedFile)
            Else
                'Notify the User
                UploadStatusLabel.Text = "File exceeds limit of 8 MB"
            End If
        Else
            ' Notify the user that a file was Not uploaded.
            UploadStatusLabel.Text = "You did not specify a file To upload."
        End If
    End Sub
    Sub SaveFile(ByVal file As HttpPostedFile)

        ' Specify the path to save the uploaded file to.
        Dim savePath As String = HttpContext.Current.Server.MapPath("memuploads\")

        ' Get the name of the file to upload.
        Dim fileName As String = FileUpload1.FileName

        ' Create the path and file name to check for duplicates.
        Dim pathToCheck As String = savePath + fileName

        ' Create a temporary file name to use for checking duplicates.
        Dim tempfileName As String

        ' Check to see if a file already exists with the
        ' same name as the file to upload.        
        If (System.IO.File.Exists(pathToCheck)) Then
            Dim counter As Integer = 2
            While (System.IO.File.Exists(pathToCheck))
                ' If a file with this name already exists,
                ' prefix the filename with a number.
                tempfileName = counter.ToString() + fileName
                pathToCheck = savePath + tempfileName
                counter = counter + 1
            End While

            fileName = tempfileName

            ' Notify the user that the file name was changed.
            UploadStatusLabel.Text = "A file with the same name already exists." + "<br />" +
                                     "Your file was saved as " + fileName

        Else

            ' Notify the user that the file was saved successfully.
            UploadStatusLabel.Text = "Your file was uploaded successfully."

        End If

        ' Append the name of the file to upload to the path.
        savePath += fileName

        ' Call the SaveAs method to save the uploaded
        ' file to the specified directory.
        FileUpload1.SaveAs(savePath)



        Dim MemUser As MembershipUser
        MemUser = Membership.GetUser()
        UserId.Text = MemUser.ProviderUserKey.ToString()

        Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        Dim con As New SqlConnection(strConnString)
        Dim strQuery As String = "insert into tblFiles (UserId, savedfor, performedby, searchcode, exercisename, bodypartmg, bodypartspecific, description, FileName, FilePath) values(@UserId, @savedfor, @performedby, @searchcode, @exercisename, @bodypartmg, @bodypartspecific, @description, @FileName, @FilePath)"
        Dim cmd As New SqlCommand(strQuery)
        cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = MemUser.ProviderUserKey.ToString()
        cmd.Parameters.Add("@SavedFor", SqlDbType.VarChar).Value = savedfor.Text
        cmd.Parameters.Add("@performedby", SqlDbType.VarChar).Value = performedby.Text
        cmd.Parameters.Add("@searchcode", SqlDbType.VarChar).Value = searchcode.Text
        cmd.Parameters.Add("@exercisename", SqlDbType.VarChar).Value = exercisename.Text
        cmd.Parameters.Add("@bodypartmg", SqlDbType.VarChar).Value = bodypartmg.Text
        cmd.Parameters.Add("@bodypartspecific", SqlDbType.VarChar).Value = bodypartspecific.Text
        cmd.Parameters.Add("@description", SqlDbType.VarChar).Value = description.Text
        cmd.Parameters.AddWithValue("@FileName", fileName)
        cmd.Parameters.AddWithValue("@FilePath", "memuploads\" & fileName)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            Response.Write(ex.Message)
        Finally
            con.Close()
            con.Dispose()
        End Try

    End Sub

End Class
Avatar of M.L. Martin
M.L. Martin
Flag of United States of America image

ASKER

The following is the error I receive:


Default Membership Provider must be specified.
  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.Configuration.Provider.ProviderException: Default Membership Provider must be specified.

Source Error:



Line 90:
Line 91:
Line 92:         Dim MemUser As MembershipUser
Line 93:         MemUser = Membership.GetUser()
Line 94:         UserId.Text = MemUser.ProviderUserKey.ToString()
ASKER CERTIFIED SOLUTION
Avatar of Mlanda T
Mlanda T
Flag of South Africa 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
SOLUTION
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
MlandaT, I agree I should not mix the two. Believe be, I am not a good enough coder to do that even if I wanted to. Can you show me the exact way I should use System.Web.HttpContext.Current.User.Identity.GetUserId() in the code behind. I assume I would place it in a Page Load event!

Also, would I still need the following? If so what would be the correct syntax?
Dim MemUser As MembershipUser
        MemUser = Membership.GetUser()
        UserId.Text = MemUser.ProviderUserKey.ToString()

Last question....if I use System.Web.HttpContext.Current.User.Identity.GetUserId() does my insert code change or would I use it the same way. It appears that if I use System.Web.HttpContext.Current.User.Identity.GetUserId() I will not have to assign the value to a text field to do an insert. Is that correct?
I will try to get help here again. I am simply trying to get the current logged in using why using ASPNet Identity. I am uploading a file and I want to write the value of the logged user submitting the file in a table field named UserId.

I Understand I need the following.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        HttpContext.Current.User.Identity.GetUserId()

    End Sub

To insert the current logged user do I need to assign the value to a textbox like the following? If I do is the syntax correct. If it is not please submit the correct code.:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        HttpContext.Current.User.Identity.GetUserId()

        If (User.Identity.IsAuthenticated) Then

            UserId.Text = User.Identity.Name
        End If

    End Sub


Lastly...If I am to use the above do I still need the following? If it is different can you please submit the needed code. My hope is that I no longer need to assign the UserId value to a Textbox but I am looking for the correct way to do this:

Dim MemUser As MembershipUser
        MemUser = Membership.GetUser()
        UserId.Text = MemUser.ProviderUserKey.ToString()

        Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        Dim con As New SqlConnection(strConnString)
        Dim strQuery As String = "insert into tblFiles (UserId, savedfor, performedby, searchcode, exercisename, bodypartmg, bodypartspecific, description, FileName, FilePath) values(@UserId, @savedfor, @performedby, @searchcode, @exercisename, @bodypartmg, @bodypartspecific, @description, @FileName, @FilePath)"
        Dim cmd As New SqlCommand(strQuery)
        cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = MemUser.ProviderUserKey.ToString()
I am now trying the following?

Dim MemUser As MembershipUser = Membership.GetUser(User.Identity.GetUserId)
        'MemUser = Membership.GetUser()
        'UserId.Text = MemUser.ProviderUserKey.ToString()

        Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
        Dim con As New SqlConnection(strConnString)
        Dim strQuery As String = "insert into tblFiles (UserId, savedfor, performedby, searchcode, exercisename, bodypartmg, bodypartspecific, description, FileName, FilePath) values(@UserId, @savedfor, @performedby, @searchcode, @exercisename, @bodypartmg, @bodypartspecific, @description, @FileName, @FilePath)"
        Dim cmd As New SqlCommand(strQuery)
        cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = User.Identity.Name
        cmd.Parameters.Add("@SavedFor", SqlDbType.VarChar).Value = savedfor.Text

But I get the following error


Default Membership Provider must be specified.
  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.Configuration.Provider.ProviderException: Default Membership Provider must be specified.

Source Error:



Line 83:
Line 84:
Line 85:         Dim MemUser As MembershipUser = Membership.GetUser(User.Identity.GetUserId)
Line 86:         'MemUser = Membership.GetUser()
Line 87:         'UserId.Text = MemUser.ProviderUserKey.ToString()
 

 Source File:  C:\Users\dmartin\documents\visual studio 2015\Projects\MyFitnessMyLife\MyFitnessMyLife\member1001glf.aspx.vb    Line:  85
MLandaT I have added Imports Microsoft.AspNet.Identity. I have the Membership ID. It is displaying in the textbox with no problem. The membership id is displaying without any issues. My problem is trying to insert the membershipid into a table.

Imports System.Data.SqlClient
Imports Microsoft.AspNet.Identity
Imports System.Web

Public Class member1001glf1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        HttpContext.Current.User.Identity.GetUserId()

        If (User.Identity.IsAuthenticated) Then

            UserId.Text = User.Identity.GetUserId
        End If

    End Sub

------------------------------------------------------------------------------------

When I click the upload button I get an error on the following code:
Dim MemUser As MembershipUser = Membership.GetUser(User.Identity.GetUserId)
        'MemUser = Membership.GetUser()
        'UserId.Text = MemUser.ProviderUserKey.ToString()

Error:

Server Error in '/' Application.

Default Membership Provider must be specified.
  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.Configuration.Provider.ProviderException: Default Membership Provider must be specified.

Source Error:



Line 83:
Line 84:
Line 85:         Dim MemUser As MembershipUser = Membership.GetUser(User.Identity.GetUserId)
Line 86:         'MemUser = Membership.GetUser()
Line 87:         'UserId.Text = MemUser.ProviderUserKey.ToString()
 

 Source File:  C:\Users\dmartin\documents\visual studio 2015\Projects\MyFitnessMyLife\MyFitnessMyLife\member1001glf.aspx.vb    Line:  85
I feel I am a step closer. I do not get errors now but I am not inserting the Logged In User's UserID. All of the other inserts work fine.

This is what is inserted for the UserId field instead of the UserId:

System.Security.Claims.ClaimsIdentity

This is what I have now.



Imports System.Data.SqlClient
Imports Microsoft.AspNet.Identity
Imports System.Web

Public Class member1001glf1
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UserId As String

HttpContext.Current.User.Identity.GetUserId()

If (User.Identity.IsAuthenticated) Then

UserId = User.Identity.GetUserId.ToString
End If

End Sub



Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim strQuery As String = "insert into tblFiles (UserId, savedfor, performedby, searchcode, exercisename, bodypartmg, bodypartspecific, description, FileName, FilePath) values(@UserId, @savedfor, @performedby, @searchcode, @exercisename, @bodypartmg, @bodypartspecific, @description, @FileName, @FilePath)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = User.Identity.ToString
cmd.Parameters.Add("@SavedFor", SqlDbType.VarChar).Value = savedfor.Text
cmd.Parameters.Add("@performedby", SqlDbType.VarChar).Value = performedby.Text
Final Solution Reached:

This works
Imports System.Data.SqlClient
Imports Microsoft.AspNet.Identity
Imports System.Web

Public Class member1001glf1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim UserId As String

        HttpContext.Current.User.Identity.GetUserId()

        If (User.Identity.IsAuthenticated) Then

            UserId = User.Identity.GetUserId.ToString
        End If

    End Sub

------------------------------------------------------
Imports System.Data.SqlClient
Imports Microsoft.AspNet.Identity
Imports System.Web

Public Class member1001glf1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim UserId As String

        HttpContext.Current.User.Identity.GetUserId()

        If (User.Identity.IsAuthenticated) Then

            UserId = User.Identity.GetUserId.ToString
        End If

    End Sub