Friday, April 20, 2012

code to check logged in user exist in provided Active Directory (AD) group or not

using Microsoft.SharePoint.Utilities;

///
/// Method to check if logged in user exists in provided AD group or not.
///

/// AD group Name
///
public bool isMemberOfGroup(string strGroupName)
{
bool reachedMaxCount;
int limit = 100;
string strUserDispName = null;
bool returnValue = false;

if (SPContext.Current != null)
{
string strCurUserName = SPContext.Current.Web.CurrentUser.LoginName;
string URL = SPContext.Current.Site.Url;

SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite mySite = new SPSite(URL))
{
using (SPWeb sPCurrentWeb = mySite.OpenWeb())
{
SPPrincipalInfo[] users = SPUtility.GetPrincipalsInGroup(sPCurrentWeb, strGroupName, limit, out reachedMaxCount);

if (users != null)
{
foreach (SPPrincipalInfo user in users)
{
strUserDispName = user.LoginName;

if (string.Equals(strCurUserName, strUserDispName, StringComparison.OrdinalIgnoreCase))
{
returnValue = true;
break;
}

}
}
}
}
});
}

return returnValue;
}

No comments:

Post a Comment