“vshost32.exe has stopped working”

This is another one of the common errors developers get and ask about: vshost32.exe has stopped working.

Problem Statement

When I run my project (or a particular usecase), it displays an error: vshost32.exe has stopped working

Assessment

vshost was introduced in Visual Studio 2005 (only for use in VS). These are files that contains vshost in the file name and are placed under the output (default bin) folder of the application. It is the “hosting process” created when we build a project in Visual Studio.

It has following core responsibilities:

  • to provide support for improved F5 performance
    To run a managed application in debug mode using F5 command, Visual Studio would need an AppDomain to provide a place for the runtime environment within which the application can run. It takes quite a bit of time to create an AppDomain and initialize the debugger along with it. The hosting process speeds up this process by doing all of this work in the background before we hit F5, and keeps the state around between multiple runs of the application.
  • for partial trust debugging
    To simulate a partial trust environment within Visual Studio under the debugger would require special initialization of the AppDomain. This is handled by the hosting process
  • for design time expression evaluation
    To test code in the application from the immediate window, without actually having to run the application. The hosting process is used to execute code under design time expression evaluation.

More details can be read here.

With above details, there could be issues while interacting with Operating System through this AppDomain and thus causing an error.

Possible Resolutions

Generally, it would be to figure out if the issue is specifically because of Visual Studio hosting process or there are other issues at play interacting with vshost.

Scenario 1:

It’s 64 bit OS, app is configured to build as AnyCPU, yet we get an error

Try:
32 bit/64 bit issues usually plays a role in relation to OS features and locations that are different. There is a setting in Build configuration that drives the debugger behavior when it is setup for AnyCPU. You need to turn off (un-tick checkbox) the Prefer 32 bit flag to run in 64 bit mode.

Now, even with above change, we can face issues that fall into 32/64 bit region. This is where vshost is still playing a role. Irrespective of above, flag vshost continues to work in 32 bit mode (platform config AnyCPU). Now, calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results. Details about how to turn it off in Debug tab: How to: Disable the Hosting Process

With above changes, AnyCPU configuration would be equivalent to the app as platform target x64 configuration.

Scenario 2:

Application is configured to build as x86 (or AnyCPU)

Try:
If the workflow is related to a third party, for 32 bit applications, use 32 bit runtime, irrespective of the OS being 32 bit or 64 bit.

Scenario 3:

Application is throwing an error for a specific code work flow that involves unmanaged assembly

Try:
If the workflow includes an interop call to an external assembly (unmanaged code that is executed outside the control of CLR), there might be incorrect usage of the function all. I have seen examples where a wrong return type can cause a vshost error. Return type of the external DLL cannot be string, it must be IntPtr.

