woensdag 14 juli 2010

SecurityException in WebParts when making SharePoint API calls

Latest webpart I made I had strange problems with the following lines of code:

SPWeb rootWeb = SPContext.Current.Site.RootWeb; 
string siteInfoUnserialized = rootWeb.Properties[Constants.SOMEKEY]; // SecurityException here

Even though I was logged in as System Administrator this exception got thrown. This error is very likely to happen due to a lack of a good nights rest, resulting in placing code in the constructor (I still can’t remember why I did that).

Placing the API code inside the OnInit function (or similar) solves the problem. The cause is that during the constructor call not everything is initialized properly.

Other possible causes (not applicable for me) are that the CAS file is not correct thus not having enough rights or the webpart dll is not in the GAC (if you do it this way, Microsoft recommends bin deployment with CAS policies)

Reference to a deeper blogpost about this by Robert Bogue: http://www.thorprojects.com/blog/archive/2008/04/16/web-part-event-firings-and-why-you-shouldn%E2%80%99t-have-code-in-the-constructor.aspx