Wednesday, November 16, 2011

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

 

I have faced this error on various instances; see below the scenarios and solutions.

 

1.       It seems the error will occur when you have no permission to update the item. Try to run your code in RunWithElevatedPrivileges as below:

SPSecurity.RunWithElevatedPrivileges(delegate()

{

 using (SPSite spSite = new SPSite("http://MyWebApp"))

 {

using (SPWeb spWeb = spSite.OpenWeb())

 {      // insert your code here  }   }});

 

2.       The 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.CSS

Wrong Code:

string siteUrl = @" http://MyWebApp"

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://MyWebApp"

SPSecurity.RunWithElevatedPrivileges(delegate() 

using (SPSite site = new SPSite(siteUrl)) 

{

    using (SPWeb web = SPSDestSite.OpenWeb())

    { 

           // To do ( run code here ) 

    } 

}); 

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://sites.wizdim.com/pathikrawal/sharepoint-2010/errorunable-to-evaluate-expression-because-the-code-is-optimized-or-a-native-frame-is-on-top-of-the-call-stack-while-debugging-project-in-visual-studio-2010-for-sharepoint-2010

 

No comments:

Post a Comment