[DllImport("Some.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr SomeMethod();
Scenario 4:

Application is throwing an error for a specific code work flow that is in realms of managed code (by CLR)

Try:
It could be that the process is taking time while executing that particular workflow. If the process is busy for a long time, it can throw an error. One of the solve would be to try the entire long operation on a BackgroundWorker thread and free up UI thread.

Conclusion

We can turn off the vshost as long as we are okay without it. It always helps to have same debugging environment (32/64 bit) as the app is expected to run in. We should be cognizant of the operations done with third party assemblies or unmanaged ones and have the right set of code/files interacting with application.

Happy troubleshooting!

Samples GitHub Profile Readme

Troubleshoot: Kafka setup on Windows

Recently, I did a setup of Kafka on a windows system and shared a Kafka guide to understand and learn. I was using a Win10 VM on my MacBook. It was not a breeze setup and had few hiccups on the way. It took some time for me to resolve them one after another looking around on web. Collating all of them here for quick reference.

ERROR #1

When:
I tried to start Zookeeper.

Command:
zookeeper-server-start.bat config\zookeeper.properties

Error:
java.lang.IllegalArgumentException: config/zookeeper.properties file is missing

Stack trace:

INFO Reading configuration from: config/zookeeper.properties (org.apache.zookeeper.server.quorum.QuorumPeerConfig)
[2014-08-21 11:53:55,748] FATAL Invalid config, exiting abnormally (org.apache.zookeeper.server.quorum.QuorumPeerMain)
org.apache.zookeeper.server.quorum.QuorumPeerConfig$ConfigException: Error processing config/zookeeper.properties
    at org.apache.zookeeper.server.quorum.QuorumPeerConfig.parse(QuorumPeerConfig.java:110)
    at org.apache.zookeeper.server.quorum.QuorumPeerMain.initializeAndRun(QuorumPeerMain.java:99)
    at org.apache.zookeeper.server.quorum.QuorumPeerMain.main(QuorumPeerMain.java:76)
Caused by: java.lang.IllegalArgumentException: config/zookeeper.properties file is missing
    at org.apache.zookeeper.server.quorum.QuorumPeerConfig.parse(QuorumPeerConfig.java:94)
    ... 2 more

How I solved?
It was clearly the case of relative path. config/zookeeper.properties was at two roots lower than where the start up script was. Either I had to correct the level or use an absolute path to move ahead.

zookeeper-server-start.bat C:\Installs\kafka_2.12-2.5.0\config\zookeeper.properties
rem OR relative path option below

zookeeper-server-start.bat ../../config/zookeeper.properties

ERROR #2

When:
Zookeeper is up and running. Attempted to start Kafka server and it failed.

Command:
kafka-server-start.bat C:\Installs\kafka_2.12-2.5.0\config\server.properties

Error:
kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING

Stack trace:

........
........
2020-07-19 01:20:32,081 ERROR Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer) [main]
kafka.zookeeper.ZooKeeperClientTimeoutException: Timed out waiting for connection while in state: CONNECTING
at kafka.zookeeper.ZooKeeperClient.$anonfun$waitUntilConnected$3(ZooKeeperClient.scala:268)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
at kafka.zookeeper.ZooKeeperClient.waitUntilConnected(ZooKeeperClient.scala:264)
at kafka.zookeeper.ZooKeeperClient.(ZooKeeperClient.scala:97)
at kafka.zk.KafkaZkClient$.apply(KafkaZkClient.scala:1694)
at kafka.server.KafkaServer.createZkClient$1(KafkaServer.scala:348)
at kafka.server.KafkaServer.initZkClient(KafkaServer.scala:372)
at kafka.server.KafkaServer.startup(KafkaServer.scala:202)
at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:38)
at kafka.Kafka$.main(Kafka.scala:75)
at kafka.Kafka.main(Kafka.scala)
2020-07-19 01:20:32,088 INFO shutting down (kafka.server.KafkaServer) [main]
2020-07-19 01:20:32,105 INFO shut down completed (kafka.server.KafkaServer) [main]
2020-07-19 01:20:32,106 ERROR Exiting Kafka. (kafka.server.KafkaServerStartable) [main]
2020-07-19 01:20:32,121 INFO shutting down (kafka.server.KafkaServer) [kafka-shutdown-hook]

How I solved?
Investigation lead to increasing the timeout settings for Kafka-Zookeeper. Because of environment settings (RAM, CPU, etc), it turns out this plays some role.
I updated the ${kafka_home}/config/server.properties file:

# Timeout in ms for connecting to zookeeper (default it was 18000)
zookeeper.connection.timeout.ms=36000 

I read many other reasons for this error (did not look applicable to my case) like:
1. zookeper service not running
2. restarting system
3. zookeper is hosted on zookeeper:2181 or other server name instead of localhost:2181

ERROR #3

When:
Zookeeper is up and running. Attempted to start Kafka server and it failed.

Command:
kafka-server-start.bat C:\Installs\kafka_2.12-2.5.0\config\server.properties

Error:
java.lang.OutOfMemoryError: Map failed OR java.io.IOException: Map failed

Stack trace:

.......
.......
java.io.IOException: Map failed
        at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:944)
        at kafka.log.AbstractIndex$$anonfun$resize$1.apply(AbstractIndex.scala:115)
        at kafka.log.AbstractIndex$$anonfun$resize$1.apply(AbstractIndex.scala:105)
        at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:213)
        at kafka.log.AbstractIndex.resize(AbstractIndex.scala:105)
        at kafka.log.LogSegment.recover(LogSegment.scala:256)
        at kafka.log.Log.kafka$log$Log$$recoverSegment(Log.scala:342)
        at kafka.log.Log.recoverLog(Log.scala:427)
        at kafka.log.Log.loadSegments(Log.scala:402)
        at kafka.log.Log.<init>(Log.scala:186)
        at kafka.log.Log$.apply(Log.scala:1609)
        at kafka.log.LogManager$$anonfun$loadLogs$2$$anonfun$5$$anonfun$apply$12$$anon
