Wednesday, May 12, 2010

Error:Unable 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

Hi All,
I have CUSTOM WCF Service hosted in IIS as a part of SharePoint Virual Directory (ISAPI under _vti_bin). This Web Service is triggered by Custom Pages and Controls on the same FARM Server. This service does nothing but adds a Web Part of user’s choice to a Page. For this I have used SharePoint Object Model.  now the actual problem, When I try to user //SPSite oSite = SPContext.Current.Site in my code, I was getting following error “Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”.
After doing some analysis I found that it is actually a “Access Denied” error which is thrown while trying to create SPSite object.
Resolution: Use SPSecurity.RunWithElevatedPrivileges, if you using Object Model in your Service Layer.
Sample code:
SPSite oSite = SPContext.Current.Site;
         Guid siteGuid = oSite.ID;
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
            //Get the SPSite Object 
             // I am using SPContext within RunWithElevatedPrivileges
             //Opening the Site with new SPSite(siteGuid);
             oSite = new SPSite(siteGuid);
             //Open the Web now
             oWebSite = oSite.OpenWeb();
        });


Thanks
Pathik

2 comments:

Clark Updike said...

Dude, a huge thanks for posting this. When I tried to debug it, it would dump me right into a catch block but the exception was useless (everything was "unable to evaluate...") and my diagnostic logging wasn't writing anything. I was stumped. How did you track it down to Access Denied?

Pathik Rawal said...
This comment has been removed by the author.