Evil Code #010 : Extension Methods

Back with Evil Code Series again. What would be the output of the following.

void Main()
{
PrintToString("SampleText");
PrintToDescription("SampleText");
PrintToString(null);
PrintToDescription(null);
}
public void PrintToString(string valueToPrint)
{
Console.WriteLine($"Printing From {nameof(PrintToString)} : {valueToPrint.ToString()}");
}

public void PrintToDescription(string valueToPrint)
{
Console.WriteLine($"Printing From {nameof(PrintToDescription)} : {valueToPrint.ToDescription()}");
}

public static class Extensions
{
public static string ToDescription(this string source)
{
return $"Description = {source??"Null"}";
}
}

The code attempts to prints 2 set of data, “SampleText” and Null Value. The PrintToString method, prints the output from the inbuild ToString() method, while the second method PrintToDescription, prints the output from an extension method.

The extension method, as such, doesn’t do anything fancy. It merely adds a prefix to the string (if not null or prints null).

It would be natural to expect the firs two method calls to print normally and then the last two calls, with null as paramter, to throw exceptions. But this is where things to change and expose the functioning of Extension methods.

While the extension methods work quite similiar to instance method, there is one fundamental difference. It has ability to execute even if the source instance if null.

In our given code, in the final call to PrintToDescription, even with a null paramter, the extension method is invoked, while the PrintToString would throw an exception as soon as null.ToString is encountered.

The output of the above code would be as following.

1. Printing From PrintToString : SampleText
2. Printing From PrintToDescription : Description = SampleText
3. // Throws Exception
4. Printing From PrintToDescription : Description = Null

Json Recipies – Part 2

Continuing with our earlier post on Json Recipies, let’s explore couple of quick reference recipes using the famous NewtonSoft.Json.

Recipe 04: Deserialize to Anonymous Type

One of the least explored feature in NewtonSoft is the ability to deserialize a Json to anonymous type. For example,

var json = @"{'Name':'anu viswan','Location':'india'}";
var anonymousType = new {Name = string.Empty, Location = string.Empty};

var result = JsonConvert.DeserializeAnonymousType(json, anonymousType);
Console.WriteLine($"Name : {result.Name}, Location:{result.Location}");

This would produce an output as

Name : anu viswan, Location:india

Isn’t that quite useful. You can now deserialize json directly to anonymous types, avoiding the need to declare a type for the purpose or going through tedious task of exploring the JObject. I believe this functionality is quite underused.

Recipe 05: Formatting Json as camelCase.

What if you come across a situation wherein, you want to format the Json with keys in camelCase. For example, consider the following json.

{'FirstName':'Anu','LastName':'Viswan','Age':35}

You would like to format the json such that the keys are rewritten as firstName,lastName and age. This is where CamelCasePropertyNamesContractResolver comes into picture. You could set the ContractResolver to CamelCasePropertyNamesContractResolver using the following.

var json = @"{'FirstName':'Anu','LastName':'Viswan','Age':35}";
var student = JsonConvert.DeserializeObject(json);
var camelSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var result = JsonConvert.SerializeObject(student,camelSettings);

Where Student is defined as

public class Student
{
public string FirstName{get;set;}
public string LastName{get;set;}
public int Age{get;set;}
}

This would format the json string with all keys in camelCase.

So far, we have examined a simple json. Let’s expand the example for a complex nested version that happens to have a property of Type object, which encapsulate the nested json part. For example, what if the json in question is as follows

{"FirstName":"Anu","LastName":"Viswan","age":35,"SkillSet":{"ProgrammingLanguages":"C#,Dart","Database":"Sql Server,MySql,MongoDb"}}

This is where things get interesting. If you were to define a Property of Type Object in the Student Class, you could be suprised that the inner object wasn’t camelCased. Let’s check by adding a Property called SkillSet of Type object in Student.

public class Student
{
public string FirstName{get;set;}
public string LastName{get;set;}
public int Age{get;set;}
public object SkillSet{get;set;}
}

If we were to run the client code using CamelCasePropertyNamesContractResolver as described above, the output would be as following.

{"firstName":"Anu","lastName":"Viswan","age":35,"skillSet":{"ProgrammingLanguages":"C#,Dart","Database":"Sql Server,MySql,MongoDb"}}

