SharePoint Web Part Constructor Fires Twice When Adding it to the Page (and has a different security
- by Damon
We had some exciting times debugging an interesting issue with SharePoint 2007 Web Parts. We had some code in staging that had been running just fine for weeks and had not been touched or changed in about the same amount of time. However, when we tried to move the web part into a different staging environment, the part started throwing a security exception when we tried to add it to a page. After a bit of debugging, we determined that the web part was throwing the exception while trying to access the SPGroups property on the SharePoint site. This was pretty strange because we were logged in as an admin and the code was working perfectly fine before. During the debugging process, however, we found out that the web part constructor was being fired twice. On one request, the security context did not seem to have everything it needed in order to run. On the other request, the security context was populated with the user context with the user making the request (like it normally is). Moving the security code outside of the constructor seems to have fixed the issue. Why the discrepancy between the two staging environments? Turns out we deployed the part originally, then deployed an update with the security code. Since the part was never "added" to the page after the code updates were made (we just deployed a new assembly to make the updates), we never saw the problem. It seems as though the constructor fires twice when you are adding the web part to the page, and when you run the web part from the web part gallery. My only thought on why this would occur is that SharePoint is instantiating an instance to get some information from it - which is odd because you would think that would happen with reflection without requiring a new object. Anyway, the work around is to just not put anything security related inside the constructor, or to do a good job accounting for the possibility of the security context not being present if you are adding the item to the page. Technorati Tags: SharePoint,.NET,Microsoft,ASP.NET