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.

 

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);
}