11.07.2015 Views

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 14: Building Secure Data Access 391(continued)}finally{conn.Close(); // Ensures connection is closed}// Helper routine that logs SqlException details to the// <strong>Application</strong> event logprivate void LogException( SqlException sqlex ){EventLog el = new EventLog();el.Source = "CustomAppLog";string strMessage;strMessage = "Exception Number : " + sqlex.Number +"(" + sqlex.Message + ") has occurred";el.WriteEntry( strMessage );}foreach (SqlError sqle in sqlex.Errors){strMessage = "Message: " + sqle.Message +" Number: " + sqle.Number +" Procedure: " + sqle.Procedure +" Server: " + sqle.Server +" Source: " + sqle.Source +" State: " + sqle.State +" Severity: " + sqle.Class +" LineNumber: " + sqle.LineNumber;el.WriteEntry( strMessage );}Ensure Database Connections Are ClosedIf an exception occurs, it is essential that database connections are closed <strong>and</strong> anyother limited resources are released. Use finally blocks, or the C# using statement toensure that connections are closed whether an exception condition occurs or not. Theabove code illustrates the use of the finally block. You can also use the C# usingstatement, as shown below:using ((SqlConnection conn = new SqlConnection(connString))){conn.Open();// Connection will be closed if an exception is generated or if control flow// leaves the scope of the using statement normally}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!