Responsive Ads Here

Tuesday, July 17, 2012

Check User is a member of certain group or not in SharePoint

In my recent project, i have a requirement to check the current user is member of a particular group or not, based upon group member or not i need to redirect the user to corresponding page.

For this we need to use IsCurrentUserMemeberOfGroup method. Return value of this method is Boolean. Basically this method will present in SPWeb class which can takes the input parameter as group id and check whether current user is a member of group or not. If the return value is true then the current user is member of the group otherwise false.

Please find the below code snippet which will gives a complete idea.


using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
{
    using (SPWeb spWeb = oSite.OpenWeb())
    {
 //To do : Check the group existence before checking the user is member in group
        bool isMember = spWeb.IsCurrentUserMemberOfGroup(spWeb.Groups["samplegroup"].ID);
    }
}

In the above code snippet, basically i am getting the current context of site and i am checking the current user is a member of group or not in samplegroup. It will return the Boolean value. In the above method i am not checking the group existence, Because i know that samplegroup present in root web. If group is not present the above method will throw an exception, so checking the group name is better coding standard. Below methods will give a clear idea how to check group existence in site.

//Check if a group exists in a website
var groupInWeb = GroupExistsInWebSite(SPContext.Current.Web, "MyGroupName");

//Check if a group exists in a site collection
var groupInSite = GroupExistsInSiteCollection(SPContext.Current.Web, "MyGroupName");

private  bool GroupExistsInWebSite(SPWeb web, string name)
{
    return web.Groups.OfType<SPGroup>().Count(g => g.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) > 0;
}
private bool GroupExistsInSiteCollection(SPWeb web, string name)
{
    return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) > 0;
}

I hope this post will be useful..

No comments:

Post a Comment