Thursday, 4 August 2016

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

Issue: 

I was trying to delete a task when I was encounter with below error:

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

Code Sample:

SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPWeb web = SPContext.Current.Site.AllWebs[new Guid(web guid)]) // this line throws error
                            {
                                SPList taskList = web.Lists[new Guid(list id)];
                                SPListItem _lstItem = taskList.GetItemById(Convert.ToInt32(item id));
                                if (_lstItem != null)
                                {
                                    _lstItem.Delete();
                                }
                                taskList.Update();
                            }                      
                    });

Reason:

From this site I was able to get reason for this error:
When running inside RunWithElevatedPrivileges, if use SPContext.Current.Site object directly, you will not able to get site object.

Solution:

Instead create a new SPSite object, passing in SPContext.Current.Site.Url.

Code Sample:

SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(SPContext.Current.Site.Url)) //add this line
                        {
                            using (SPWeb web = site.AllWebs[new Guid(web guid)])
                            {
                                SPList taskList = web.Lists[new Guid(list id)];
                                SPListItem _lstItem = taskList.GetItemById(Convert.ToInt32(item id));
                                if (_lstItem != null)
                                {
                                    _lstItem.Delete();
                                }
                                taskList.Update();
                            }
                        }
                    });

Reference: 
  1. http://sharepoint.stackexchange.com/questions/27462/unable-to-evaluate-expression-because-the-code-is-optimized-or-a-native-frame-is
  2. http://frazzleddad.blogspot.in/2011/03/getting-past-sharepoint-exceptions-with.html