Back to Basics #002

Continuing with our series of subtle changes that make differences, let’s look into Conditional Attributes over Directives.

static void Main(string[] args)
{
Method01();
Method02();

Queue queue = new Queue();
queue.Enqueue("One");
queue.Enqueue("Two");
queue.Enqueue("Three");

Method03(queue.Dequeue());
Console.WriteLine(queue.Count);
Console.WriteLine("All Done");
Console.ReadLine();
}

// Approach One
private static void Method01()
{
#if DEBUG
Console.WriteLine("Hello Method01");
#endif
}
[Conditional("DEBUG")]
private static void Method02()
{
Console.WriteLine("Hello Method02");
}

[Conditional("DEBUG")]
private static void Method03(string Value)
{
Console.WriteLine(Value);
}

What would be the output of above code under
a) Debug Mode
b) Release Mode

The Debug Mode should be easy and as expected

Hello Method01
Hello Method02
One
2
All Done

What about release mode ?
3
All Done

You might have a tendency to say “2”, considering you might expect the dequeue statement to be executed. However, that is not the case. The dequeue is not called either because the result is not used as the method is not called.This leads to unexpected errors .
This is one the reasons why it is recommended not to decorate a method that accepts parameter with conditional Attributes.

Advertisements

Back to Basics #001

Welcome to first post on ‘Back to basics’. Yeah, as you guessed right, this series attempt to check minor differences in our understanding of basic concepts.

Predict the output of following.


public class FirstType
{

}
public class SecondType
{
private FirstType _mType;

public static implicit operator FirstType(SecondType t)
{
return t._mType;
}
}

static void Main(string[] args)
{
object objectInstance = new SecondType();

FirstType attempt1 = objectInstance as FirstType;
if (attempt1 != null)
{
Console.WriteLine("'As' Conversion Succeeded");
}
else
{
Console.WriteLine("'As' Conversion Failed");
}

try
{
FirstType attempt2 = (FirstType)objectInstance;
Console.WriteLine("Cast Succeeded");
}
catch (Exception)
{
Console.WriteLine("Cast Failed");
}

}

Ideally, One would expect the first attempt to fail, but would feel the second would succeed considering we have implemented implicit conversion. But unfortunately, that’s not the case. The output would be

‘As’ Conversion Failed.
Cast Failed.

The reason for this is that, the compiler generates code based on the compile time type of the objectInstance, which in this case is ‘object’. It then checks if there is any conversion declared to convert object to FirstType, which doesn’t exist. The compiler doesn’t check the type of the objectInstance during runtime, which results in the above output.

The reason for this is that, the compiler generates code based on the compile time type of the objectInstance, which in this case is ‘object’. It then checks if there is any conversion declared to convert object to FirstType, which doesn’t exist. The compiler doesn’t check the type of the objectInstance during runtime, which results in the above output.

Updated

The behavior is even more tricky when we change the type of¬†objectInstance from ‘object’ to SecondType. We would expect it to work smoothly now, however, you end up with a compiler exception this time .

“Cannot convert type ‘Cast.SecondType’ to ‘Cast.FirstType’ via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion”

This is what makes ‘as’ operators great as it provides early detection of errors. The ‘as’ operator, notices that there is a implicit conversion declared between FirstType and SecondType. However, it also recognizes that two types aren’t related by inheritance. This is the reason ‘as’ statements throws a compile-time error at this stage.

 

Adapter Pattern

There is already a large amount of literature on the Internet which discusses Adapter Pattern. However, the purpose of article is to showcase the implementations of the Adapter Pattern, rather than discussing the application of the pattern. In this post, adapter class is implemented using

1. Inheritance
2. Dependency Injection
3. Generics

Consider your old legacy code, which has a single method, GetEmployeeList.

public interface IHRSoftware
    {
        List<string> GetEmployeeNameList();
    }
    public class HRSoftware : IHRSoftware
    {
        public List<string> GetEmployeeNameList()
        {
            return new List<string>() { "Jia", "Anu", "Sreena" };
        }
    }

Client, consumes the class as follows.

            IHRSoftware hrsoft = new HRSoftware();
            foreach (var item in hrsoft.GetEmployeeNameList())
            {
                Console.WriteLine(item);
            }

Now, it so happened that the Client has gone through an overhaul and is now looking to use a new contract (interface), namely INewAgeSoftware, which exposes a property EmployeeList, replacing the GetEmployeeNameList Method. The interface declaration is as shown below.

    public interface INewAgeHRSoftware
    {
        List<string> EmployeeList { get;  }
    }

You however, would like to use your old existing code, without actually going ahead and making the changes in your legacy code. This is where adapter pattern come in handy. Following are different implementations of Adapter Class

1. Using Inheritance.

    public class AdapterWithInheritence : HRSoftware, INewAgeHRSoftware
    {
       
        public List<string> EmployeeList
        {
            get
            {
                return this.GetEmployeeNameList();
            }
        }
    }

