0

I am using below code for update SharePoint user profile

try
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
      {

        HttpContext con = HttpContext.Current;
        SPSite tempSite = new SPSite(SPContext.Current.Site.Url);
        SPUserToken superToken = tempSite.SystemAccount.UserToken;
        string sAccount = string.Empty;
        UserProfile profile = null;
        using (SPSite site = new SPSite(SPContext.Current.Site.Url, superToken))
        {
            SPWeb web = site.OpenWeb();

            web.AllowUnsafeUpdates = true;
            SPServiceContext context = SPServiceContext.GetContext(site);
            HttpContext.Current = null;
            UserProfileManager profileManager = new UserProfileManager(context);
            SPUser NewUser = web.EnsureUser(spuser);
            sAccount = NewUser.LoginName;
            if (!profileManager.UserExists(sAccount))
            {
                profile = profileManager.CreateUserProfile(sAccount);
            }
            else
            {
                profile = profileManager.GetUserProfile(sAccount);
            }
            web.AllowUnsafeUpdates = false;
        }
        // profile["AccountName"].Value = createusert1.UserName;
        profile["FirstName"].Value = "Test";                    
        profile.Commit();

        });
}
catch (Exception ex) {}

This code works perfect and save data in user profile but after complete this code execution error come in browser object reference not set to an instance of an object.

Why its happening? Any idea? It comes for any user update his own profile also. No error in code but error in browser.

2 Answers 2

3

Your code set HttpContext.Current = null;, but do not restore it, use try-finally approach:

HttpContext con = null;
try{
  con = HttpContext.Current;
  ......
}
catch(Exception ex){}
finally{
   HttpContext.Current = con;
}

And also, this code

SPSite tempSite = new SPSite(SPContext.Current.Site.Url);

leads to memory leaks, why not to use simply

SPContext.Current.Site.SystemAccount.UserToken;
0
0

You can validate this using the Powershell as mentioned below.

Set-SPUser -Identity ‘Domain\userid’ -DisplayName ‘test’ –Web http://yoursitecollection

After you run this script will notice the display changes for the selected AD user. However post completion of the script, you will get an object not found shown in the powershell window.

Try this after you have run the above script and notice the changes to the user property.

Set-SPUser -Identity ‘domain\userid’ –Web http://yoursitecollection –SyncFromAD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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