Tag Archives: c#

Centralized exception handling

Exception handling is a very useful mechanism to improve a program’s robustness. In case an unexpected exception occurs, developers commonly write a code block as follows:

try
{
  // Do something
}
catch (Exception ex)
{
  // Log the exception
  // Notify the user about the exception
}

That code block is very often duplicated everywhere in the project. It is obviously not a good coding practice. Instead of duplicating, we should extract and promote it as a subroutine. That way, we can gain the following advantages:

  1. More maintainable; if the exception handling is kept in a single place, it is easy to apply future modifications.
  2. More productive; less amount of code to write (or copy) means less coding time and less possibility of error.
  3. Separation of concern; each routine will be much clearer since it is not polluted with exception handling, logging, and notification code blocks.

Centralized exception handling implementation

If you already have or willing to use Microsoft Enterprise Library, there is already the Exception Handling Application Block for you to use.

But you can easily implement your own. The basic idea is create a method with your exception handling block. This method must be able to accept and execute a code block. To achieve this we can use delegate. In .NET Framework 3.5, it is even simpler with the Action delegate.

The code executes inside the try block, while in the catch block, all necessary treatments (logging and notification) can be added.

The following is a sample skeleton of the implementation built as a method called TryExecute:

void TryExecute(Action code)
{
  try
  {
    code(); // Execute the passed code
  }
  catch (Exception ex)
  {
    // Log the exception
    // Notify the user
    // Add more things as required
  }
}

Then, in your client code, you can just call it as follows:

void SomeMethod()
{
  // Send the code inside the block to the TryExecute() method.
  TryExecute(() =>
  {
    // Do something
  });
}

Easy, right?

C# constants best practice

In C# there are two way to define constants, using const and readonly. Some may say that there is the enum keyword, but it’s actually a group of const. In case you don’t know, there are some important differences between these two keywords:

const readonly
It is always a static class member. It can be a static or instance class member.
The value is evaluated at compile time. Therefore, the only
possible values for constants of reference types are string and null.
The value is evaluated at run time and embedded to every assembly that uses it. Therefore, the values for
readonly fields can be the output of method calls.
It has to be initialized at the declaration. It can be initialized at the declaration or the class constructor.
It can be used to construct enumerated values. It cannot be used to construct enumerated values.
It can be used to construct attributes. It cannot be used to construct attributes.

Based on the differences, we can establish a practice when to use const and readonly.

Use const:

  1. To construct enumerated values.
  2. To construct attributes.
  3. When you are sure that the value will never change between releases, for example, mathematical constants (pi, Euler’s number, golden ratio, and so on).
  4. When declared inside a class with internal modifier. The internal modifier ensures the fields cannot be used in another assembly, thus eliminating versioning issues when the value is changed.

Use readonly:

  1. When you need to assign the value with an output of a function.
  2. When you need to assign the value in the constructor.
  3. When the fields are going to be used by other assemblies. This prevents the value from being embedded to the assembly, hence there will be no issues even if the value of the fields are changed.
  4. When declared inside a class with public modifier. The public modifier indicates that the class is available to be used by other assemblies, hence there can be a versioning issue if const is used instead of readonly.

System.Net.WebException: An exception occurred during a WebClient request

When using either WebClient or HttpWebRequest to download file from a remote location, sometimes I got the following exception:

System.Net.WebException: An exception occurred during a WebClient request

For some reasons, IIS (the Web server) may deny to serve a request that doesn’t specify the user-agent property in the request header. So, although it’s not really obvious, this can be solved pretty easily by specifying the particular user-agent property. You can set it to anything, it doesn’t matter as long as it exists.

For example, here how you provide the property using WebClient:

using (var wc = new WebClient())
{
	wc.Credentials = CredentialCache.DefaultCredentials;
	wc.Headers.Add(HttpRequestHeader.UserAgent, "anything");
	wc.DownloadFile(fileUrlToDownload, fileNameToSafe);
}

And, here how to do it with HttpWebRequest:

var req = (HttpWebRequest)HttpWebRequest.Create(fileUrlToDownload);
req.Credentials = CredentialCache.DefaultCredentials;
req.UserAgent = "anything";
 
var resp = (HttpWebResponse)req.GetResponse();
 
using (var stream = resp.GetResponseStream())
{
	using (var fstream = new FileStream(fileNameToSafe)
	{
		var buffer = new byte[8192];
		var maxCount = buffer.Length;
		int count;
		while ((count = stream.Read(buffer, 0, maxCount)) > 0)
			fstream.Write(buffer, 0, count);
	}
}
 
resp.Close();

You may also notice that downloading a file using WebClient is much simpler than using HttpWebRequest. The later, however, gives you much more control.