Recently I wrote a web part using the WSPBuilder Visual Studio add-ins. I wanted to deploy it to the BIN directory and not have to elevate the trust level of my farm, so I was going to have to write a Code Access Security Policy (CAS Policy).
Others have written good descriptions of what CAS Policy is (here is a good description by Bamboo), but the short description is that it tells your application (SharePoint) to give certain additional rights to an assembly (in our case, the web part). These rights are things like being able to access the disc, the network, or even the SharePoint Object Model!
Yup, that’s right – under default Code Access Security, my assembly wouldn’t even be able to access the SharePoint APIs.
Anyway, I started looking into I’d have to do to add a policy. Basically, it’s a lump of XML that goes in the Manifest file of your WSP. Conveniently, I discovered, WSPBuilder automatically performs reflection on my assembly, and generates a CAS Policy by itself:
If you open that image up, what you’ll see is a set of permissions being defined, and then at the bottom the assemblies (just the one in my case) that those assemblies apply to.
I was surprised that my automatic CAS policy contained rights for things like File IO, SMTP and SQL Client – but my web part uses the SharePoint object model, and that probably uses all those rights.
So, an automatically generated CAS Policy – nice, neat! It didn’t work. I kept getting an error that my web part didn’t have the Microsoft.SharePoint.Security.SharePointPermission.
Well, for some reason the reflection that generated the CAS Policy came back with the wrong description for that permission. It used just ‘SharePointPermission’, but the CAS Policy needs the full strong name.
On looking at WSPBuilder I found that I could specify my own file containing additional permissions:
WSPBuilder.exe -WSPName CreateNewDocumentWebPart.wsp -CustomCAS CasPolicy.txt
That file contained a declaration of a classes that implement the IPermission interface. This include the SharePointPermission using the full strong name:
(There are others here; I was experimenting)
WSPBuilder then created the Manifest file with my permissions:
And that worked; all my permissions exceptions went away. My web part worked without elevating trust for my entire farm, or putting my assembly in the GAC (which gives the whole assembly Full Trust).
Kudos to @Einaros for pointing me toward the right declaration for the Microsoft.SharePoint.Security.SharePointPermission