As you can observe, the inner Object didn’t have its keys formatted with CamelCase.

The trick lies in most unexpected corner. Infact, you do not even need the Student Class. All you need is the ExpandoObject. Let’s rewrite the client code using ExpandoObject.

var json = @"{'FirstName':'Anu','LastName':'Viswan','Age':35, SkillSet:{ProgrammingLanguages:'C#,Dart',Database:'Sql Server,MySql,MongoDb'}}";
var student = JsonConvert.DeserializeObject(json);

var camelSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var result = JsonConvert.SerializeObject(student,camelSettings);

That’s all the magic you needed. Now the formatting for inner Object is magically fixed.

{"firstName":"Anu","lastName":"Viswan","age":35,"skillSet":{"programmingLanguages":"C#,Dart","database":"Sql Server,MySql,MongoDb"}}

Recipe 06: Search and Replace using JObject.

There might be situations which forces you to use JObject for parsing json. Yes, it is inconvenient way of doing it, but sometimes you need to walk the hard path ( or should I say, sometimes JObject is the most convenient option).

How could you search and replace a token in JObject, especially if you do not know the names of parent node. For example, let us consider the following two json strings.

{'Fields' : { 'CA' : 'P' , 'MA' : { 'COLL': 'Q'} } }
{'Item' : { 'PA' : 'P' , 'VA' : { 'COLL': 'D'} } }

You are supposed to update the Value of COLL. However, as you can observe from the two Jsons available, the parents nodes are different.

Updating COLL would have been tough task. But there are few interesting methods in JObject makes our life easier.

To Select the COL token in either of the Json, you could use the SelectToken method

jobject.SelectToken("$..COLL");

For updating the value, you could use the Replace method. For example,

jobject.SelectToken("$..COLL").Replace(1);

That would give use the output we require. The output of above given samples would be as follows.

// Example 1
{
"Fields": {
"CA": "P",
"MA": {
"COLL": 1
}
}
}

// Example 2
{
"Item": {
"PA": "P",
"VA": {
"COLL": 1
}
}
}

Non-Blinking Caret in WPF Textbox

A recent question I came across recently was “How could one stop the caret in a WPF Textbox from blinking ?“.

My first instinct drove me in the direction of HideCaret method, but quickly realized WPF applications doesn’t allow you to get the Handle for individual controls. It only provides handles for Windows. This was quite unlike WinForm applications and ruled out usage of HideCaret API as it requires Handle for the control to disable the Caret.

The next solution I came up with ( and am still sticking on to it until i get a better one) was to emulate the behavior. What if it was possible to disable the original caret and mock the behavior using something else. The first part of the challenge was pretty easy, you could set the CaretBursh property to a Transparent color and the original Caret is hidden.

<TextBox x:Name="txtName" CaretBrush="Transparent" />

But the more important question was how to mock the caret. The solution lies in using a Canvas and Border overlaying the Textbox to emulate the caret. Let’s update our XAML first.

<Grid>
<TextBox x:Name="txtName" CaretBrush="Transparent" />
<Canvas>
<Border x:Name="Caret" Visibility="Collapsed" Canvas.Left="0" Canvas.Top="0" Width="1" Height="15" Background="Black"/>
</Canvas>
</Grid>

The final act of the trick involves writing a bit of code-behind logic.

txtName.SelectionChanged += (sender, e) => MoveCustomCaret();
txtName.LostFocus += (sender, e) => Caret.Visibility = Visibility.Collapsed;
txtName.GotFocus += (sender, e) => Caret.Visibility = Visibility.Visible;

Where the MoveCustomCaret is defined as

private void MoveCustomCaret()
{
var caretLocation = txtName.GetRectFromCharacterIndex(txtName.CaretIndex).Location;

if (!double.IsInfinity(caretLocation.X))
{
Canvas.SetLeft(Caret, caretLocation.X);
}

if (!double.IsInfinity(caretLocation.Y))
{
Canvas.SetTop(Caret, caretLocation.Y);
}
}

And now you have your non-blinking caret in textbox ready. Here is a screenshot of the control.

sample1

If you have a better solution, please let me know. That would be interesting to learn.

Type Argument Inference during Type Initialization

One of the least discussed topics about compiler and Generic Methods is its ability to infer the Type Arguments. For example, consider the following code.

