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

dinsdag 25 mei 2010

Debugging Powershell Cmdlets V2

As I was trying to debug my custom powershell commandlets through visual studio I had the problem that it was not hitting the breakpoints automatically when running through F5.

The trick is to create a powershell.exe.cfg in your PowerShell folder (C:\Windows\System32\WindowsPowerShell\v1.0):

<?xml version="1.0"?>
  <startup useLegacyV2RuntimeActivationPolicy="true">
   <supportedRuntime version="v2.0.50727"/>

The other steps to follow are still quite the same as Bart De Smet has explained in his blogpost here: http://bartdesmet.net/blogs/bart/archive/2008/02/03/easy-windows-powershell-cmdlet-development-and-debugging.aspx

Some things I did differently are setting post build events like this:

@SET GACUTIL="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\gacutil.exe"
@SET INSTALLUTIL="C:\Windows\Microsoft.NET\Framework64\v2.0.50727\installutil.exe"

%GACUTIL% -if Shaks.PowerShell.SharePoint.Cmdlets
%INSTALLUTIL% -i Shaks.PowerShell.SharePoint.Cmdlets.dll

In the Debug-tab of the project properties I start an external program (powershell.exe) with the following attributes:

-PSConsoleFile Shaks.PowerShell.SharePoint.Cmdlets.psc1  -noexit

I’ll post my psc1 file here for reference, although you can just generate this:

<?xml version="1.0" encoding="utf-8"?>
<PSConsoleFile ConsoleSchemaVersion="1.0">
    <PSSnapIn Name="shaks.powershell.sharepoint.cmdlets" />

The commandlet itself will be for a next blogpost.