Developer's Connection
by: Scott Jackson, MCT, Manager .Net Development Training
I am often asked for advice on how to write better, cleaner code using .NET. I am a big fan of encapsulation – especially as it relates to data access. If you are looking for a Microsoft solution that has been tested and used in many companies throughout the industry, I suggest checking out Microsoft Data Access Application Blocks.
The most common tasks are encapsulated within the application block methods. Certain features, like opening and closing the database, take place “behind the scenes” and have error handling code surrounding them. This will help speed up development, and reduce errors in coding
An example from Codersource helps to illustrate this. The first block of code is inserting 2 parameters into the database. 12 lines of code in total:
string connectionString = (string)
ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("INSERT_PERSON",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Name",SqlDbType.NVarChar,50));
command.Parameters["@Name"].Value = txtName.Text;
command.Parameters.Add(new SqlParameter("@Age",SqlDbType.NVarChar,10));
command.Parameters["@Age"].Value = txtAge.Text;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Using Application Blocks, we can accomplish the same thing in 3 lines of code:
using Microsoft.ApplicationBlocks.Data;
SqlHelper.ExecuteNonQuery(connection,"INSERT_PERSON",new
SqlParameter("@Name",txtName.Text) ,new SqlParameter("@Age",txtAge.Text) );
As you can see, this code is much cleaner. All of the code from the preceding block is still happening, but it’s all inside the Application Block. Even more useful is that when you download this, you have full access to the source code. This means you can add your own code to the application block – great for customizing it for your organization.
For this example, I am using the earlier version, which is simpler to understand. It can be downloaded from here. The newer version can be downloaded here, and is part of the Enterprise Library 4.0 and Unity 1.2. I will get more into detail on these with my next article.
If you want to give Scott feedback on this article, email him @ sjackson@neweratechology.com
|