RSS

Tag Archives: error stack

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

Problem description:
This is one of the common runtime error reported by a lot of ASP.NET users. A successfully compiled code at runtime throws the following error during an operation:

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

Typically, this happens when the Response.EndResponse.Redirect, or Server.Transfer method is used.

Assessment:
This happens because current page execution is stopped and execution is sent to the Application_EndRequest event in the application’s event pipeline.

The duty of Response.End method is to stop the page execution and raise the EndRequest event. Thus, the line of code that follows Response.End is not executed. Error occurs with Response.Redirect and Server.Transfer methods too because both the methods call Response.End internally.

When a call is made to the Abort method to destroy a thread, the CLR throws a ThreadAbortException. It is a special exception that can be caught, but will automatically be raised again at the end of the catch block. When this exception is re-raised, the CLR executes all the finally blocks before ending the thread.

Using Visual Studio debugger, we can see the internal message for the exception as “Thread was being aborted.”

Resolution:

  • Use a try-catch statement to catch the exception if needed
    try {
    }
    catch (System.Threading.ThreadAbortException ex){
    }
  • For Response.End : Invoke  HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event
  • For Response.Redirect : Use an overload, Response.Redirect(String url, bool endResponse) that passes false for endResponse parameter to suppress the internal call to Response.End
    // code that follows Response.Redirect is executed
    Response.Redirect ("mynextpage.aspx", false);
  • For Server.Transfer : Use Server.Execute method to bypass abort. When Server.Execute is used, execution of code happens on the new page, post which the control returns to the initial page, just after where it was called.

Refer:
Microsoft Support Article – 312629
MSDN: HttpResponse.Redirect Method
MSDN: HttpResponse.End Method
MSDN: ThreadAbortException Class
MSDN: HttpServerUtility.Execute Method

Conclusion:
This is as designed. This exception has bad effect on Web application performance, which is why handling the scenario correctly is important.

Advertisements
 
1 Comment

Posted by on January 27, 2013 in ASP.NET

 

Tags: , , , ,

“Cannot evaluate expression because the code of the current method is optimized”

Problem description:
This is one the common error faced by a lot of Visual Studio users. Typically, they get the below error message during debugging:

“Cannot evaluate expression because the code of the current method is optimized.”

Assessment:
In .NET, “Function Evaluation (funceval)” is the ability of CLR to inject some arbitrary call while the debuggee is stopped somewhere. Funceval takes charge of the debugger’s chosen thread to execute requested method. Once funceval finishes, it fires a debug event. Technically, CLR have defined ways for debugger to issue a funceval.

CLR allows to initiate funceval only on those threads that are at GC safe point (i.e. when the  thread will not block GC) and Funceval Safe (FESafe) point (i.e. where CLR can actually do the hijack for the funceval.) together. Thus, possible scenarios for CLR, a thread must be:

1. stopped in managed code  (and at a GC safe point): This implies that we cannot do a funceval in native code. Since, native code is outside the CLR’s control, it is unable to setup the funceval.

2. stopped at a 1st chance or unhandled managed exception (and at a GC safe point): i.e at time of exception, to inspect as much as possible to determine why that exception occurred. (e.g: debugger may try to evaluate and see the Message property on raised exception.)

Overall, common ways to stop in managed code include stopping at a breakpoint, step, Debugger.Break call, intercepting an exception, or at a thread start. This helps in evaluating the method and expressions.

Refer: MSDN Blog: Rules of Funceval

Possible resolutions:
Based on the assessment, if thread is not at a FESafe and GCSafe points, CLR will not be able to hijack the thread to initiate funceval. Generally, following helps to make sure funceval initiates when expected:

Step #1:

Make sure that you are not trying to debug a “Release” build. Release is fully optimized and thus will lead to the error in discussion. By using the Standard toolbar or the Configuration Manager, you can switch between Debug & Release.

For more details about it: How to: Set Debug and Release Configurations

Step #2:

