The code works. There is no error.
Please let me know if this is the best practice to read/write to the user profile property in SharePoint 2013.
Read:
string currentUser = SPContext.Current.Web.CurrentUser.LoginName;
SPSite spSite = SPContext.Current.Site;
try
{
// Set the context of the site to the SPSite site
SPServiceContext context = SPServiceContext.GetContext(spSite);
//Create and instance of the UserProfileManager
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile userProfile = profileManager.GetUserProfile(currentUser);
string customValue=userProfile["customPropertyName"].Value.ToString();
}
Write:
string currentUser = SPContext.Current.Web.CurrentUser.LoginName;
SPSite spSite = SPContext.Current.Site;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = null;
try
{
// Set the context of the site to the SPSite site
SPServiceContext context = SPServiceContext.GetContext(spSite);
//Create and instance of the UserProfileManager
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile userProfile = profileManager.GetUserProfile(currentUser);
userProfile["customPropertyName"].Value = "True";
userProfile.Commit();
}
finally
{
System.Web.HttpContext.Current = currentContext;
}
});
Do I have to use for read also the below code as used in case of write?
before try
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = null;
in finally:
System.Web.HttpContext.Current = currentContext;
Why is it that we have to do like this for the write?