Search code examples
c#sharepoint-2013web-parts

InvalidProgramException throws on Microsoft.Office.Server.UserProfiles.UserProfileManager


I am making a webpart that needs to fetch the current user information from active directory using below code:

protected void fetchUserInfo()
{
    System.Security.PermissionSet ps = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
    ps.Assert();

    Microsoft.SharePoint.SPServiceContext serviceContext = Microsoft.SharePoint.SPServiceContext.Current;
    UserProfileManager upm = new Microsoft.Office.Server.UserProfiles.UserProfileManager(serviceContext);
    ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;
    string userName = SPContext.Current.Web.CurrentUser.LoginName;
    UserProfile profile = upm.GetUserProfile(userName);

    foreach (ProfileSubtypeProperty prop in pspm.PropertiesWithSection)
    {
    }
}

However an InvalidProgramException throws on line ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;

The error message is:

Common Language Runtime detected an invalid program.

I tried googling Common Language Runtime detected an invalid program. sharepointUserProfileManager but there aren't much info.

What could be the problem?


Just now saw that the exception flows on UserProfileManager, so the SPServiceContext isn't valid, and when I look at the property SiteSubscriptionId on serviceContext, I found it was 00000000-0000-0000-0000-000000000000

So what does it mean? is there any alternative way to get the current user info from sharepoint?


Solution

  • At last, I changed my mind using UserPrincipal to get the user info:

        PrincipalContext _principalcontext = GetPrincipalContext();
        UserPrincipal _user = UserPrincipal.FindByIdentity(_principalcontext, IdentityType.SamAccountName, UID);
    
        if (_user != null)
        {
            DirectoryEntry directoryEntry = _user.GetUnderlyingObject() as DirectoryEntry;
            //Property is here;
        }