I ran into a situation that reminded me of Steam Harman’s post about A New Year’s Resolution for Developers in which he states that by default methods should be public and virtual unless there is a good reason not to.
This started when after I decided I was missing functionality like RegisterClientScriptBlock, allowing me to add a client script only if one of the controls needs it, along with only adding it once. I was also missing the ability to use designers.
To this end, I decided I was going to make a simple server control library with server controls that would provide the functionality found in the MVCToolkit Html extension methods. I also figured it would be nice if I could allow them to function in WebForms as well, if they are on a runat server form tag.
After a while I found the VerifyRenderingInServerForm method on the Page, which seemed to be the only method available for this. Unfortunately while I can override this method after loading up reflector to see how the base Page was determining that the control is in a form tag, I found that I could only do it with a try/catch around base.VerifyRenderingInServerForm.
While I don’t really have much of a problem doing this, there is a little bit of nagging in the back of my head over the fact that the Page class contains a method called IsInOnFormRender, which has exactly the information I want. Unfortunately this property is internal, preventing me from retrieving efficiently retrieving this information.
The other problem I find with this is that these server controls would need to run on a special page in order to have the desired functionality, have each of the controls that while have the functionality do the try/catch on VerifyRenderingInServerForm, or use reflection to get access to that variable. None of which are particularly optimal.
On a side note, I wish I had found this method when I years ago when I was writing the controls of the framework we use at work. Since I could not have our controls running within a runat server form tag because we submit the data through an IFrame, overriding VerifyRenderingInServerForm would have allowed me to stop them from throwing the error.