fun$apply$1.apply$mcV$sp(LogManager.scala:172)
        at kafka.utils.CoreUtils$$anon$1.run(CoreUtils.scala:57)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1
149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:
624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.OutOfMemoryError: Map failed
        at sun.nio.ch.FileChannelImpl.map0(Native Method)
        at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:941)
        ... 17 more

How I solved?
It turned out related to Java heap size. I made a change in the Kafka startup script file: ${kafka_home}/bin/windows/kafka-server-start.bat

IF NOT ERRORLEVEL 1 (
        rem 32-bit OS
        set KAFKA_HEAP_OPTS=-Xmx512M -Xms512M
    ) ELSE (
        rem 64-bit OS
        rem set KAFKA_HEAP_OPTS=-Xmx1G -Xms1G => Commented this
        rem added this below line
	set KAFKA_HEAP_OPTS=-Xmx512M -Xms512M
    )

Though, while looking for solution, quite a few also solved it up upgrading their Java from 32bit to 64bit application. I did not try this solution as had other Java setup dependencies on my system that I wanted to keep intact.

ERROR #4

When:
I tried to delete Kafka topic because I was having problems while pushing message from Producer

Command:
kafka-topics.bat --list --bootstrap-server localhost:9092 --delete --topic my_topic_name

Error:
Topic test is already marked for deletion

Stack trace:

Topic test is marked for deletion.
Note: This will have no impact if delete.topic.enable is not set to true.

How I solved?
I enabled topic deletion configuration. It needs to be set as delete.topic.enable = true in file ${kafka_home}/config/server.properties. Restarted the server post updating the config.

# Delete topic enabled
delete.topic.enable=true

ERROR #5

When:
Zookeeper & Kafka is up and running. I get an error when I try to create a Topic.

Command:
kafka-topics.bat --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic testkafka

Error:
org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment

Stack trace:

Error while executing topic command : org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
[2020-07-19 01:41:35,094] ERROR java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
    at org.apache.kafka.common.internals.KafkaFutureImpl.wrapAndThrow(KafkaFutureImpl.java:45)
    at org.apache.kafka.common.internals.KafkaFutureImpl.access$000(KafkaFutureImpl.java:32)
    at org.apache.kafka.common.internals.KafkaFutureImpl$SingleWaiter.await(KafkaFutureImpl.java:89)
    at org.apache.kafka.common.internals.KafkaFutureImpl.get(KafkaFutureImpl.java:260)
    at kafka.admin.TopicCommand$AdminClientTopicService.createTopic(TopicCommand.scala:163)
    at kafka.admin.TopicCommand$TopicService.createTopic(TopicCommand.scala:134)
    at kafka.admin.TopicCommand$TopicService.createTopic$(TopicCommand.scala:129)
    at kafka.admin.TopicCommand$AdminClientTopicService.createTopic(TopicCommand.scala:157)
    at kafka.admin.TopicCommand$.main(TopicCommand.scala:60)
    at kafka.admin.TopicCommand.main(TopicCommand.scala)
Caused by: org.apache.kafka.common.errors.TimeoutException: Timed out waiting for a node assignment.
 (kafka.admin.TopicCommand$)

How I solved?
For once it worked for me as is but when I tried again later, I kept getting this error. While looking on web, suggestions were to enable listener and set it up like: listeners=PLAINTEXT://localhost:9093 in the server config file.

Before attempting this, I rebooted my system as it was little sluggish too. Turns out, mostly it was memory issue. I was in a Windows VM and probably it was craving for memory space. Without a change, things worked fine as is for me.

ERROR #6

When:
This was during another instance of Kafka setup (from start) in few days. Zookeeper is up and running. Attempted to start Kafka server and it failed.

Command:
kafka-server-start.bat C:\Installs\kafka_2.12-2.5.0\config\server.properties

Error:
It was around logs or lock file.

How I solved?
Looking at details, it hinted me to look into pre-exisiting (something related to my previous setup). I went ahead and deleted the logs and data folder that was auo created when I moved ahead with the entire process setup. Post this, the error was gone. Believe my server shutdown was not smooth and thus something was interferring with the current startup.

.

Hope these would help. Keep learning!

HTTP 500 – Internal server error

This is another common error that troubles a lot of ASP.NET users.

Problem Statement

Generally, the questions are framed like:

I receive a HTTP 500 – Internal Server Error  exception while trying to browse my hosted web application. Exception message says “This error (HTTP 500 Internal Server Error) means that the website you are visiting had a server problem which prevented the webpage from displaying”. Please help, how to resolve it?