public void Display<T>(T value)
{
Console.WriteLine(value);
}

A typical invocation of the code might look like following.

var value = 45;
Display<int>(value);

However, in some scenarios as above, the compiler is smart enough to allow you to skip the type argument from the generic method. For example, you could call the method as the following.

var value = 45;
Display(value);

This is because the compiler realizes you have passed an integer value as argument and it infers the type argument T as Int32.

This is great feature to have and allows you to do away with a lot of ceremony. However, the type inference is limited to Methods and doesn’t quite help you in Type Initialization. For example,

public class MyClass<T>
{

}

For initializing the above class, you would have to explicitly mention the Type Argument.

var instance = new MyClass<int>();

However, having said that, there is a easy-to-use pattern to work around the issue. If you were to inspect the Tuple static class, you might find some interesting methods there.

For example,

public static Tuple<T1> Create<T1>(T1 item1)
{
return new Tuple<T1>(item1);
}
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
{
return new Tuple<T1, T2>(item1, item2);
}

In the first glance, you might be temped to question the intend of the methods. What would one create a static method to create instances, when you could call the constructor directly. However, when closely examined, this is a great example of how to make type inference possible during initialization.

For example, for initializing a Tuple<int,int> using the constructor, you would have to pass the type arguments.

var instance = new Tuple<int,int>(3,4);
var instance = new Tuple(3,4); // This doesn't compile

However, the presence of static methods allows you to create the instance without passing the type arguments.

var instance = Tuple.Create(3,4);

This is a easy-to-use pattern if you ever want to support Type inference during initialization. Looking back at our sample class, we could now create helper methods as following.

public static class MyClass
{
public static MyClass<T> Create<T>(T value)
{
return new MyClass<T>();
}
}

The initialization code could now skip the type arguments, just like with the Tuples.

var instance = MyClass.Create(4);

C# over the years has reduced ceremony and boiler plate code and type inference is one yet another way to achieve the same.

SOLID : Liskov Substitution Principle (Part 1)

The “L” in SOLID stands for Liskov Substitution Principle, named after Barbara Liskov, who initially introduced in 1987 keynote address. LSP provides guidelines for creating inheritence heirachy where a client can use any class or subclass without breaking the expected behavior.

We will begin by looking at the official definition first.

If S is a subtype of T, then objects of type T may be replaced with objects of type S,without breaking the program.

It would be unwise to explain this theoratically, hence like always, let hit the Visual Studio and write some code. I would like borrow an example given by Tim Correy in his famous video.

Assume we have an Employee class defined as follows.

public class Employee
{
public string Name{get;set;}
public Employee AssignedManager{get;protected set;}
public virtual double GetPay()
{
var currentSalary = 500;
Console.WriteLine($"Current Pay {currentSalary}");
return currentSalary;
}

public virtual void AssignManager(Employee manager)
{
Console.WriteLine("Manager Assigned");
AssignedManager = manager;
}
}

Now let’s assume we have a Manager class, which inherits from Employee

public class Manager:Employee
{
public override double GetPay()
{
var currentSalary = 750;
Console.WriteLine($"Current Pay {currentSalary}");
return currentSalary;
}

public override void AssignManager(Employee manager)
{
Console.WriteLine("Manager Assigned");
AssignedManager = manager;
}
}

Let’s write some client code now which consumes these classes.

var manager = new Manager();
manager.Name = "John Doe";
manager.GetPay();

var programmer = new Employee();
programmer.Name = "Roel Doel";
programmer.GetPay();
programmer.AssignManager(manager);

Output

Current Pay 750
Current Pay 500
Manager Assigned

As you can observe, the output is perfectly fine. Let us try making some changes to the Client Code now. Let us replace the Employee class (programmer instance) with Manager.

var manager = new Manager();
manager.Name = "John Doe";
manager.GetPay();

var programmer = new Manager();
programmer.Name = "Roel Doel";
programmer.GetPay();
programmer.AssignManager(manager);

Output

Current Pay 750
Current Pay 750
Manager Assigned

This has turned out fine as well. Yes the output is different, which is expected considering the Pay for Manager and Employee are different, but the client hasn’t behaved unexpectedly. Let’s write one more class, inheriting from Employee and call it CEO.