If you still get the error, Debug option might be set for optimization. Verify & Uncheck the “Optimize code” property under Project “Properties”:

  • Right click the Project
  • Select option “Properties”
  • Go to “Build” tab
  • Uncheck the checkbox “Optimize code”

Step #3:

If you still get the error, Debug Info mode might be incorrect. Verify & set it to “full” under “Advanced Build Settings”:

  • Right click the Project
  • Select option “Properties”
  • Go to “Build” tab
  • Click “Advanced” button
  • Set “Debug Info” as “full”

Step #4:

If you still face the issue, try the following:

  • Do a “Clean” & then a “Rebuild” of your solution file
  • While debugging:
    1. Go to modules window (VS Menu -> Debug -> Windows -> Modules)
    2. Find your assembly in the list of loaded modules.
    3. Check the Path listed against the loaded assembly is what you expect it to be
    4. Check the modified Timestamp of the file to confirm that the assembly was actually rebuilt
    5. Check whether or not the loaded module is optimised or not
  • Remote chance could be that your call stack is getting optimized because your method signature is too large (more than 256 argument bytes). Read more about it at this MSDN blog

Conclusion:
It’s not an error but an information based on certain settings and as designed based on how .NET runtime works.

 
1 Comment

Posted by on January 26, 2013 in ASP.NET, Visual Studio

 

Tags: , , , ,

“Invalid postback or callback argument”

Problem description:
This is one the common issues that a lot of ASP.NET beginners face, post and ask about. Typically, they post the error message as below and seek for resolution without sharing much about what they were trying to do.

[ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation=”true” %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]

Though, error stack trace itself suggests a quick resolution by setting eventvalidation off, it is not a recommended solution as it opens up a security hole. It is always good to know why it happened and how to solve/handle that root problem.

Assessment:
Event validation  is done to validate if the origin of the event is the related rendered control (and not some cross site script or so). Since control registers its events during rendering, events can be validated during postback or callback (via arguments of __doPostBack). This reduces the risk of unauthorized or malicious postback requests and callbacks.

Refer: MSDN: Page.EnableEventValidation Property

Based on above, possible scenarios that I have faced or heard that raises the issue in discussion are:
Case #1: If we have angular brackets in the request data, it looks like some script tag is being passed to server

Possible Solution:
HTML encode the angular brackets with help of JavaScript before submitting the form, i.e. replace “<” with “&lt;” and “>” with “&gt;”

function HTMLEncodeAngularBrackets(someString)
{
var modifiedString = someString.replace("<","&lt;");
modifiedString = modifiedString.replace(">","&gt;");
return modifiedString;
}

Case #2: If we write client script that changes a control in the client at run time, we might have a dangling event. An example could be having embedded controls where an inner control registers for postback but is hidden at runtime because of an operation done on outer control. This I read about on MSDN blog written by Carlo, when looking for same issue because of multiple form tags.

Possible Solution:
Manually register control for event validation within Render method of the page.

protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(myButton.UniqueID.ToString());
base.Render(writer);
}

As said, one of the other common scenario reported (which looks like falls in the this same category) is building a page where one form tag is embedded in another form tag that runs on server. Removing one of them corrects the flow and resolves the issue.

Case #3: If we re-define/instantiate controls or commands at runtime on every postback, respective/related events might go for a toss. A simple example could be of re-binding a datagrid on every pageload (including postbacks). Since, on rebind all the controls in grid will have a new ID, during an event triggered by datagrid control, on postback the control ID’s are changed and thus the event might not connect to correct control raising the issue.

Possible Solution:
This can be simply resolved by making sure that controls are not re-created on every postback (rebind here). Using Page property IsPostback can easily handle it. If one want to create control on every postback, then it is necessary to make sure that the ID’s are not changed.

protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
// Create controls
// Bind Grid
}
}

Conclusion:
As said, easy/direct solution can be adding enableEventValidation=”false” in the Page directive or Web.config file but is not recommended. Based on the implementation and cause, find the root cause and apply the resolution accordingly.

 
Leave a comment

Posted by on January 24, 2013 in ASP.NET

 

Tags: ,