Assessment

Any HTTP request made to web application running on IIS (or any other web server) returns the status of the response. This HTTP status code indicates about the request success or failure. If the request was unsuccessful, it might provide the reason why so.

Out of various status code, 5xx are the codes related to Server error. They indicate that the server failed to complete the request because server encountered an error.

The 500 Internal Server Error is a very general HTTP status code. It means something has gone wrong on the website and web server is unable to specify what exactly, thus failing in fulfilling the request made by the client. This is not related to client and the fault is in the webpage/website requested that resides on server. This status code can be considered as a ‘catch-all’ server error of Web server.

More details around various HTTP status code: The HTTP status code in IIS 7.0, IIS 7.5, and IIS 8.0

Possible Resolutions

Make sure that internally web server maintains some kind of internal error logs that gives more detail of what went wrong and thus help in diagnosing the issue. Generally, it is logged into Windows Event Logs on the server. Thus, first thing while troubleshooting the error is to see Windows Event Logs on the server to find what went wrong.

Other useful thing to troubleshoot it would be to disable friendly HTTP error messages to see if the raw content can provide a direction to look more. Steps:

  • Go to menu Tools/Internet Options in your IE.
  • Click on the Advanced tab & then uncheck “Show friendly HTTP error messages” option & then click Ok.
  • Now, when on accessing the same web page, much more developer meaningful error message will be shown.

Moving on, following are most common:

Option #1:
HRESULT: 0x80070035 – The page cannot be displayed because an internal server error has occurred.
This occurs because the server that is running IIS cannot access the configured root directory of the requested location.

Resolution would be to make sure that the server that is running IIS can access the configured root directory of the requested location.

Option #2:
HRESULT: 0x800700c1 – The page cannot be displayed because an internal server error has occurred.
This occurs because a script mapping is not valid.

Resolution would be to make sure that the script mapping points to the ISAPI.dll file that can process the request.
To do this, follow these steps:

  1. Click Start, click Run, type inetmgr.exe, and then click OK.
  2. In IIS Manager, expand server name, expand Web sites, and then click the Web site that you want to modify.
  3. In Features view, double-click Handler Mappings.
  4. Make sure that the script mapping points to the correct ISAPI.dll file. (e.g: .asp files should map to the %windir%\system32\inetsrv\asp.dll file)

Option #3:
HRESULT: 0x8007007f – There is a problem with the resource you are looking for, so it cannot be displayed.
This occurs because the handler mapping for the requested resource points to a .dll file that cannot process the request.

Resolution would be to edit the handler mapping for the requested resource to point to the .dll file that can process the request.
To do this, follow these steps:

  1. Click Start, click Run, type inetmgr.exe, and then click OK.
  2. In IIS Manager, expand server name, expand Web sites, and then click the Web site that you want to modify.
  3. In Features view, double-click Handler Mappings.
  4. Right-click the script mapping that you want to edit, and then click Edit.
  5. In the Edit Script Map dialog box, type the appropriate executable file in the Executable box, and then click OK.

Option #4:
One of the other possibilities could be an issue in the way web application is hosted. Some security configuration issue or conflict due to multiple config files.

Resolution would be to make sure application is hosted correctly by published the application as website and setting up the virtual directory as needed.
More details around the known issues and their resolution:
Error message when you visit a Web site that is hosted on IIS 7.0: “HTTP Error 500.0 – Internal Server Error”
Troubleshoot an “HTTP 500 – Internal Server Error” error message on IIS 4.0 or on IIS 5.0

Conclusion

This is a server error and can only be solved by website admin who has access to files and the web-server. There can be one of/or multiple reasons to get this error. One has to track down the issue and handle accordingly.

Keep learning!

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

This is one of the common runtime error reported by a lot of ASP.NET users.

Problem description

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

Try one of the following that suits your workflow:

  • Use a try-catch statement to catch the exception if needed
try { 
  // your code here
} 
catch (System.Threading.ThreadAbortException ex){ 
  // log/handle it
}
  • 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
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.

Keep learning!

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

This is one the common error faced by a lot of Visual Studio users.

Problem description

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.

Keep learning!

“Invalid postback or callback argument”

This is one the common issues that a lot of ASP.NET beginners face, post and ask about.

Problem description

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("<","<");
   modifiedString = modifiedString.replace(">",">");
   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.

Keep learning!