Sunday, April 12, 2009

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when use new spsite

Scenario:
While using RunWithElevatedPrivileges you got following error.

Error : Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when use new spsite

Solution:
SPSite and SPWeb object should be created inside delegate(), example below. If not you might get the above error.

Wrong Code:

string siteUrl = @"http://localhost";
SPSite site = null ;
SPWeb web = null ;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
site = new SPSite(siteUrl);
web = SPSDestSite.OpenWeb();

// To do ( run code here )

});
web.Close();
site.Close();
Correct Code:
string siteUrl = @"http://localhost";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = SPSDestSite.OpenWeb())
{
// To do ( run code here )
}
}
});

5 comments:

Anonymous,  February 2, 2011 at 1:17 AM  

Thanks for sharing.
it helps me solving this error.

Pavan Kumar February 7, 2011 at 6:29 AM  

Hi Sandeep,

I have a similar problem. We are using sharepoint "GetUsageData" method to get MySite URL details. I followed the same steps you posted, but still I am getting the problem.

Pavan Kumar February 7, 2011 at 6:30 AM  

Hi,

We are using sharepoint "GetUsageData" method to get all the details of MySite URL. how do we data from this ?

Pavan Kumar February 7, 2011 at 6:32 AM  

Hi,

we are using a sharepont method "GetUsageData" for MySite url access and get the details. I am facing the same problem while getting the data with "GetUsageData" method along with RunWithElevatedPrivileges

Pavan Kumar February 9, 2011 at 11:45 PM  

Hi,

I too have a similar problem.

But I got solved with 1 day of research work.
Here the problem is authorization. We need to provide authorization to GetUsageData method. How we can achieve this is by using SPUserToken object.

Here is the code.

SPUserToken token = personalSite.SystemAccount.UserToken;
(here personalSite = "http://...")
now
string personalUrl = UserProfile.PropertyContstant.PersonalUrl.ToString();
using(SPSite site = new SPSite(personalUrl,token)
{
using(SPWeb web = site.OpenWeb())
{
DataTable Dt = web.GetUsageData (.....);
{

}
}

Note that all the above code should be placed under RunWithElevatedPrivileges method.