I recently wrote a feature that was to be activated on a custom site definition. I believe this is called Feature Stapling. I could be wrong. Either post will show you the funny thing I found when trying to delete the groups in sharepoint, that were the custom groups that were created as part of the site definition. What I wanted to do was to create a new site based on the site definition and then do a little house cleaning to set a master page, a css and clean out the groups that were created and create my own.
First I tried this,
for (int i = 0; i < site.RootWeb.SiteGroups.Count; i++)
{
site.RootWeb.SiteGroups.Remove(i);
}
for (int i = 0; i < site.RootWeb.Groups.Count; i++)
{
site.RootWeb.Groups.Remove(i);
}
THe problem with this is that groups are not indexed from location 0 to N.
So then I tried this,
foreach (Spgroup group in site.RootWeb.SiteGroups){
site.RootWeb.SiteGroups.RemoveByID(group.ID);
}
THis seems like it would work, but it doesn't. Instead of removing by index, I now used "RemoveByID" and sent in the ID as the parameter. The problem was that once the group was being removed, it effected the enumeration of the 'foreach' loop.
in order to delete the groups you have to store the id's and then remove the groups by id. Like the following.
List<int> sitegroupids = new List<int>();
foreach (SPGroup group in site.RootWeb.SiteGroups)
{
sitegroupids.Add(group.ID);
}
foreach (int id in sitegroupids) { web.SiteGroups.RemoveByID(id); }
and that's the way it's done! Just thought it was interesting enought mention and blog about it.