Evil Code #008: Property Instance

It has been long since I blogged on Evil Code series. Time to check one again now. Consider two samples of code.

Sample 1

public class AnotherClass
{
public MyClass ClassInstance{get;set;}
}

public class TestClass1
{
public AnotherClass AnotherClass{get;set;}
public int Id
{
get=> AnotherClass.ClassInstance.Id;
set=> AnotherClass.ClassInstance.Id=value;
}
}

public class MyClass
{
public int Id{get;set;}
}

Sample 2

public class AnotherClass
{
public MyStruct StructInstance{get;set;}
}

public class TestClass2
{
public AnotherClass AnotherClass{get;set;}
public int Id
{
get=> AnotherClass.StructInstance.Id;
set=> AnotherClass.StructInstance.Id=value;
}
}
public struct MyStruct
{
public int Id{get;set;}
}

How differently would two of the code samples given below behave ?

Well, Sample 1 compiles and Sample 2 doesn’t. Why ?? Sample 2, in fact raises following error.

Cannot modify the return value of 'AnotherClass.StructInstance' because it is not a variable

Could you reason why ?

If you look into the two Sample codes, there is a significant difference. MyStruct, used by Sample 2 is a value type. This means that when you are are in fact accessing a copy of StructInstance and not the valeu itself ( as you would have had it been a class – reference type).
Any change made in the property is made on the Copy instance, and then disregarded, leaving the original value unchanged.

This is the reason compiler warns you against.

Exploring Randomize.Net

Randomize.Net provides an easy and lightweight extensions for System.Random for creating random instances of any given Type T, with generated random value. This can be highly useful for generating POCO’s to test your sample code, including LINQ queries against. The API has been designed to make it extremely simple and devoid of any complex syntax.

Generating Random Instances

For Example,

// Primitive Types
var _random = new Random();_
var randomString = _random.GenerateInstance<string>();
var randomInt32 = _random.GenerateInstance<Int32>();

// Output
// randomString = OfuQ42CoIe
// randomInt32 = 239016499

Randomize.Net works with User Defined Types as well, including nested User Defined Types.

public class SampleClass
{
public string StringProperty{get;set;}
public int Int32Property {get;set;}
public char CharProperty {get;set;}
}

public class AnotherSampleClass
{
public SampleClass SampleClassProperty{get;set;}
public string StringProperty{get;set;}
}

var sampleClass = _random.GenerateInstance<SampleClass>();
var anotherSampleClass = _random.GenerateInstance<AnotherSampleClass>();

/* Output
* sampleClass.StringProperty = ORCPiyNoy5
* sampleClass.Int32Property = -1461704929
* sampleClass.CharProperty = q
*
* anotherSampleClass.StringProperty = D5wfOfQhAK
* anotherSampleClass.SampleClassProperty.StringProperty = DC7ArGwDj5
* anotherSampleClass.SampleClassProperty.Int32Property = -1311605510
* anotherSampleClass.SampleClassProperty.CharProperty = y
*/

Randomize.Net also supports generation of Collections.

// Method Signature
public static IEnumerable<T> GenerateCollection<T>(this Random source,int count = 1)

//Example
var sampleClassCollection = _random.GenerateCollection<SampleClass>(5);

// sampleClassCollection.Count = 5

Further examples on Randomize.Net would follow soon. If you are interested in looking at the code you can access it my Github.

Mock RestClient.ExecuteAsync

RestSharp is not a stranger to developers, so is the usage. What this posts aims to explore is how to do Unit Test a method, involving a RestClient.ExecuteAsync call. To be more precise, the post explores how to mock the RestClient for the method.

Let’s consider the following code, taken from VSPostman, one of the side projects I am working on.

