Question

I have created a Custom Web Service for my .NET application that performs various functions against a Sharepoint 2010 site. I use a standard function to run each function as an impersonated user (so there is a parameter for each function that states the user acct under which to run the function).

My problem is that when I go to pull up this account (using the code below), I keep getting a SPException: User cannot be found, despite specifically creating those accounts on the site (because the user sync service is a miserable failure)

So, can someone explain to me how I fix this? I am running this service under the local administrator account, and the accounts exist on the site (honest), but still, it cannot find it.

see below:

Private Function GetToken(ByVal p_strURL As String, ByVal p_strUser As String, ByRef p_strTokenError As String) As Byte()

    Dim objImpersonateSite As SPSite = nothing
    Dim objSPUser As SPUser = Nothing
    Dim w As SPWeb = Nothing
    Dim objToken As SPUserToken = nothing
    Dim bytArr() As Byte

    Try

        'Open my site (I should be admin @ this point)
        objImpersonateSite = New SPSite(p_strURL)

        w = objImpersonateSite.OpenWeb()

        'Figure out my user request param -- usually: DOMAIN\Username
        If InStr(p_strUser, "@") > 0 And InStr(p_strUser, ".") > 0 Then
            objSPUser = w.Users.GetByEmail(p_strUser)
        ElseIf IsNumeric(p_strUser) = True Then
            objSPUser = w.Users.GetByID(CInt(Val(p_strUser)))
        Else
            objSPUser = w.Users(p_strUser)
        End If

        'Check for an actual found acct
        If Not objSPUser Is Nothing Then
            objToken = objSPUser.UserToken
            bytArr = objToken.BinaryToken

            'Return the token
            GetToken = bytArr
        End If


    Catch ex As Exception
        'Pass back the error
        p_strTokenError = ex.ToString
    Finally

    End Try
End Function
Was it helpful?

Solution

SPWeb.Users.GetByEmail() and SPWeb.Users.GetById() is only going to return the users that have logged in to your site. Try the method SPWeb.EnsureUser(). MSDN says the following:

Checks whether the specified logon name belongs to a valid user of the website, and if the logon name does not already exist, adds it to the website.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top