C# shortcuts
<geek>Let me first say that I really, really like working with .nizzle. The problem is that so many of the web apps that i work on are really similar, so a lot of the work gets boring; seems like I'm always doing the same steps for an admin site: 1. Create database table for new article/category/user/whatever. 2. Create all associated stored procedures to add/update/delete/otherwise modify new db table. 3. Create a strongly typed C# object to hold all the methods and properties of said object. 4. Create front-end .aspx pages to allow admin user to make use of steps 1-3. 5. Lather/rinse/repeat.
The other day I found a neat little chunk of code from M$FT to help me out with step 3, the Data Access Application Block, which is really just a bunch of handy shortcuts for some of the more repetitive coding that I do.
"Well, geez", you're saying, "don't just tell me about it, show my why it's better!" Hey sure.
For a really simple grab of all records and stuffing them in a database, we go from this:
public DataSet GetAllArticles() { // Create Instance of Connection and Command Object SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]); SqlCommand myCommand = new SqlCommand("GetAllNewsArticles", myConnection); // Mark the Command as a SPROC // Adapter and DataSet try catch(Exception oException) |
to this:
public DataSet GetTopLevelProductCategories() { // Create Instance of Connection and Command Object SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]); DataSet oDataSet; oDataSet = SqlHelper.ExecuteDataset(myConnection,CommandType.StoredProcedure, "GetTopLevelProductCategories"); return oDataSet; if (myConnection.State == ConnectionState.Open) myConnection.Close(); } // end GetTopLevelProductCategories() |
Notice the "ExecuteDataset" function, which is an overloaded function which lets you pass parameters, transaction info, or not.
I like it even better when you're passing parameters to an insert or update stored procedure. Old style:
public bool UpdateCategory(Category myCategory) { SqlConnection myConnection = null; SqlCommand myCommand = null; bool bUpdated = true; myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]); myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterName = new SqlParameter("@Name", SqlDbType.VarChar, 255); SqlParameter parameterImageUrl = new SqlParameter("@ImageUrl", SqlDbType.VarChar, 255); try return bUpdated; } // end UpdateCategory() |
New hotness:
public void UpdateProductCategory(ProductCategory myCategory) { SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]); SqlParameter[] arParams = new SqlParameter[4]; |
No more setting datatypes, and taking 3 lines to add one stored procedure parameter. Less is more. </geek>