Hi,
I have BasePage.cs class which is being used by other .cs files instead of System.Web.UI.Page (public partial class page : BasePage).
I am using it for opening and closing SQL connections to make sure every SQL connection gets closed.
Code looks like this
{
public class BasePage: System.Web.UI.Page
{
public SqlConnection globalConnection;
protected override void OnInit(EventArgs e)
{
globalConnection = new SqlConnection();
globalConnection.ConnectionString = ConfigurationManager.ConnectionStrings["kontemiConnectionString"].ToString();
globalConnection.Open();
}
protected override void OnUnload(EventArgs e)
{
if (globalConnection != null)
{
globalConnection.Close();
}
}
}
}
So far it has worked really well for me. It means that every time a connection opens it also gets closed. Or at least I thought so.
My question is whether this solutions is bulletproof and every single connection gets closed in case there is some processing error during code execution. When tracing this code, if I on purpose create error 500 it always goes to OnUnload event and gets closed.
So, do you think is this execution safe? (To stop discussion whether I shouldn't open SQL when I actually need it, answer is that every page which uses BasePage also opens a SQL connection.)