public async Task Get(string url)
{
if (string.IsNullOrWhiteSpace(url) || _parameterDictionary.Values.Contains(null)) throw new ArgumentNullException();

_restClient.BaseUrl = new Uri(url); // _restClient is an instance of RestClient
_restRequest.Method = Method.GET;
var _returnValue = new ResponseObject();
if(_parameterDictionary?.Count==0)
_restRequest.Parameters.AddRange(_parameterDictionary?.Select(x => new Parameter() {Name = x.Key, Value = x.Value }));
var tcs = new TaskCompletionSource();
var watch = Stopwatch.StartNew();
_restClient.ExecuteAsync(_restRequest, response =>
{
_returnValue.ContendType = response.ContentType;
_returnValue.ResponseString = response.Content;
_returnValue.StatusCode = response.StatusCode;
_returnValue.StatusDescription = response.StatusDescription;
_returnValue.ResponseTime = watch.Elapsed;
_returnValue.Length = response.ContentLength;
if (response.Headers != null)
_returnValue.Headers = response.Headers.ToDictionary(x => x.Name, y => y.Value as string);

tcs.SetResult(_returnValue);
});
return await tcs.Task;
}

As observed, the code raises a GET Request using the ReshSharp library. If I was using TDD and writing a Unit Test case for this method, how would I approach it ? How would I mock the RestSharp library calls ?

Of course, it is easy to understand that we need to create the mock object of IRestClient. But how do we create a response ? For this we attach a call back.

var expected = "response content";
var expectedBytes = Encoding.UTF8.GetBytes(expected);
Mock restClient = new Mock();
restClient.Setup(x => x.ExecuteAsync(
It.IsAny(),
It.IsAny<Action<IRestResponse, RestRequestAsyncHandle>>()))
.Callback<IRestRequest, Action<IRestResponse, RestRequestAsyncHandle>>((request, callback) =>
{
callback(new RestResponse { Content= expected }, null);
});
// act
var clientService = new ClientServiceUsingRestSharp(restClient.Object);
var actualResponse = await clientService.Get($"http://www.google.com");

That would be all you need. The callback would ensure you get the response from the mock object.

Linq Join on Like%

One of the recent requirements I came across recently needed what looks like a Join on a ‘Like%’. Let me cite an example to demonstrate the requirement.
Consider the Collections below.

Master Collection

ID Name
1 Jia Anu
2 Sreena Anu
3 Anu Viswan

Child Collection

ID First Name Age
1 Jia 2
3 Sreena 34
5 Anu 35

I would like to Join on Master.Name and Child.FirstName where Child.FirstName StartsWith Master.Name. The expected output is as follows.

Name FirstName Age
Jia Anu Jia 2
Sreena Anu Sreena 34
Anu Viswan Anu 35

Let’s begin by defining the input collections.

var master = new List<Master>
{
new Master{Id=1,Name="Jia Anu"},
new Master{Id=2,Name="Sreena Anu"},
new Master{Id=3,Name="Anu Viswan"}
};

var child = new List<Child>
{
new Child{Id=1,FirstName="Jia",Age=2},
new Child{Id=2,FirstName="Sreena",Age=34},
new Child{Id=3,FirstName="Anu",Age=35}
};

Where Master and Child is defined as

public class Master
{
public int Id {get;set;}
public string Name {get;set;}
}

public class Child
{
public int Id{get;set;}
public string FirstName {get;set;}
public int Age {get;set;}
}

The default Join uses Equality as Comparer, and is not useful for us in this scenario. The solution lies in a little known overload of Group, which allows to provide our own customer Comparer. Let’s define our Custom Comparer.

class StartsWithEqualityComparer: IEqualityComparer<string>
{
public bool Equals(string right, string left)
{
return left.StartsWith(right);
}
public int GetHashCode(string obj) { return 0; }
}

Now, we can use our StartsWithEqualityComparer.

var result = master.Join(child,
m=>m.Name,
c=>c.FirstName,
(m,c)=> new
{
Name = m.Name,FirstName = c.FirstName,Age = c.Age
}
},new StartsWithEqualityComparer());

That’s it, we have our GroupBy with Like%.

Caliburn.Micro #008: Gesture Recognition using Short-Hand Syntax

