Posted by Adam Buenz
I had to write a small method this morning that would allow me to test whether an SPUser object was a member of an arbitrary SPGroup. Particularly, I needed a way to do this in an event receiver, which is why you see a reference to the properties parameter representative of the SPItemEventProperties when getting a reference to the relevant item and list objects. I wanted to do this basically:
C#:
-
SPUser curUser = web.CurrentUser;
-
-
SPGroup testGroup = properties.ListItem.Web.Groups["Home Visitors"];
-
string groupName = testGroup.Name;
-
if (bIsInGroup(curUser, groupName))
-
{
-
-
-
}
Then to use this boolean test, I simply just used this method:
C#:
-
private bool bIsInGroup(SPUser user, string strname)
-
{
-
try
-
{
-
foreach (SPGroup group in user.Groups)
-
{
-
if (group.Name == strname)
-
return true;
-
}
-
}
-
catch (Exception exception)
-
{
-
WriteLogEvent(string.Format("An Error Occured | Exception Message:{0} StackTrace: {1}", exception.Message, exception.StackTrace));
-
}
-
return false;
-
}
And just using the traditional way of writing errors to the event log:
C#:
-
public void WriteLogEvent(string strmessage)
-
{
-
// Create a new event comLog object
-
-
// Check whether the event comLog source already exists
-
if (!EventLog.SourceExists("test"))
-
EventLog.CreateEventSource("test", "Application");
-
-
// Specify the source for the exception message
-
comLog.Source = "test";
-
// Write the entry to the event comLog
-
comLog.WriteEntry(strmessage);
-
}











August 8th, 2007 at 1:08 am
Hi Adam,
I've looked into this too at the following article: http://chrissyblanco.blogspot.com/2007/07/determining-whether-user-is-member-of.html
I looked at doing it your way i.e iterating the Groups collection of the SPUser object, however this didn't appear to work for the following scenario:
Say you have a user who is a member of an AD group e.g. ADGroupX. You then add ADGroupX to a SharePoint group (SPGroup), say SharePointGroupY.
If you iterate the Groups collection of the SPUser object for the user who is a member of ADGroupX then SharePointGroupY is not one of the SPUser.Groups . . .
Have you seen this issue too ?!
Many thanks,
Chris