External Tracker for OxyPlot

Back with another hack with Oxyplot. This time around what I would like to achieve is to actively update a TextBlock with Tracker values as the user moves around the graph. This could be useful when you want to have an external mini-dashboard which would the tracker values as User works on the graph after turning off your original tracker.

For sake of demo, we would leave the OxyPlot Tracker on, so that the results could be verified with our external tracker.

Let’s set up the View first.

<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>

<oxy:PlotView Model="{Binding DemoPlotModel}"/>
<TextBlock Grid.Row="1" Text="{Binding CurrentTrackerValue}"/>
</Grid>

We will now define our PlotModel and define our Series.

DemoPlotModel = new PlotModel();
var xAxis = new LinearAxis
{
Position = AxisPosition.Left,
Maximum = 100,
Minimum = 0
};

var yAxis = new LinearAxis
{
Position = AxisPosition.Bottom,
Maximum = 100,
Minimum = 0
};

DemoPlotModel.Axes.Add(xAxis);
DemoPlotModel.Axes.Add(yAxis);

var listOfDataPoints = new DataPoint[]
{
new DataPoint(10,5),
new DataPoint(20,15),
new DataPoint(30,20),
new DataPoint(40,28),
new DataPoint(50,39),
new DataPoint(60,55),
new DataPoint(70,60),
new DataPoint(80,73),
new DataPoint(90,90),
};
var series = new LineSeries
{
ItemsSource = listOfDataPoints,
Color = OxyColors.Green,
MarkerType = MarkerType.Square,
MarkerSize = 5,
MarkerFill = OxyColors.DarkGreen
};

DemoPlotModel.Series.Add(series);

And now it is time our adding our little hack to update the Label’s bound property – CurrentTrackerValue.

DemoPlotModel.TrackerChanged += (sender, eventArgs) =>
{
CurrentTrackerValue = eventArgs.HitResult != null ? eventArgs.HitResult.Text : CurrentTrackerValue;
NotifyOfPropertyChange(nameof(CurrentTrackerValue));
};

public string CurrentTrackerValue { get; set; }

That’s it, now you have your external live tracker.

Json : Fetch all keys using Linq

Given a Json, how do we get all the keys in it ? Just the keys. For example, Consider the Json below.

{
Person:['Jia Anu', 'Anu Viswan','Sreena Anu'],
Details:[
{
Name: 'Jia Anu',
Age:3,
},
{
Name: 'Anu Viswan',
Age:35,
},
{
Name: 'Sreena Anu',
Age:34,
}
],
Address : 'Address here',
State : 'Kerala',
Country : 'India'
}

Given the above Json, you would like to get all the keys. You might be later interested to show this as a Menu or Dropdown, that’s down to the requirements. But, how do we get the keys in first place ? May be a Linq One liner would be great ?

Person
Details
Details.Name
Details.Age
Address
State
Country

Of course, you do have the option to loop through the JTokens, but the easiest way out would be using Linq.

var data = JObject.Parse(jsonString);
var result = data.Descendants()
.OfType<JProperty>()
.Select(f=>Regex.Replace(f.Path,@"\[[0-9]\]",string.Empty))
.Distinct();

The Regex involed is to ensure the arrays indices are removed and keys in arrays aren’t duplicated. The output of above Linq would give you collection of all keys in the Json as expected.

Enumerable.Empty vs new T[0]

The need for creating an Empty array/collection rises quite often in most applications. This, normally presents us with two options.

  • Using the Constructor, new T[0];
  • Using the extension method, Enumerable.Empty

Let’s dive a bit deeper into both and examine how both these options work and differ.

Using new T[0]

Creating an empty array with Array Construction syntax is as follows.

var collection = new T[0];

What exactly happens behind the scenes. Let’s examine the following code.

var collection1 = new string[0];
var collection2 = new string[0];
object.ReferenceEquals(collection1,collection2).Dump();

Output of above code would be

False

The reason for this is self-explanatory. Each call to ‘new T[0]’ create a new Empty array in the memory. Both these, are as noticable, separate instances. What happens with Enumerable.Empty then ? Let’s examine that next.

Using Enumerable.Empty

Consider the complimentary code using Enumerable.Empty approach.

var collection1 = Enumerable.Empty<string>();
var collection2 = Enumerable.Empty<string>();
var result = object.ReferenceEquals(collection1,collection2);

What would be output of code in above scenario ? As you might have guessed, the output would be true.

Output

True

Enumerable.Empty caches the result for calls and reuses it later on. As MSDN states it

The Empty<TResult>() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

This can be further verified by checking out the source code of Enumerable.Empty.

public static IEnumerable<TResult> Empty<TResult>()
{
return EmptyEnumerable<TResult>.Instance;
}
internal class EmptyEnumerable<TElement>
{
public static readonly TElement[] Instance = new TElement[0];
}

This difference might be of less significance in applications where memory constraints aren’t too critical, but when your applications requires to ensure memory allocations are used well, then Enumerable.Empty is your friend. Personally, I felt Enumerable.Empty should be the “go to” under all circumstances for not only for the reasons described above, but it also is more verbose in declaration and increases code readability manifold.

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%.