In this part of Caliburn.Micro tutorials we would explore how to configure and use Gesture Recognition with Caliburn.Micro, particularly exploiting the Short-Hand syntax for Actions. Caliburn.Micro doesn’t support this out of the box, so obviously we need to work around the Actions to provide support for Gestures. Let’s first formulate the syntax of how we would like to add a Gesture and its binding in XAML and then find our way to it.

We would ideally like to use a syntax, that is close to Action Syntax for triggering events.

[Event Click]=[Action Method1] // Normal Events
[Key F12]=[Action Method1] // Ideal Gesture Syntax.

The first step required would be to write a Trigger that would catch the KeyPress event. The trigger should provide ability to pass the expected “Key” and invoke the binded action when the expected “Key” is pressed. Let’s go ahead and write the required Custom Trigger.

public class KeyTrigger : TriggerBase<UIElement>
{
public static readonly DependencyProperty KeyProperty =
DependencyProperty.Register("Key", typeof(Key), typeof(KeyTrigger), null);

public Key Key
{
get => (Key)GetValue(KeyProperty);
set => SetValue(KeyProperty, value);
}

protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.KeyDown += OnAssociatedObjectKeyDown;
}

protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.KeyDown -= OnAssociatedObjectKeyDown;
}

private void OnAssociatedObjectKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key)
{
InvokeActions(e);
}
}
}

The KeyTrigger is quite self-explainatory. It declares Dependency Property called “Key” of System.Windows.Input.Key, and verifies if the Key Pressed is actually the one registered in KeyDown Event of AssociatedObject. If the Key matches the registered Key, it invokes the associated Action.

The Step is to Write our Custom Action Format, that would be recognized by the Caliburn.Micro Parser, and calls from Trigger(and there by Action). In order to achieve this, we re-define Parser.CreateTrigger method, which is responsible to generate the trigger. We do this in our Bootstrapper, overriding Configure Method.

// In Bootstrapper

protected override void Configure()
{
var defaultCreateTrigger = Parser.CreateTrigger;

Parser.CreateTrigger = (target, triggerText) =>
{
if (string.IsNullOrEmpty(triggerText)) return defaultCreateTrigger(target, null);

var regex = new Regex($@"^\[(?<{X_ACTION}>[a-zA-Z]+)\s(?<{X_SHORTCUT}>[a-zA-Z0-9]+)\]$");
var matches = regex.Match(triggerText.Trim());

switch (matches.Groups[X_ACTION].Value.ToUpper())
{
case X_KEY:
return new KeyTrigger
{
Key = (Key)Enum.Parse(typeof(Key), matches.Groups[X_SHORTCUT].Value, true),
};
default:
return defaultCreateTrigger(target, triggerText); ;
}
};
}

As observed, we check if the triggerText contains our special keywords, and if so, create our Custom trigger, namely KeyTrigger. In all other case, it returns the default trigger.

That’s all we require to configure our Gesture Recognition. We can now move on to our View and define the Gesture using our custom Action syntax.

cal:Message.Attach="[Key Enter] = [Action Increment]"

You can access the complete code sample, demonstrated in this post in my Github.

Btw, Merry Christmas !!!

Filter List and Display Type members with specified attribute

One of the recent questions that was intriguing (for me) in Stackoverflow was the need to Process a List and while displaying the result, display only the properties that are decorated with a specific attribute.

Let me explain with an example. Consider the following Entity.

public class Employee
{
public int ID { get; set; }

public string Place { get; set; }

[IncludeinReport]
public string BusinessVertical { get; set; }

[IncludeinReport]
public string Region { get; set; }

public string Country { get; set; }

[IncludeinReport]
public string BusinessUnit { get; set; }
}

For a List<Employee>, the expected result would display only “BusinessVertical”, “Region”, and “BusinessUnit” in the result. Let’s begin by creating a mock sample data to test it.

var list = new List<Employee>
{
new Employee{ID = 1, Region = "Europe", BusinessUnit="Software", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Asia", BusinessUnit="Software", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Asia", BusinessUnit="Hardware", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Europe", BusinessUnit="Software", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Asia", BusinessUnit="Telecom", BusinessVertical = "Sample1"},
new Employee{ID = 1, Region = "Europe", BusinessUnit="Software", BusinessVertical = "Sample1"},
};

Just to make things interesting, we would add restriction that the result needs to be Sorted By Region and Then by BusinessUnit. A LINQ solution would have been ideal, but unfortunately, I couldn’t go all the way with LINQ. But here is the solution I could suggest.
The first step, obviously was to get the List of Properties that has the required Attribute, which we can achieve using Reflection.

var properties = typeof(Employee).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(IncludeinReport))).Select(v=>v);
var intermediate = list.OrderBy(c => c.Region).ThenBy(x=>x.BusinessUnit).SelectMany((x,index)=> properties.Select(v=> new {GroupId = index, Dict = new KeyValuePair<string,object>(v.Name, v.GetValue(x))})) ;
var resultList = intermediate.GroupBy(x=>x.GroupId).Select(x=>x.ToList().Select(c=>c.Dict).CreateObject());

Where CreateObject is defined as

public static class Extensions
{
public static ExpandoObject CreateObject(this IEnumerable<KeyValuePair<string,object>> source)
{
dynamic returnValue = new ExpandoObject();
var dict = returnValue as IDictionary<string, object>;
foreach (var kvp in source)
{
dict.Add(kvp.Key, kvp.Value);
}
return returnValue;
}
}

Since even anonymous types needs to have Property Names defined in compile time, the only solution to create a Dynamic Type (including property names) was using ExpandoObject.
This would give you the desired output as enclosed in the screenshot.

Capture

Again, this is the solution I could arrive at, there would be better ones. I would certainly be interested to know a better solution. If anyone would like to follow the OP in question, please follow it StackoverFlow

Mapping XML Using Automapper

Automapper comes handy when you have to deal with a lot of DTOs, making it very easy to map one type to another. But there are situations where you might need an extra hand.

Consider the following Type definitions.

public class SourceUser
{
public string Name {get;set;}
public int Age {get;set;}
public string Address {get;set;}
}

public class DestinationUser
{
public string UserName{get;set;}
public int Age{get;set;}
public Address Address{get;set;}
}
public class Address
{
public string City {get;set;}
public string State {get;set;}
public string Country {get;set;}
}

The Source.Address is a XML representation of Address. Your requirement is to configure Automapper to convert SourceUser to DestinationUser. Let’s define an example SourceUser first, so that our demonstration could be easier.

var sourceUser = new SourceUser
{
Name = "Anu Viswan",
Age = 35,
Address = "<Address><County>India</Country><State>Kerala</State><City>Cochin</City></Address>"
};

This is where ConstructUsing method of comes into place. The first step is define our custom Construction Method.

static DestinationUser ConstructAddress(SourceUser src)
{
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(src.Address);
var destinationUser = new DestinationUser
{
Address = new Address
{
Country = xdoc.Root.Element(nameof(Address.Country)).Value,
City = xdoc.Root.Element(nameof(Address.City)).Value,
State = xdoc.Root.Element(nameof(Address.State)).Value,
}
};

return destinationUser;
}

With our Construction Method ready, we now move on to configure Automapper.

Mapper.Initialize(cfg =>
cfg.CreateMap<SourceUser, DestinationUser>()
.ConstructUsing(x => ConstructAddress(x))
.ForMember(dest => dest.UserName, source => source.MapFrom(s => s.Name))
.ForMember(dest => dest.Age, source => source.MapFrom(s => s.Age))
.ForMember(dest=> dest.Address, source => source.Ignore()));

Do note that we have relied on Automapper for rest of Properties, which can be easily mapped. It is also important to instruct Automapper to Ignore the Address property in its routine parsing. That would give you the desired result and you can map the incompatible Types using the following.

var destinationUser = Mapper.Map<DestinationUser>(sourceUser);