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


        '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)))
            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

    End Try
End Function

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.

  • So Would I call this before calling for the token then??
    – Andrew
    Jun 29 '11 at 19:01
  • Yes. This method will return an SPUser object. Unfortunately, you'll need to pass in domain\username, and not email address. Jun 29 '11 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.