Wednesday, January 6, 2010

Check Usergroups of Sharepoint

//Check whether the currently logged in user is in a specific role
public bool IsCurrentUserInRole(string role)
{
bool inRole = false;
using (SPSite site = new SPSite(strSiteCollectionURL))
{
using (SPWeb rootWeb = site.OpenWeb())
{
SPRole spRole = rootWeb.Roles[role];
SPUser currentUser = rootWeb.CurrentUser;
foreach (SPUser roleUser in spRole.Users)
{
if (roleUser.ID.Equals(currentUser.ID))
{
inRole = true;
break;
}
}

return inRole;

}
}

}


//Check whether the currently logged in user is a member of a specific group
public bool IsCurrentUserInGroup(string group)
{
bool inGroup = false;
using (SPSite siteCollection = new SPSite(strSiteCollectionURL))
{
using (SPWeb rootWeb = siteCollection.OpenWeb())
{
SPUser currentUser = rootWeb.CurrentUser;
SPGroup spGroup = rootWeb.Groups[group];

foreach (SPUser groupUser in spGroup.Users)
{
if (groupUser.ID.Equals(currentUser.ID))
{
inGroup = true;
break;
}
}
siteCollection.Dispose();
rootWeb.Dispose();
return inGroup;
}
}

}



public Hashtable GetUserGroupsForCurrentUser()
{

using (SPSite site = new SPSite(strSiteCollectionURL))
{
using (SPWeb web = site.OpenWeb(strCurrentSiteURL))
{

SPUser user = web.CurrentUser;

SPGroupCollection grpColl = user.Groups;


Hashtable htgetusergroups = new Hashtable();
int igroup = 0;

//Iterate through the SPGroupCollection to see which group(s)
//the user belongs to and add the group names to the hashtable accordingly.
foreach (SPGroup group in grpColl)
{
htgetusergroups.Add(igroup, group.Name);
igroup = igroup + 1;

}

return htgetusergroups;

}

}


}

//Returns a hashtable, if the currently logged in user is a
//member of more than one group
public Hashtable GetUserGroups(SPUser user)
{


using (SPSite siteCollection = new SPSite(strSiteCollectionURL))
{
using (SPWeb web = siteCollection.OpenWeb())
{
Hashtable htgetusergroups = new Hashtable();
user = web.CurrentUser;
SPGroupCollection grpColl = user.Groups;

int igroup = 0;

//Iterate through the SPGroupCollection to see which group(s)
//the user belongs to and add the group names to the hashtable accordingly.
foreach (SPGroup group in grpColl)
{
htgetusergroups.Add(igroup, group.Name);
igroup = igroup + 1;

}
// BDX-798 start
if (htgetusergroups.Count == 0)
{
htgetusergroups.Add(igroup, strBDXVistor);
}
// BDX-798 End
return htgetusergroups;

}
}

}


//Returns the current user
public SPUser GetCurrentUser()
{
using (SPSite siteCollection = new SPSite(strSiteCollectionURL))
{
using (SPWeb web = siteCollection.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
siteCollection.Dispose();
return currentUser;
}
}

}

No comments: