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.

Advertisements

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.

Batch Execution in Firebird

Executing a .sql file on Firebird Database can be quite a messy job. The lack of proper documentation and support would hurt you more when encountered issues and that is what I faced when I required to do execute contends of a .Sql File. Having understood that FbBatchExecution is the command I would required, I went to write following Function in C#.
public void ExecuteTransaction()
{
    try
    {
        if (m_cmd.Connection.State == System.Data. ConnectionState.Closed)
            m_cmd.Connection.Open();

        using ( FbTransaction fbTransaction = m_connnection.BeginTransaction())
        {
            FbScript script = new FbScript( this.ScriptFileContends);
            m_cmd.Transaction = fbTransaction;
            script.Parse();
            var BatchExecute = new FbBatchExecution(m_cmd.Connection, script);
            BatchExecute.Execute( true);
        }
    }
    catch ( Exception Ex)
    {
		throw Ex;
    }
}

This looked reasonable, I am reading out the Contends of the File using FbScript object and using the FbBatchExecution Object for bulk queries. I am managing the whole operation using FbTransaction. All seems well until I ran it and came up with following Exception.
“Execute requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized”
After hours of browsing, it turned out to be simple actually. All I needed for to add following lines.
 BatchExecute.CommandExecuting += delegate( object sender, CommandExecutingEventArgs args)
{
      args.SqlCommand.Transaction = fbTransaction;
};

The new Method would like following and you all set to go.
 public void ExecuteTransaction()
{
    try
    {
        if (m_cmd.Connection.State == System.Data. ConnectionState.Closed)
            m_cmd.Connection.Open();

        using ( FbTransaction fbTransaction = m_connnection.BeginTransaction())
        {
            FbScript script = new FbScript( this.ScriptFileContends);
            m_cmd.Transaction = fbTransaction;
            script.Parse();
            var BatchExecute = new FbBatchExecution(m_cmd.Connection, script);
			BatchExecute.CommandExecuting += delegate( object sender, CommandExecutingEventArgs args)
            {
                args.SqlCommand.Transaction = fbTransaction;
            };
            BatchExecute.Execute( true);
        }
    }
    catch ( Exception Ex)
    {
		throw Ex;
    }
}