Category Archives: Best Practices

Take Advantage of Application Name

Along with the SQL Server, Database, Username and Password, don’t forget to include the Application Name in your connection string.  It’s an optional parameter, but it can be a lifesaver. 

     Data Source=myServer;
     Initial Catalog=myDB;
     User Id=myUsername;
     Application Name=myApp;

Consider this example:  There are multiple .NET applications running on a single web server.  Each application shares a common SQL Server Server which is suddenly performing very poorly.   You are tasked with determine which of the applications is causing havoc.  You launch SQL Profiler and run a trace.  Since you have included the optional parameter in your connection string, you may now filter the application specific queries and troubleshoot the problem far more effectively.  If you hadn’t specified the application name, you would have some work ahead of you.  In this case, all of the queries would have had a generic app name, .NET sqlClient Data Provider, and that isn’t very helpful, is it?  

Do yourself a favor and be sure to add this practice to your coding standards…

Poor Performance with DateTime.Parse()

We traced a performance bottleneck to a single function recently. Interestingly enough, this function has been in existence (running in a production environment in all of its glory) for roughly 4 years now. Only now that we are required to execute the offending piece of code approximately 10 million times within a short four hour window has the problem actually surfaced.Our function has about 100 LOC. It contains custom collection class references, string manipulation, financial calculations and numerous other operations which I would flag as suspicious. We successfully avoided performance counters and simply stepped through the code after ensuring we had set an adequate number of timespan variables to track execution times the old fashion way. As it works out, DateTime.Parse we the bottleneck and our simple logic to determine is IsDate() or IsDatePast() might as well have been the most complicated, resource-eating routines on the planet.Why was this? Well, the Parse method tries very hard to make sense of the string that’s passed to it in order to create a valid DateTime value. It ignores leading and trailing white space, and unrecognized characters if possible, and it fills in missing information with the corresponding current date and time values. Parse will throw a FormatException if it’s unable to decipher the string you send to it, but otherwise, it bends over backwards for you. Our guess is it tries to do too much for its own good and exhausts itself in the process.We tried to replace the Parse method with the other DateTime static method — ParseExact — but it didn’t provide much relief.In the end, we got creative. We opted to create a simple function which first instantiates a new DateTime reference by using the month, day and year from the string representation of the date. (We were lucky because we knew this string would either be in the MM/DD/YYYY format or emtpy.)  Would you believe that splitting our string and then constructing a new DateTime reference performed considerably better than using the standard DateTime.Parse method?  Well, it did.

1: ///<summary> 2: ///Do not rely on the DateTime.Parse() method 3: ///Check if date is in the past by splitting string, 4: ///building datetime object then compare against today 5: ///</summary> 6: ///<param name=”sDate”>Date to Check</param> 7: ///<returns>False if greater than today</returns>8: public static bool IsDatePastParse(string sDate) 9: { 10: try 11: { 12: if (sDate.Length > 0) 13: { 14: string[] dt = sDate.Split(‘/’); 15: return IsDatePast(16: new DateTime(Convert.ToInt32(dt[2]), 17: Convert.ToInt32(dt[0]),18: Convert.ToInt32(dt[1])));19: } 20: else 21: {22: // Invalid if no date is passed 23: return false; 24: } 25: } 26: catch 27: { 28: // Assume the string was an invalid date29: return false; 30: } 31: } 32:  33: ///<summary> 34: ///Has the date past? Compare against today’s date. 35: ///</summary> 36: ///<param name=”dtDate”>Date to Check</param> 37: ///<returns>False if date is in the past</returns>38: public static bool isDatePast(DateTime dtDate) 39: { 40: // Consider today in the past41: if (DateTime.Today.Date >= dtDate.Date) 42: return true; 43: else 44: return false; 45:

Why Don’t We Handle Exceptions

Exception handling is extremely important, isn’t it? When it comes to testing, troubleshooting and maintenance it is paramount. Exception handling is definitely highlighted on every developers list of application technical requirements. So, why don’t all applications have proper exception handling? I have a few ideas.

The first and most likely reason is most developers (no matter how experienced) don’t have a good understanding of how to do it. This operation may seem trivial to some, but it actually takes a good amount of attention and care to do correctly. Granted, in many cases it’s perfectly fine to simply wrap the contents of a function with a “generic” try/catch block and merely bubble the exception up to its caller. Great. But what does the caller do with the exception? Nine out of ten times the caller, in turn, will also bubble the exception up (because that’s what the “pattern” does) or it swallows it. Even if a coder uses this bare bones approach, there are usually issues with the implementation. For example, there is a big difference between throw; and throw ex;. The difference is that throw; preserves the original stack trace and throw ex; truncates the stack trace below the method in which the throw ex; call is located. Most of the time, throw ex; is inappropriately. There are many other examples of poor exception handling, but here’s my favorite — the coder does everything “by the book” until it is time to display a error page and a coder reveals the exception details including secure information such as connection strings to the user. Yikes! Not understand proper exception handling can be dangerous.

The second reason is priority and timeline. Exception handling isn’t sexy and, let’s be honest, it doesn’t need to be in place before an application can be deployed. Hence, exception handling is usually pushed to the backburner — along with technical documentation. Only once the application requires future troubleshooting do we feel the pain of the missing “requirement.” Interesting enough, a colleague of mine now waits until his code base is quite stable to implement his error handling. He does this without regard for priority and timeline. He’d prefer to have his application assume unnecessary fatal errors early on it the project lifecycle rather than mask the issues through improper exception handling. All the same, timeline is still a standard developer excuse for lack of error handling.

The third reason is ego. Aren’t we all a little guilty of thinking our code can’t fail? After all, we can’t have a bunch of coders with defeatist-attitudes working on our projects. 🙂 Without the safety net of exception handling, we are bound to write better code, right? (Of course, this argument doesn’t hold a lot of water since it would promote getting rid of the QA team if we wanted really good code.) I do think ego is a factor though, but I’m not sure to what extent.

That’s my take on exception handling. What do you think?

Improve String Management with StringBuilder

Strings are immutable. In other words, a string can not be changed once assigned. When you append a string to an existing string, the .NET framework actually creates a new string containing the original string and the appended string. This is a resource-hungry and time-consuming process.

The alternative to appending strings, is the StringBuilder class which is somewhat hidden in the System.Text namespace. The class is faster because it allocates an initial space when an instance of it is created. By default, a StringBuilder object created using the StringBuilder class default constructor reserves a space of 16 characters in memory. This default can be overloaded.

Generally, the recommended cutoff number is five. If you have more than five separate string concatenations, StringBuilder is generally more efficient than appending the strings.

Convert ToString with Caution

Assume we have a datarow field, name, which evaluates to null. What is the result of the following two cases?

string name = Convert.ToString(dr[“name”]);

string name = dr[“name”].ToString();

In the first case, Convert.ToString() will evaluate to null. In the second case, however, .ToString() will throw an exception. And it makes sense, doesn’t it? After all, “nothing” doesn’t have a ToString() function to execute!

So, do yourself a favor and use object.ToString() sparingly. Use is only when using non-null values. In cases where null is a possibility, use Convert.ToString().

Short-circuit Operators in C#

Do you know how to short-circuit operators? In C#, And (&) and Or (|) operators evaluate both boolean expressions in the statement. However, the && operator only evaluates the first Boolean if false and the || operator only evaluates the first Boolean if true. This technique prevents the execution of the second expression if unnecessary — therefore optimizing your logic.

if (_username ==”” & _password == “”)


if (_username == “” && _password == “”)