2. Using Dependency Injection

    public class AdapterWithDI : INewAgeHRSoftware
    {
        private IHRSoftware _HRInstance;
        public AdapterWithDI(IHRSoftware HRSoftInstance)
        {
            _HRInstance = HRSoftInstance;
        }
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

3. And Finally, using Generics

    public class AdapterWithGenerics<T> : INewAgeHRSoftware where T : HRSoftware
    {
        private T _HRInstance;
        public AdapterWithGenerics(T Instance)
        {
            _HRInstance = Instance;
        }
      
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

Your new Client class would now look as follows

 Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Inheritence");
            INewAgeHRSoftware newhrsoftInheritence = new AdapterWithInheritence();
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via DI");
            INewAgeHRSoftware newhrsoftDI = new AdapterWithDI(new HRSoftware());
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
           
           
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Generics");
            INewAgeHRSoftware newhrsoftGenerics= new AdapterWithGenerics<HRSoftware>(new HRSoftware());
            foreach (var item in newhrsoftGenerics.EmployeeList)
            {
                Console.WriteLine(item);
            }

Serialize Deserialize NameValueCollection

Don’t ask me why one cannot Serialize/Deserialize a NameValueCollection, but the workaround for the same is based on conversion to dictionary. I ended up writing extension methods to NameValueCollection for serializing and deserializing the collection.

public static string JSONSerialize(this NameValueCollection _nvc)
{
return JsonConvert.SerializeObject(_nvc.AllKeys.ToDictionary(k => k, k =>_nvc.GetValues(k)));
}
public static void JSONDeserialize(this NameValueCollection _nvc,string _serializedString)
{
var deserializedobject = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(_serializedString);
foreach (var strCol in deserializedobject.Values)
foreach (var str in strCol)
_nvc.Add(deserializedobject.FirstOrDefault(x => x.Value.Contains(str)).Key, str);
}

An Introduction into Dicom using Fellow Oak

DICOM (Digital Imaging and Communication in Medicine) is probably the most common standard used for storage and exchange of Medical Images. This article provides a basic introduction on reading a Dicom File using C#.

The basic unit of a Dicom file is called an Element. Dicom Elements consists of 4 components

1. Tag
2. Value Representation
3. Value Length
4. Value Field

Tag
Tag uniquely identifies each element in the file. It consists of 2 short numbers representing the group and element.

Value Representation
Value Representation is an optional field, which defines the datatype of the element. For example,
UI – Unique Identifier
CS – Custom String
OS – Other Byte
US – Unsigned Short

Value Length
This even sized field would contain the length of the field. This field would always be even sized.

Value Field
Value Field as expected, would contain the actual value.

Reading a Dicom Element is pretty easy in C#. For this example, am using Fellow Oak Dicom Library for .Net.

Following lines of code would read the patient name out of a Dicom File using the Fellow Oak Library

 Dicom. DicomFile obj = Dicom.DicomFile .Open(FilePath);
var PatientName = obj.Dataset.Get< string>( DicomTag.PatientName, null );

The Fellow Oak Library provides a simple interface to read all Dicom Elements.

More on Dicom in next post.

Rethrow Exception

CA2200 : Rethrow to preserve stack details. That’s one recommendation that as a developer you might have seen when running Code Analysis on your solution.

So what does it mean ? What does the guilty code looks like and what is the correct way to throw exceptions. Lets start with incorrect code first.

Considering following Code.


    class Program
    {
        static void Main( string[] args)
        {
            try
            {
                new IntermediateClass().IntermediateMethod();
            }
            catch ( Exception Ex)
            {
               
                throw;
            }
        }
    }

    class IntermediateClass
    {
        public void IntermediateMethod()
        {
            try
            {
                new ErrorClass().ErrorMethod();
            }
           catch ( Exception Ex)
           {
                throw  Ex;
            }
        }
    }
    
    class ErrorClass
    {
        public void ErrorMethod()
        {
            int k = 1;
            int j = 3 / --k;
        }
    }
 

We have 3 classes, the main class which invokes a method of IntermediateClass, which in turns invokes method from ErrorClass. The ErrorMethod has been designed purposely to throw an error. It doesn’t implement an exception handling mechanism of its own, and the exception is caught by the Intermediate Class. The Intermediate Class, in turns, throws the exception back to the main class. The Code Analysis Tool has problem with this very same line, where the Intermediate Class throws the exception.

Every Exception Object contains a property called Stack Trace, which carries a list of method call hierarchy starting from the method which threw the exception to the method which caught the exception. If you were to analysis the stack trace of the exception caught in the Main Class, you would find something in similar lines.

“ExceptionHandling.IntermediateClass.IntermediateMethod() in <Path>\IntermediateClass.cs:line 21\r\n at ExceptionHandling. Program. Main (String[] args) in <Path>\Program.cs”

As you can observe, the stack trace doesn’t contains the references to the ErrorMethod, but rather it is reset and traces method starting from the point the exception is rethrown, that is from the intermediate method. In order to preserve the stack information, when you need to rethrow the exception without specifying the exception explicitly. Following would be the modification that would be required in Intermediate Method.


    class IntermediateClass
    {
        public void IntermediateMethod()
        {
            try
            {
                new ErrorClass().ErrorMethod();
            }
           catch ( Exception Ex)
           {
                throw ;
            }
        }
    }

Now if you were to view the stack trace now, the method list would look slightly different.

“ExceptionHandling.ErrorClass.ErrorMethod() in <path>\ErrorClass.cs:line 14\r\n at ExceptionHandling. IntermediateClass. IntermediateMethod() in <path>\IntermediateClass.cs:line 21\r\n at ExceptionHandling.Program.Main(String[] args) in <path>\Program.cs:line “

So next time you rethrow an exception, don’t forget to ensure the exception is not explicitly specified.