Json Custom Filtering : Remove Properties of a Type T

One of the recent questions that came up in SO which fascinated me was how do one filter a Json string by removing properties from Json, which is of a particular Type. For example, consider the following Json.

{
'widget':
{
'debug': 'on',
'window': {
'title': 'Sample Widget',
'name': 'main_window',
'width': 500,
'height': 500
},
'image': {
'src': 'Images/Sun.png',
'name': 'sun1',
'hOffset': 250,
'vOffset': 250,
'alignment': 'center'
},
'text': {
'data': 'Click Here',
'size': 36,
'style': 'bold',
'name': 'text1',
'hOffset': 250,
'vOffset': 100,
'alignment': 'center',

}
}}

What if you want to remove all Json Properties that has a value of Integer Type. What would be a good way to achieve it if the format of Json is unknown ?

I ended up writing an extension method.

public static class Extensions
{
public static JToken RemoveFieldTypes(this JToken token,params JTokenType []fieldTypes)
{
JContainer container = token as JContainer;
if (container == null) return token;

var tokensToRemove = new List<JToken>();
foreach (JToken el in container.Children())
{
JProperty p = el as JProperty;
if(p!=null && fieldTypes.Contains(p.Value.Type))
{
tokensToRemove.Add(el);
}
el.RemoveFieldTypes(fieldTypes);
}
foreach (JToken el in tokensToRemove)
{
el.Remove();
}
return token;
}
}

Client Code Sample

JToken nodeList = JToken.Parse(strJson);
nodeList.RemoveFieldTypes(JTokenType.Integer);

Sample Ouput

{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window"
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"alignment": "center"
},
"text": {
"data": "Click Here",
"style": "bold",
"name": "text1",
"alignment": "center"
}
}
}

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.

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