I think every developer experiences a moment in his career that he is pretty sure his code is correct, but it isn’t. There is a problem without any doubt, but although he looks a thousand times at his code, he can’t find it. Eventually he starts to doubt himself and after a lot of sweat, coffees, no-sleep, grrrrs, help-me-please, he suddenly yells very loud. Everyone is looking and wondering which pills he forgot to take this morning and the only thing you have is a very big smile on your face and red cheeks. And yes, you can guess it probably, I experienced that this week!
The case (ripped to the bottom) was very simple. I had to create a new Site Collection, add a group to this new Site Collection and update some properties of this new group. Simple isn’t it? Let me paste the code I wrote for this and probably everyone sees the problem immediately. Only thing I have as input was an url to a Site Collection, an url, a title and an owner for the new Site Collection and a name for the new Group.
Dim site As SPSite = New SPSite(siteUrl)
Dim webApp As SPWebApplication = site.WebApplication
Dim newSite As SPSite = webApp.Sites.Add(newSiteUrl, newSiteTitle, Nothing, 1033, newSiteOwner, Nothing, Nothing)
Dim newWeb As SPWeb = newSite.RootWeb()
newWeb.SiteGroups.Add(newGroupName, site.Owner, Nothing, Nothing)
Dim newGroup As SPGroup = newWeb.SiteGroups(newGroupName)
You see it? Let’s hope you don’t, otherwise I feel really stupid
On the last line, you get a nice exception, Group cannot be found. Unless, and here is the fun part, your site.Owner is the same account as who is running your Web Application (in other words the account running the Application Pool for your Web Site in IIS).
So you have a workaround and a real problem to tackle. If you know what, it is simple. Don’t use SPUser objects from other Site Collections to do things! You see the problem now? For those who don’t, replace site.Owner (an SPUser object from another Site Collection) with newSite.Owner and everything is solved. Stupid I looked over this and didn’t realised this could be a potential problem, but lesson learned as they say.