Unable to cast COM object of type Microsoft.SharePoint.Library.SPRequestInternalClass to interface type Microsoft.SharePoint.Library.ISPRequest

Posted on

Well, out there, there is many people with this problem and to all of them the solution is different because they face this problem in different scenarios.
I read some face it in webparts, some in custom templates, some in powershell, etc.

I faced it in something really simple and its creating list columns via powershell, but I am using an application called PowerGUI.

This was my code:

param([string]$webAppUrl)
$site = SPSite($webAppUrl)
$web = $site.RootWeb
$spList = $web.Lists["MyList"]
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("c1",$spFieldType,$false)
$spList.Fields.Add("c2",$spFieldType,$false)
$spList.Fields.Add("c3",$spFieldType,$false)
$spList.Update()

And it was throwing this exception, not in the powergui output console. In this console the error said only that SPList is null, so when I try to add the column it was not working.

What I did is to run each line one by one and see the Log on real time with ULS Log Viewer

Then in the log, I found this exception below, in the line $web.Lists["MyList"]

Unable to cast COM object of type Microsoft.SharePoint.Library.SPRequestInternalClass to interface type Microsoft.SharePoint.Library.ISPRequest

Really weird, isnt it?, this code worked in another scenario.

The solution was:

param([string]$webAppUrl)
[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(
{
$site = SPSite($webAppUrl)
$web = $site.RootWeb
$spList = $web.Lists["Workspace Access Rights"]
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("Organisation",$spFieldType,$false)
$spList.Fields.Add("Country",$spFieldType,$false)
$spList.Fields.Add("samAccountName",$spFieldType,$false)
$spList.Update()
}
)

and voila it works now.

I hope this information is useful to someone out there. If you face the same problem with other scenarios, and find a solution, please comment.

About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s