Suppressed Exception On The Empty Catch Block

When you investigate an issue or a problem you usually get the error or exception message first and then try to replicate that exception in a lower environment such as your local machine. What if there was an error but the application did not produced a message or even a trace where the error occurred? Big problem. One such case to avoid this problem and to avoid passing this problem to the next person that will support your application, is to avoid having suppressed exception on the empty catch block on your code. Yes, having an empty catch block will not be detected by the C# compiler, bummer.

The culprit

public class SilentExceptionSample
{

public void DivideOperation(int a, int b)
{
try
{
var result = a / b;
}
catch (Exception)
{
//throw;
}

}

}

The code above is a sample method that does not return anything (void) and an operation to divide a and b. A try catch block will be able to catch any exception that may happen but throwing the exception that may happen is a different scenario. Inside the catch block, the C# compiler allows the block to be empty and not return anything. Most of the time this block can contain a logic to handle the exception such as logging and external error handlers. What happens if the developer leaves the block empty without the intention of leaving it empty? Errors in your application will not have any trace.

Some unit testing

[TestFixture]
public class SuppressedExceptions
{

[Test]
public void Division_With_Exception_Test() {

var silentException = new SilentExceptionSample();

Assert.Throws(() => silentException.DivideOperation(1,0));
}

[Test]
public void Division_With_NoException_Test()
{
var silentException = new SilentExceptionSample();

Assert.DoesNotThrow(() => silentException.DivideOperation(1,1));
}

}

I created a unit test to test the exception, on this sample above its the DivideByZeroException, that the method will throw when you divide a number by zero. The test fails in the first scenario since the error suppressed exception on the empty catch block.

Test Results

Ways to avoid

There can be ways to avoid this code smell. I suggest the following…

Unit Test

– Perform unit tests on exception handling on your code.

Code Snippet

– Use the code snippets on Visual Studio. If you want to use a try catch block, typing in “try” then tab will auto complete the whole block.

Resharper

– Tools such as Resharper can help in detecting code smells. See the warning below from the Resharper engine on the empty catch block.
Resharper Warning

This type of code smell can be the source of problem you are investigating now or something you can prevent while in development. You’ve been warned! 🙂

How To Transfer App.Config ApplicationSettings to Web.config

Add Web Reference from a class library for .Net 2.0

If you still use .Net framework 2.0, the way to reference a web service to your project is to add a Web Reference.
What if you want to add the web reference from a class library project? This will result to Visual Studio automatically
adding an app.config to your project. The app.config will contain the configuration under applicationSettings of the newly added reference of the web service.

Add Web Reference - ApplicationSettings

Add Web Reference

The app.config will look like this for example.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Noel.Sample.ServiceInterface.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Noel.Sample.ServiceInterface.Properties.Settings>
<setting name="Noel_Sample_ServiceInterface_ServiceHello_Service"
serializeAs="String">
<value>http://localhost:59962/Service.asmx</value>
</setting>
</Noel.Sample.ServiceInterface.Properties.Settings>
</applicationSettings>
</configuration>

What if you want to use one config file?

Your main application is a web application and it has its own web.config file. What if you want to use and maintain one
config file? You don’t need to point the app.config section from your web.config file. You can move the section group and
the section of the web service from your app.config to your web.config.

Move app.config applicationSettings to Web.config

<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework,
Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Noel.Sample.ServiceInterface.Properties.Settings"
type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Noel.Sample.ServiceInterface.Properties.Settings>
<setting name="Noel_Sample_ServiceInterface_ServiceHello_Service"
serializeAs="String">
<value>http://localhost:59962/Service.asmx</value>
</setting>
</Noel.Sample.ServiceInterface.Properties.Settings>
</applicationSettings>
</configuration>

The section group can be added to the configSections. The applicationSettings can be added under the configuration section of the web.config.

Get value of service URL from Web.Config under applicationSettings

Under appSettings of a Web.config file usually you use for example ConfigurationManager.AppSettings[“WebServiceURL”] to get a value in the Web.config. But when the URL is under the applicationSettings in a Web.config this is how you can get the value of the URL.

public class ConfigHelper
{
public string GetUrl()
{
var section = (ClientSettingsSection)ConfigurationManager.
GetSection("applicationSettings/Noel.Sample.ServiceInterface.Properties.Settings");
var url = section.Settings.Get("Noel_Sample_ServiceInterface_ServiceHello_Service").Value.ValueXml.InnerText;
return url;
}

}

The last step is to remove the app.config from the class library. This is the case if the app.config was added to have the configuration of the web reference. In other cases where you need to the app.config, just remove the configSections and applicationSettings for the web service.

I spent some time looking for a way to make this work and not too much resource from web points to this approach. Hopefully it can help solving yours in less time. Thank you for this post from Stackoverflow on how solve this problem.

Comparing using CompareTo C# Method

 

A colleague asked me for a suggestion on the program module he is doing that involves determining if one value is “>” greater than, “=” equal or “<” less than another value. I first thought of a solution involving a stack but its too low level and involves much longer code. After some suggestions and trying to think of another way, he came across of a solution to use CompareTo C# method.

What is CompareTo C# Method?

First, MSDN defines IComparable as an interface that “Defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances.” It has a method called CompareTo which as defined by MSDN “Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.”

The CompareTo method is available on all objects as long as the objects has the same type. See the sample code below for comparing value types integer and a string type.

CsharpCompareTo

 

The Return Value of CompareTo

The CompareTo method has a return value of int. The integer value return will be one of the values less than 0, 0 or greater than zero as what is shown below.

CompareToReturnValues

 

Nullable Types Does Not Implement CompareTo

Take note that Nullable types like int? short for Nullable<int> does not implement the CompareTo method. It will not even compile since the method is not implemented.

CompareToNullable

This blog post will serve as a quick reference for me whenever there is a need for me to use sorting or comparison of data when programming. I hope it will serve the same for you.