public class CEO:Employee
{
public override double GetPay()
{
var currentSalary = 750;
Console.WriteLine($"Current Pay {currentSalary}");
return currentSalary;
}

public override void AssignManager(Employee manager)
{
throw new Exception("Am the CEO, no Manager for me !!");
}
}

The difference this time is of course the CEO doesn’t have a Manager and it raises an exception in the AssignManager method. Let’s head back to out Client code and replace Employee with CEO in our original code.

var manager = new Manager();
manager.Name = "John Doe";
manager.GetPay();

var programmer = new CEO();
programmer.Name = "Roel Doel";
programmer.GetPay();
programmer.AssignManager(manager);

Output

Exception:Am the CEO, no Manager for me !!

Aha, we have an exception here. When replaced the Employee (Base type) with a subtype (CEO), the expected behavior of program has been broken. This is a violation of LSP.

Let’s examine the violation further. It is often said that Inheritence is the IS-A relation. However, if you truely examine CEO and Employee, do they follow a IS-A relation in every sense ? Not really, not according the current definition of Employee. Yes, that is right. The problem doesn’t quite lie in CEO, but it originate from the definition of Employee class. While designing the Employee class, we “assumed” that all Employees would have a manager.

So what is the best solution for this scenario ? What if we were to ensure the Employee class had only those functionalities which are common to every employee ? Obviously, the Manager is not applicable for everyone, so let’s remove it and create an interface which contains only the basic employee functionalities.

public interface IBaseEmployee
{
string Name{get;set;}
double GetPay();
}

public abstract class BaseEmployee:IBaseEmployee
{
public string Name{get;set;}
public virtual double GetPay(){ return 0;}
}

Remember, we still have to consider the Manager assignment. What we would do here is define another interface IHasManager, which would wrap the functionalities required for Employees who has Manager.

public interface IHasManager
{
IBaseEmployee AssignedManager{get;set;}
void AssignManager(IBaseEmployee manager);
}

Let’s now define our Employee and Manager classes.

public class Employee:BaseEmployee,IHasManager
{
public IBaseEmployee AssignedManager{get; set;}
public override double GetPay()
{
var currentSalary = 500;
Console.WriteLine($"Current Pay {currentSalary}");
return currentSalary;
}

public virtual void AssignManager(IBaseEmployee manager)
{
Console.WriteLine("Manager Assigned");
AssignedManager = manager;
}

}

public class Manager:BaseEmployee,IHasManager
{
public IBaseEmployee AssignedManager{get; set;}
public override double GetPay()
{
var currentSalary = 750;
Console.WriteLine($"Current Pay {currentSalary}");
return currentSalary;
}

public void AssignManager(IBaseEmployee manager)
{
Console.WriteLine("Manager Assigned");
AssignedManager = manager;
}
}

As you can see, the Manager and Employee inherits from BaseEmployee and implements the IHasManager interface. The next step is to define our CEO Class, and this time, we know that he doesn’t need a Manager.

public class CEO:BaseEmployee
{

public override double GetPay()
{
var currentSalary = 750;
Console.WriteLine($"Current Pay {currentSalary}");
return currentSalary;
}

}

That’s it. Let’s rewrite our Client code now.

var manager = new Manager();
manager.Name = "John Doe";
manager.GetPay();

var programmer = new Employee();
programmer.Name = "Roel Doel";
programmer.GetPay();
programmer.AssignManager(manager);

The above code compiles and executes as expected. Let’s replace the Employee with a Manager first.

var manager = new Manager();
manager.Name = "John Doe";
manager.GetPay();

var programmer = new Manager();
programmer.Name = "Roel Doel";
programmer.GetPay();
programmer.AssignManager(manager);

That works fine as well. Let’s try again, and this time replace with CEO.

var manager = new Manager();
manager.Name = "John Doe";
manager.GetPay();

var programmer = new CEO();
programmer.Name = "Roel Doel";
programmer.GetPay();
programmer.AssignManager(manager);

Not surprisingly, that doesn’t compile at all. CEO doesn’t have the AssignManager method as it doesn’t implement the IHasManager interface. Your client no longer have unexpected behavior as such errors are caught during compilation.

