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

Collection of Custom Configuration

Adding application configuration in app.config, especially under the appSetting key is something which every developer is used to.

 <appSettings>
<add key="Version" value="1.0" />
<add key="AutoSave" value="True" />
<add key="LoadOnWindowsStartUp" value="True" />
</appSettings>

What if we need to add our own customer collection. For example,

 <PluginSettings>
<Plugins>
<Plugin ID="906260f8-57ab-417a-8d83-015c73f4a5c8" IsEnabled="true"></Plugin>
<Plugin ID="906260f8-57ab-417a-8d83-015c73f4a5c9" IsEnabled="true"></Plugin>
</Plugins>
</PluginSettings>

That’s when we need to write up code to define these customized segments. We will begin with the basic element first, which in this case is


<Plugin ID="906260f8-57ab-417a-8d83-015c73f4a5c8" IsEnabled="true"></Plugin>

As seen, the basic element has two properties, a GUID named ID and a boolean value called IsEnabled. Let’s go ahead and define them. Our custom class needs to inherit from ConfigurationElement Class.


public class PluginConfigurationElement:ConfigurationElement
 {
 private const string XML_PLUGIN_ID = "ID";
 private const string XML_TITLE = "Title";
 private const string XML_IS_ENABLED = "IsEnabled";

[ConfigurationProperty(XML_PLUGIN_ID,IsRequired =true,IsKey =true)]
 public Guid ID
 {
 get
 {
 return (Guid)this[XML_PLUGIN_ID];
 }
 set
 {
 this[XML_PLUGIN_ID] = value;
 }
 }
 [ConfigurationProperty(XML_IS_ENABLED, IsRequired = true, DefaultValue =false)]
 public bool IsEnabled
 {
 get
 {
 return (bool)this[XML_IS_ENABLED];
 }
 set
 {
 this[XML_IS_ENABLED] = value;
 }
 }
 }

As seen in the example configuration, what we need is a collection of the defined Basic element. We will go ahead and define the collection now. Similar to basic element, we have a base class to inherit from.


public class PluginCollection:ConfigurationElementCollection
 {
internal const string PropertyName = "Plugin";

public override ConfigurationElementCollectionType CollectionType
 {
 get
 {
 return ConfigurationElementCollectionType.BasicMapAlternate;
 }
 }
 protected override string ElementName
 {
 get
 {
 return PropertyName;
 }
 }
 protected override bool IsElementName(string elementName)= elementName.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase);
 public override bool IsReadOnly() = false;
 protected override ConfigurationElement CreateNewElement()= new PluginConfigurationElement();
 protected override object GetElementKey(ConfigurationElement element) = ((PluginConfigurationElement)(element)).ID;
 protected override void BaseAdd(ConfigurationElement element) = base.BaseAdd((PluginConfigurationElement)element);

public void Add(PluginConfigurationElement element) = this.BaseAdd(element);
 public void Remove(Guid Key) = this.BaseRemove(Key);
 public void Clear() = this.BaseClear();

public PluginConfigurationElement this[int idx]
 {
 get
 {
 return (PluginConfigurationElement)BaseGet(idx);
 }
 }

 }

The final class we need to define is the actual Section itself.


public class PluginSection:ConfigurationSection
 {

 private const string XML_PLUGINS = "Plugins";

 [ConfigurationProperty(XML_PLUGINS)]
 public PluginCollection Plugins
 {
 get { return ((PluginCollection)(base[XML_PLUGINS])); }
 set { base[XML_PLUGINS] = value; }
 }
}

We are almost ready now. The final step required is to reference the class in app.config.


<configSections>
<section name="PluginSettings" type="MyNamespace.PluginSection, MyNamespace " />
</configSections>

Make sure you put this as the first step in app.config, right below the root element . Now you are all set to write your own configuration. Happy Coding.

An Introduction to EcSolvo.RestHelper

This post intends to act as an introductory guide on the EcSolvo.RestHelper Nuget. It takes you through the Main Methods that you would be using in your routine tasks.

RestHelper Constructor and ExecuteAsync

The RestHelper Constructor and ExecuteAsync Method is the heart of RestHelper Library. It is build on ‘Pit of Success’ philosophy, removing possible erroneous steps by the consuming Developer.
The RestHelper Constructor takes a single Parameter, which is the base address of your API.The ExecuteAsync is an Asynchronous Method which take in two Parameters,
a) HTTP Verb (GET,POST)
b) Resource (URL to the exact API Resource)

For GET Request

For Handling URI Parameters, the EcSolvo.RestHelper Library exposes a method called ‘AddURLParameters’, which helps to add parameters to the QueryString dictionary.


private string _BaseAddress = "http://localhost:8888/";
var resourceURL = "api/user/SingleParamStringResponse";
var restHelper = new EcSolvo.RestHelper(_BaseAddress);
string ParameterKey = "VariableStr";
string ParameterValue = "DummyString";
restHelper.AddURLParameters(ParameterKey, ParameterValue);
var result = await restHelper.ExecuteAsync<string>(HttpMethod.Get, resourceURL);

The library works even if the parameter passed is a Complex Parameter (Controller uses FromUri Attribute).

For POST Request

For Handling OnBody Parameter in POST Request, the library exposes a method called ‘AssignMessageBodyParameter’.


restHelper.AssignMessageBodyParameter(Parameter);
var result = await restHelper.ExecuteAsync<string>(HttpMethod.Post, resourceURL);

If the POST Request have additional URI Parameters, it can use the ‘AddURLParameters’ Method to add it to the dictionary.

EcSolvo.RestHelper Nuget

Recently I have started working on a Nuget Package for providing a is a sleek and simple Wrapper library for providing simple access to Rest API, by hiding away the complexities of HTTPClient Class.Named EcSolvo.RestHelper it is particularly designed to work along with Xamarin PCL Projects

You can follow and contribute to the Nuget in Github : Link to GitHub Repository

Follow updates on Nuget : Link To Nuget

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.