Tuesday, September 15, 2009

Code: Handling SQL Command Timeout Errors

Unfortunately there is not an exception object in .Net that corresponds directly to a command timeout.  However you can specifically handle one by checking the Number property on the exception.  The number for an SQL Exception happens to be –2 (Using reflection you can see the TdsEnum in System.Data.SqlClient).

catch (SqlException ex)
{
//Sql time out exception number is -2
if (ex.Number == -2)
{
//timeout exception, tell user to try changing params
lblTimeOut.Visible = true;
}
else
{
throw (ex);
}
}

Code: Setting Command Timeouts using Data Access Application Blocks

When doing database work in .Net you can set a timeout value in your connection string.  This timeout specifies the length of time (in seconds) to wait for a connection to the database server to be established.  If you want to specify a timeout value for your stored procedure in SQL command to complete, you need to set the time out on your command object.  If you are using Enterprise Library’s Data Access Application Blocks your code should look similar to below

Database db = DatabaseFactory.CreateDatabase("ConnectionStringName");
using (DbCommand cmd = db.GetStoredProcCommand("StoredProcedureName"))
{
    cmd.CommandTimeout = 60;
    int rowsAffected = db.ExecuteNonQuery(cmd);
}

Tuesday, September 8, 2009

Code: ASP.Net MVC Maintain Checkbox State

Below is a quick and dirty way to maintain a check box checked state during postbacks with MVC:

<%= Html.CheckBox("IsSecure", (Request.Form["IsSecure"] ?? string.Empty).Contains("true"))%>

Code: ASP.Net MVC SelectList / DropDownList Selected Item

I spent an hour on a strange issue on my MVC page the other day where MVC would not obey my SelectedItem assignment on a drop down list.  I originally thought the issue was how I was making the assignment in code, or the object I was using to do the binding, but it turns out that some built in MVC functionality was actually working against me.  If you name your ViewData key name the same name as your Html.DropDownList item, MVC will attempt to populate the selected value for you.  However I wanted to manually set the selected value so my solution was to change this:
<%= Html.DropDownList("Encoding", ViewData["Encoding"] as SelectList)%>

to:
<%= Html.DropDownList("Encoding", ViewData["EncodingData"] as SelectList)%>

And in my controller I just needed to change the ViewData key name accordingly:
Dictionary<string, string> pushPull = new Dictionary<string, string>();
pushPull.Add("pull_encode", "Pull");
pushPull.Add("push_encode", "Push");
if (pushPullValue == "") pushPullValue = "pull_encode";
ViewData["EncodingData"] = new SelectList(pushPull, "Key", "Value", pushPullValue);