That was pretty easy, isn’t it ? But we are not done yet. There is more to the definition of LSP. In the next part of this series, we will examine the Contact and Variance rules which must be followed for LSP compliance.

Evil Code #009 : nameof Operator

The nameof() operator has been so commonly used by the developers that one could not be called guilty if he assumes it was there since C# was born. Despite that, there are days it might still surprise you.

What would be your reply if I asked you to predict the output of the following.

nameof(School.Division.Student)

No prizes for guessing. It wouldn’t be hard to guess that the output would be “Student”. So what is the surprise factor.

Let me add some more constraint to the code. What could be the output is the code was compiled on Visual Studio 2017, v15.5.x ? Would your answer change ?

If you were to say that you answer would still be the same, then here is the surprise for you. This is a bug on the C# compiler, which results in compiler error when you use nested properties /sub expression of the format X.Y.Z.

CS0120: An object reference is required for the non-static field, method, or property 'C.Instance'

This bug was fixed in 15.7.x, and anyone using a Visual Studio with version 15.7.x or above, would be able to see the desired result of “Student”.

If you are one of those lucky ones as yours truely, then you are in for an unusual compiler error. If you are interested to read more on the issue, please follow the issue on Github here.

GOF: Composite Pattern

Composite Pattern, in a way, literally takes of from where Decorator Pattern ends. One might be inclined to think of it as a specialized case of Decorator Pattern which composes one or more instances of similiar objects and manipulate them uniformly. This allows the client to work on a single entity or composition of entity uniformily, or in other words, it eliminates the need of programmers to discriminate between leaf and branch, and thereby avoid writing specific logic to handle both scenarios.

The key components of Composite Pattern can be defined as follows

Component
Components defines the interface that specifies the behavior that needs to be uniformly executed by primitive object or composite object.

Leaf
The non-decomposible leaf object, which defines the behavior for the primitive object

Composite
Holds the collection of Child components, and implements the behavior of components that have children.

That would be enough of theory, let’s write some code now. For the sake of example, we will write a little program that would print the size of given File/Directory. Let’s begin by defining the Component interface.

public interface IMetaInfo
{
double GetSize();
}

The next step would be define the behavior of the primitive object, which in this case would be the File.

public class FileObject : IMetaInfo
{
private string _fileName;
public FileObject(string fileName)
{
_fileName = fileName;
}
public double GetSize()
{
Console.WriteLine($"Calculating size of {_fileName}");
return 0;
}
}

As one can understand, the actual behavior is different for File and Directory. The size of Directory needs to be cumiliative size of all the individual Files in it. Let’s define the behavior for Directory Class now.

public class DirectoryObject : IMetaInfo
{
private string _directoryName;
private List<IMetaInfo> _fileCollection;
public DirectoryObject(string directoryName)
{
_directoryName = directoryName;
_fileCollection = new List<IMetaInfo>();
}

public void Add(IMetaInfo file)
{
_fileCollection.Add(file);
}

public void Remove(IMetaInfo file)
{
_fileCollection.Remove(file);
}
public double GetSize()
{
var directorySize = 0d;
foreach (var file in _fileCollection)
{
directorySize += file.GetSize();
}
return directorySize;
}
}

As one could see in the example code, the Directory Structure uses the bahavior of the individual File Structure to calculate the cumiliative Size. Let’s write the code for Client now and see how client can work without having the knowledge of what exactly it is dealing with.

class Client
{
static void Main(string[] args)
{
Console.WriteLine("When using Composite Object");
var directoryInstance = new DirectoryObject("BaseDirectyory");
for(var i = 0; i < 10; i++)
{
directoryInstance.Add(new FileObject($"{i.ToString()}_File"));
}

GetSize(directoryInstance);

Console.WriteLine("When using Component Object");
var fileInstance = new FileObject("Another File Instance");
GetSize(fileInstance);
Console.ReadLine();
}

private static void GetSize(IMetaInfo instance)
{
instance.GetSize();
}
}

The Client.GetSize() method accepts an instance of IMetaInfo as the parameter. It doesn’t really know whether it is actually dealing with a Composite object or a Primitive one.

The Composite pattern is a highly useful pattern when one needs to deal with a irregular structure of objects and composite of objects, enabling the client to deal with them uniformly.

The entire source code shown in this example are available in my GitHub.