Monday, 22 September 2008

Is the current SPUser a colleague?

I had an SPItem in a list, and I wanted to know: Is the creater of the item a colleague with the current user?

After surfing around on the internet, I came to a solution where I use UserProfile's.
I can get the loggedIn- and Current-UserProfiles Guid and check whether they are colleagues.

// Get Site and Web.
SPSite currentSPSite = SPControl.GetContextSite(Control.Context);
SPWeb currentSPWeb = currentSPSite.RootWeb;

// Loop through SiteUserInfoList
foreach (SPItem currentSPItem in currentSPWeb.SiteUserInfoList.Items)
string createdBy = currentSPItem["Created By"].ToString();
int index = createdBy.IndexOf(';');
int id = Int32.Parse(userValue.Substring(0, index));
SPUser currentSPUser = currentSPWeb.SiteUsers.GetByID(id);

// ServerContext provides run-time methods for shared services in Microsoft Office SharePoint Server 2007.
ServerContext serverContext = ServerContext.GetContext(currentSPSite);
// UserProfileManager is a collection of UserProfile objects.
UserProfileManager userProfileManager = new UserProfileManager(serverContext);

// The current UserProfile for the current item
UserProfile currentUserProfile = userProfileManager.GetUserProfile(currentSPUser.LoginName);
// The current UserProfile for the logged in user
UserProfile loggedInUserProfile = userProfileManager.GetUserProfile(currentSPWeb.CurrentUser.LoginName);

// Is the currentUserProfile a colleague with the loggedInUserProfile
if (currentUserProfile.Colleagues.IsColleague(loggedInUserProfile.ID))
Code here...

No comments: