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

Json Recipes

Here are few quick recipes with Newtonsoft.Json

Recipe 01 : Convert Json to XML

One way to convert a Json to XML would be to convert Json to intermediate class structure and then serialize the class using XMLSerializer. But why go the long way when you can do it directly.

Let’s check the code straightaway.

var jsonString = @"{
'Family':[
{
'Name':'Anu',
'Age': '35'
},
{
'Name':'Jia',
'Age': '2'
}
]
}";
var xml = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonString,"root");

That’s it, you have your XML. Output is shown below.

<root>
<Family>
<Name>Anu</Name>
<Age>35</Age>
</Family>
<Family>
<Name>Jia</Name>
<Age>2</Age>
</Family>
</root>

Recipe 02 : Convert XML to Json

No prizes for guess how to do it other way around (XML to Json) – Yes, you Serialize.

var xmlString = @"<root>
<Family>
<Name>Anu</Name>
<Age>35</Age>
</Family>
<Family>
<Name>Jia</Name>
<Age>2</Age>
</Family>
</root>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
var json = JsonConvert.SerializeXmlNode(doc);

Recipe 03: Dynamic Json
Consider the following Json. What could be the best way to model it in C# class.

{
'Key1' : 'some value 1',
'Key2' : 'some value 1',
'Key3' : 'some value 1',
'Key4' : 'some value 1',
}

Where you do not know how many Keys would be there and what could be there name ? The easiest way would be if you can serialize it to an Dictionary. The ‘JsonExtensionData‘ attribute allows you to do exactly the same.

<br />public class JsonSample
{
[JsonExtensionData]
public Dictionary<string,object> RandomKeyValuePair {get;set;}
}

// Client Code
var jsonString = @"
{
'Key1' : 'some value 1',
'Key2' : 'some value 1',
'Key3' : 'some value 1',
'Key4' : 'some value 1',
}";

var jsonSampleObject = JsonConvert.DeserializeObject<JsonSample>(jsonString);

Of course the reverse is also possible.

var jsonResult = JsonConvert.SerializeObject(jsonSampleObject);

More recipes later.

Verifying if View Exists for specified ViewModel

There might raise situations in your Project where you might be interested to check if the ViewModel specified has a corresponding View defined and gradefully handle the error, than throwing an exception.

Caliburn Micro’s ViewLocator class provides you methods that enables you to do exactly that.

if ((ViewLocator.LocateForModelType(typeof(DummyViewModel), null, null) is TextBlock tb
&& tb.Text.StartsWith("Cannot find", StringComparison.InvariantCultureIgnoreCase)))
{
// View does not exist, Terminate or redirect to another
}
else
{
// View found, redirect to intended one
}

Shaders with HLSL #03: Passing Additional Parameters

In previous parts of this series, we briefly discussed the need for Shaders and created our first Shader Program. In this subsequent part, we would be exploring on passing additional parameters to our Custom Shader.

In previous example, we replaced entire color of applied Control with a single color. What if we need to replace only certain colors, among different colors in the control. We would then need to pass the ‘color to replace’ and ‘new color’ to the Shader.

Step 01 : The Shader

Let’s write our Shader, again with HLSL. We will delve into details soon.

sampler2D input: register(s0);
float4 oldColor : register(c0);
float4 newColor : register(c1);

float4 main(float2 uv:TEXCOORD) : COLOR
{
float4 color = tex2D(input, uv);
if (color.r == oldColor.r && color.b == oldColor.b && color.g == oldColor.g)
{
return newColor;
}
return color;
}

We now have two additional parameters defined in the Line 2 & 3. While it follows the earlier parameter declaration, there is an important difference. For additional (non-image) parameters, we are using the C series registers, which are, as discussed in last post, floating point registers. We have two parameters, both of type float4, which would hold details of ‘old color‘ and ‘new color‘.

float4 oldColor : register(c0);
float4 newColor : register(c1);

In the first line of our main function, we see a new function, which we haven’t seen in previous example.

float4 color = tex2D(input, uv);

tex2D is a texture sampling intrinsic function, which generates a vector from its a sampler and a float2, which holds the two-dimensional texture cordinates at which the sampler is to be sampled. The cordinates (u and v), ranges from (0,0) to (1,1) as one moves from top-left to bottom-right.

In the subsequent code, which is self-explanatory, we compare the RGB values to decide whether we need to replace the color.

Step 02 : The ShaderEffect Class

Having written our Shader, the next obvious step is create our custom class derieved from ShaderEffect. Like in Shader code, we will write the code first and then explore the details.

public class ReplaceColorEffect : ShaderEffect
{
public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(ReplaceColorEffect), 0);
public Brush Input
{

get => ((Brush)(GetValue(InputProperty)));
set => SetValue(InputProperty, value);
}

public Color OldColor
{
get { return (Color)GetValue(OldColorProperty); }
set { SetValue(OldColorProperty, value); }
}

public static readonly DependencyProperty OldColorProperty =
DependencyProperty.Register("OldColor", typeof(Color), typeof(ReplaceColorEffect), new PropertyMetadata(Colors.Black,PixelShaderConstantCallback(0)));
public Color NewColor
{
get { return (Color)GetValue(NewColorProperty); }
set { SetValue(NewColorProperty, value); }
}

public static readonly DependencyProperty NewColorProperty =
DependencyProperty.Register("NewColor", typeof(Color), typeof(ReplaceColorEffect), new PropertyMetadata(Colors.Black, PixelShaderConstantCallback(1)));

public ReplaceColorEffect()
{
PixelShader pixelShader = new PixelShader();

pixelShader.UriSource = new Uri(@"E:\App Store\GitHub\anuviswan\LearningPoint\Shaders\ShaderExample001\Shader\ReplaceColor.ps", UriKind.Absolute);

PixelShader = pixelShader;
UpdateShaderValue(InputProperty);
UpdateShaderValue(OldColorProperty);
UpdateShaderValue(NewColorProperty);

}
}

While most of the code is pretty similiar to code in our previous example, ones that needs more attension is discussed below. The most significant difference is the two additional parameters, which are mapped to floating point registers (c registers) and how it is defined in C# code.

public Color OldColor
{
get { return (Color)GetValue(OldColorProperty); }
set { SetValue(OldColorProperty, value); }
}

public static readonly DependencyProperty OldColorProperty =
DependencyProperty.Register("OldColor", typeof(Color), typeof(ReplaceColorEffect), new PropertyMetadata(Colors.Black,PixelShaderConstantCallback(0)));

As observed in the code above, the declaration of dependency properties for c-registers are in the more familiar & conventional syntax, using the DependencyProperty class. What makes it different from normal dependency properties is the PixelShaderConstantCallback parameter of PropertyMetadata class. This tells the compiler that this is a special Dependency property which needs to be mapped to c-registers when communicating with the Shader application.

Rest of the code is pretty self-explanatory and XAML is no different than ones you might have seen countless times, using the dependency properties.

<shadereffects:ReplaceColorEffect OldColor="Red" NewColor="Green"/>

Hit F5 and you can now see your Shader in action. For complete code discussed in this series, please refer to my Github.

Complete Shader with HLSL Series

Assignment using Ternary Operator

Couple of days back, I happened to come across a question in StackOverflow. Question seemed pretty straightforward, but at the same time, interesting. How would one use ternary operator for assignment. For example, how would write following code using ternary operator.

var a = 1;
var b = 2;
var c = 3;
var flag = false;
if(flag)
a = c;
else
b = c;

Obviously, following wouldn’t work.

// CS0131 The left-hand side of an assignment must be a variable, property or indexer
(flag?a:b) = c;

One way to use ternary operator would using Action.

(flag ? new Action(() => a = c): () => b = c)();

But that doesn’t quite give you the clean syntax of Ternary Operator. That brings us to the second way using features exposed by C# 7.2. Let us rewrite the code.

(flag ? ref a : ref b) = c;

Enjoy coding…

C# 8.0 : Default Implementation of Interface Members

The way C# language is evolving is definitely exciting and one feature that truly makes the wait for C# 8.0 all the more exciting is default implementation of interfaces.

Since the onset, interfaces were behaviors characterized by member signatures, strictly disallowing any implementation. All that is going to change when C# 8.0 rolls out, as it supposedly, plans to support default implementation of interfaces. What it means is further trimming down the walls between interface and class (but remember, walls would still exist : Interface and Classes will still have significant difference, we will talk about it a bit later.)

Let’s look at an example, courtesy MSDN Blogs.

interface ILogger
{
void Log(LogLevel level, string message);
void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); // New overload
}

class ConsoleLogger : ILogger
{
public void Log(LogLevel level, string message) { ... }
// Log(Exception) gets default implementation
}

Doesn’t that look exciting ? Gone are days when as an Author of an interface, you were almost handicapped extending the interface fearing it might break any of implementing code. You could now provide the default implementation of your interface member, and still be assured that all implementing code works as fine as it was before.

If this doesn’t excite you, think from another perspective. What this implies is possibility of multiple inheritance (almost) in a language that was never really supported it. You could now provide two interfaces with default implementation, and have a class inherit from both.

interface IParentA
{
string MethodA() => nameof(MethodA);
}

interface IParentB
{
string MethodB() => nameof(MethodB);
}

class Child : IParentA,IParentB
{
void MethodChild()
{
Console.WriteLine($"{nameof(MethodA)} = {MethodA()}");
Console.WriteLine($"{nameof(MethodB)} = {MethodB()}");
}
}

This effectively brings in Multiple Inheritance in place. What would be interesting to see is how Microsoft circumvented the Diamond Problem. Let’s delve a bit into Diamond Problem first, before trying to understand Microsoft’s workaround from what ever we know as of now.

Diamond Problem

Let’s consider the following inheritance structure assuming C# were to support Multiple Inheritance.

class A
{
public virtual string DemoMethod() => $"{nameof(A)}.{nameof(A.DemoMethod)}()";
}

class B : A
{
public override string DemoMethod() => $"{nameof(B)}.{nameof(B.DemoMethod)}()";
}

class C : A
{
public override string DemoMethod() => $"{nameof(C)}.{nameof(C.DemoMethod)}()";
}

// Let's assume this works for sake of demonstration
class D:B,C
{
public void Print()=> Console.WriteLine(DemoMethod());
}

In the above code, class D inherits from both Class B and Class C, both of which, in-turns inherits from Class A and overrides virtual member DemoMethod. Assuming this code compiles, what would be the output of Print() Method in Class D. Will it invoke method from Class B or Class C ? This ambiguity is better known as Diamond Problem.

Microsoft intents to work around the Diamond Problem here by taking the most specific override at the time. As Microsoft pens it down

“Diamonds with Classes

A class implementation of an interface member should always win over a default implementation in an interface, even if it is inherited from a base class. Default implementations are always a fallback only for when the class does not have any implementation of that member at all.”

Let’s rewrite the above code using default implementation of interfaces.

interface A
{
string DemoMethod() => $"{nameof(A)}.{nameof(A.DemoMethod)}()";
}

interface B: A
{
override string DemoMethod() => $"{nameof(B)}.{nameof(B.DemoMethod)}()";
}

interface C: A
{
override string DemoMethod() => $"{nameof(C)}.{nameof(C.DemoMethod)}()";
}

// This would be Error as no most specific override for A.DemoMethod()
class D:B,C
{
public void Print()=> Console.WriteLine(DemoMethod());
}

// This would be Error as no most specific override for A.DemoMethod()
class E:B,C,A
{
string DemoMethod()=> B.base.DemoMethod();
public void Print()=> Console.WriteLine(DemoMethod());
}

So will now abstract class == interface ?

No, not really. Even though the differences are diminishing, there still lies a lot of difference between the two. To name a few
– Unlike Abstract Class ,you still can’t write a default constructor for interface.
– Covariance and Contravariance

Essentially, abstract class and interface would continue to coexist in its own space. What Microsoft has done with Default Implementation of Interface is making use of Traits (more on traits later.)

 

Shaders with HLSL #02 : Applying Shader to WPF Application

In the first part of series, we wrote our first Shader Program. Now it is time to compile it so that we could use it in our WPF Application.

HLSL Compiler

To compile your HLSL code to a format that could be used with .Net WPF application, you would require the fxc compiler. For Windows 7 and earlier editions, you would need to install DirectX SDK in order to get fxc.exe. For Windows 8 and above, this comes as part of the Windows SDK.

The compiler can found under the location ‘Program Files (x86)\Windows Kits‘. If we had saved our previous written code (from previous part of this series) as RedTint.hlsl, we would need to use following command to compile it.

fxc /T ps_2_0 /E main /Fo RedTint.ps RedTint.hlsl

This would give the necessary ps file, or Pixel Shader file which we could now refer in our WPF Application. Now that we have our Pixel Shader file, we will move on to our WPF application.

Creating our Test Application

We will keep our text application simple. The XAML code is shown below.

<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" Content="Normal Button" HorizontalAlignment="Center"/>
<Button Grid.Column="0" Grid.Row="1" Content="Click Me"/>

<Label Grid.Column="1" Grid.Row="0" Content="Button with Shader" HorizontalAlignment="Center"/>
<Button Grid.Column="1" Grid.Row="1" Content="Click Me"/>
</Grid>

Also enclosed is a screenshot of the application. The purpose of our application would be apply our shader to one of the buttons, while leaving the other button untouched, so that we could easily demonstrate the difference (or rather impact of shader). We will also add our RentTint.ps file to our project as a resource.

Defining Custom Effect

To use the compiled shader application, we need to load it to the rendering engine input stream. This is accomplished with the help of ShaderEffect class in .Net. The ShaderEffect base class makes it possible to wrap the HLSL pixel shader and apply them our applications XAML elements.

public class RedTintEffect: ShaderEffect
{
public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(RedTintEffect), 0);
public Brush Input
{

get => ((Brush)(GetValue(InputProperty)));
set => SetValue(InputProperty, value);
}

public RedTintEffect()
{
PixelShader pixelShader = new PixelShader();

pixelShader.UriSource = new Uri(@"path_to_ps_resource", UriKind.Absolute);

PixelShader = pixelShader;
UpdateShaderValue(InputProperty);

}
}

We have defined our custom effect, namely RedTintEffect, derieved from ShaderEffect. Let’s examine the code closely beginging with the constructor.

public RedTintEffect()
{
PixelShader pixelShader = new PixelShader();

pixelShader.UriSource = new Uri(@"path_to_ps_resource", UriKind.Absolute);

PixelShader = pixelShader;
UpdateShaderValue(InputProperty);
}

The first step we need to is to initialize an object of PixelShader (which is a protected member of ShaderEffect class) and refer our ps file using the UriSource property. This would enable the ShaderEffect to communicate with the GPU.

The next step is to create a Dependency Property of Type Brush, calling it “Input”. This is a special property and would contain the input image. There lies a difference in the way we register the Dependency Property as well. Instead of the usual DependencyProperty.Register(), we would be using ShaderEffect.RegisterPixelShaderSamplerProperty() method.

public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(RedTintEffect), 0);
public Brush Input
{

get => ((Brush)(GetValue(InputProperty)));
set => SetValue(InputProperty, value);
}

One of the important points to note in the above code is the final parameter of ShaderEffect.RegisterPixelShaderSamplerProperty() method. The Integer value 0 corresponds to the S0 pixel shader register in our HLSL code. Here is the refered code from HLSL source.

sampler2D input: register(s0);

That’s all we need. We can now go back to our XAML and apply the effect.

Applying Shader

The update code is as follows.

<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="4*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0" Content="Normal Button" HorizontalAlignment="Center"/>
<Button Grid.Column="0" Grid.Row="1" Content="Click Me"/>

<Label Grid.Column="1" Grid.Row="0" Content="Button with Shader" HorizontalAlignment="Center"/>
<Button Grid.Column="1" Grid.Row="1" Content="Click Me">
<Button.Effect>
<shadereffects:RedTintEffect/>
</Button.Effect>
</Button>
</Grid>

We have added our newly added custom Effect to one of the button. Let’s hit F5 and verify our changes.

As observed in the screenshot, the Button to which the Effect was applied has turned Red, while the other Controls remain the same. Do observe that even the Forecolor of Text within the button has turned Red. This is true to our definition of our Shader, since it returns Red irrespective of the input. We will look into more complex scenarios in later posts where we will introduce conditional color changes.

You can access the entire source code described in Part 1 and Part 2 of this series from my Github