Posted by: Zeeshan Amjad | September 9, 2019

## Quaternions in Python

`I was trying to learn the syntax of Python so looking for some simple example I can implement. The first think came in my mind is a typical Point class which can be used in Graphics. Before even I write anything, I came across an interesting concept of Quaternions which is an actually extension imaginary number. Here is my attempt to write Quaternions in Python.`
```import math

class Quaternion:
def __init__(self, s = 1, i = 0, j = 0, k = 0):
self.i = i
self.j = j
self.k = k
self.s = s

def getX(self):
return self.i

def setX(self, i):
self.i = i

def getY(self):
return self.j

def setY(self, j):
self.j = j

def getZ(self):
return self.k

def setZ(self, k):
self.k = k

def getS(self):
return self.s

def setS(self, s):
self.s = s

def __str__(self):
return "(" + str(self.getS()) + "," + str(self.getX()) + "," + str(self.getY()) + "," + str(self.getZ()) + ")"

q = Quaternion()
q.i = self.getX() + quaternion.getX()
q.j = self.getY() + quaternion.getY()
q.k = self.getZ() + quaternion.getZ()
q.s = self.getS() + quaternion.getS()
return q

def __mul__(self, quaternion):
q = Quaternion()
q.s = self.getS() * quaternion.getS() - self.getX() * quaternion.getX() - self.getY() * quaternion.getY() - self.getZ() * quaternion.getZ()
q.i = self.getS() * quaternion.getX() + quaternion.getS() * self.getX() + self.getY() * quaternion.getZ() - self.getZ() * quaternion.getY()
q.j = self.getS() * quaternion.getY() - self.getX() * quaternion.getZ() + self.getY() * quaternion.getS() + self.getZ() * quaternion.getX()
q.k = self.getS() * quaternion.getZ() + self.getX() * quaternion.getY() - self.getY() * quaternion.getX() + self.getZ() * quaternion.getS()
return q

def __eq__(self, quaternion):
if (self.getS() == quaternion.getS() and self.getX() == quaternion.getX() and self.getY() == quaternion.getY() and self.getZ() == quaternion.getZ()):
return True
else:
return False

def conjugate(self):
q = Quaternion(self.getS(), -1 * self.getX(), -1 * self.getY(), -1 * self.getZ())
return q

def norm(self):
return math.sqrt(self.getS()**2 + self.getX()**2 + self.getY()**2 + self.getZ()**2)

def inverse(self):
c = self.conjugate()
norm = self.norm()

if norm == 0:
raise Exception("norm is zero can't calculate inverse.")

c.s = c.getS() / norm ** 2
c.i = c.getX() / norm ** 2
c.j = c.getY() / norm ** 2
c.k = c.getZ() / norm ** 2
return c

def dot(self, quaternion):
return self.getS() * quaternion.getS() + self.getX() * quaternion.getX() + self.getY() * quaternion.getY() + self.getZ() * quaternion.getZ()
```
Posted by: Zeeshan Amjad | September 2, 2018

## Writing Webservice with node.js and express

Node js is very popular and easy to use technology to write server side code in JavaScript language. with the additin of express js library it would be very easy to write not only the web service, but also middle ware for any full stack application. Node js and express are very popualar to all Java Script full stake platform such as MEAN (MongoDB, Express, Angular, Node) and MERN (MongoDB, Express, React, Node). Application written using MEAN and MERN stack are not only cross platform, but also written in one language i.e. Java Script, therefore it is comparatively easy to build the full stack application in one language.

The first step to write application is to install node which is available in all platform. https://nodejs.org You can check if you have install nodejs on your computer or not by running “node –v”.

Once node js is isntall then create a new application by runing the “npm init” command. It will ask some questions and if selected all default options will create a file package.json

{
"name": "experiment",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
}

Then install the express library by runining the following command “npm install express –save”. It will change the package.json file and added the “dependencies” section and it will look like this.

{
"name": "experiment",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"dependencies": {
"express": "^4.16.3"
}
}

Here the ^ sign before the version of express shows that it will get the latest major version of express if available.

The complete code to write the simple web service.

```var express = require('express')

var port = 5000

var app = express()

app.get('/', (req, res) => {

res.send('Hello world from node')

})

app.listen(port, () => {

console.log(`listening on port \${port}`)

})

```

Save this file as index.js (because in package.json the file name is index.js) We can run this application by runing “node index.js” in the command prompt.If you open localhost:5000 in the browser you will see “Hello world from node”. Now let’s make something useful. If we want to pass some query paramter to the web service url we can get it with req.query.

Let’s make a simple application that perform some financial calculationss. Before that let’s make a small change in the package.json file. Add the following line in package.json under the script section and it will become like this.

"scripts": {

"start": "node index.js",

"test": "echo \"Error: no test specified\" && exit 1"

},

The advantage of this is now we can run the application by just running “npm start” command.

Here is a compelete code of some basic financial web services.

```var express = require('express')

var port = 5000
var app = express()

app.get('/', (req, res) => {

var x = parseFloat(req.query.x);
var y = parseFloat(req.query.y);
res.json({
"methods": [
{
"name": "fv",
"description": "Calculate the future value of money",
"parameters": {
"pv": "Present value of money",
"n": "Number of years",
"r": "Interest rate"
}
},
{
"name": "pv",
"description": "Calculate the present value of money",
"paramteres": {
"fv": "Future value of money",
"n": "Number of years",
"r": "Interest rate"
}
},
{
"name": "dt",
"description": "Calculate the time to double the money",
"parameters": {
"r": "Interest rate"
}
},
{
"name": "per",
"description": "Calculate the pepetuity value to get infinite dividend",
"parameters": {
"d": "Desire dividend value",
"r": "Interest rate"
}
},
{
"name": "pmt",
"description": "Calculate the monthly payment of loan",
"parameters": {
"loan": "Loan amount",
"n": "Total monthly payments",
"r": "Interest rate"
}
}
]
})
})

app.get('/fv', (req, res) => {
var pv = parseFloat(req.query.pv)
var n = parseFloat(req.query.n)
var r = parseFloat(req.query.r)

if (isNaN(pv)
|| isNaN(n)
|| isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var fv = pv * Math.pow(1+r/100, n)

res.json({
pv: pv,
n: n,
r: r,
fv: fv
})
}
})

app.get('/pv', (req, res) => {
var fv = parseFloat(req.query.fv)
var n = parseFloat(req.query.n)
var r = parseFloat(req.query.r)

if (isNaN(fv)
|| isNaN(n)
|| isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var pv = fv / Math.pow(1+r/100, n)

res.json({
pv: pv,
n: n,
r: r,
fv: fv
})
}
})

app.get('/dt', (req, res) => {
var r = parseFloat(req.query.r)

if (isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var dt = Math.log(2) / Math.log(1 + r/100);

res.json({
r: r,
dt: dt
})
}
})

app.get('/per', (req, res) => {
var d = parseFloat(req.query.d)
var r = parseFloat(req.query.r)

if (isNaN(r)
|| isNaN(d)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var per = d / (r/100)

res.json({
d: d,
r: r,
per: per
})
}
})

app.get('/pmt', (req, res) => {
var loan = parseFloat(req.query.loan)
var n = parseFloat(req.query.n)
var r = parseFloat(req.query.r)/100

if (isNaN(loan)
|| isNaN(n)
|| isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var interestTerm = Math.pow((1+r/12), n)
var pmt = (loan * r/12) / (1 - (1/interestTerm))

res.json({
loan: loan,
n: n,
r: r*100,
pmt: pmt
})
}
})

app.listen(port, () => {
console.log(`listening on port \${port}`)
})

```
```var express = require('express')

var port = 5000
var app = express()

app.get('/', (req, res) => {

var x = parseFloat(req.query.x);
var y = parseFloat(req.query.y);
res.json({
"methods": [
{
"name": "fv",
"description": "Calculate the future value of money",
"parameters": {
"pv": "Present value of money",
"n": "Number of years",
"r": "Interest rate"
}
},
{
"name": "pv",
"description": "Calculate the present value of money",
"paramteres": {
"fv": "Future value of money",
"n": "Number of years",
"r": "Interest rate"
}
},
{
"name": "dt",
"description": "Calculate the time to double the money",
"parameters": {
"r": "Interest rate"
}
},
{
"name": "per",
"description": "Calculate the pepetuity value to get infinite dividend",
"parameters": {
"d": "Desire dividend value",
"r": "Interest rate"
}
},
{
"name": "pmt",
"description": "Calculate the monthly payment of loan",
"parameters": {
"loan": "Loan amount",
"n": "Total monthly payments",
"r": "Interest rate"
}
}
]
})
})

app.get('/fv', (req, res) => {
var pv = parseFloat(req.query.pv)
var n = parseFloat(req.query.n)
var r = parseFloat(req.query.r)

if (isNaN(pv)
|| isNaN(n)
|| isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var fv = pv * Math.pow(1+r/100, n)

res.json({
pv: pv,
n: n,
r: r,
fv: fv
})
}
})

app.get('/pv', (req, res) => {
var fv = parseFloat(req.query.fv)
var n = parseFloat(req.query.n)
var r = parseFloat(req.query.r)

if (isNaN(fv)
|| isNaN(n)
|| isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var pv = fv / Math.pow(1+r/100, n)

res.json({
pv: pv,
n: n,
r: r,
fv: fv
})
}
})

app.get('/dt', (req, res) => {
var r = parseFloat(req.query.r)

if (isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var dt = Math.log(2) / Math.log(1 + r/100);

res.json({
r: r,
dt: dt
})
}
})

app.get('/per', (req, res) => {
var d = parseFloat(req.query.d)
var r = parseFloat(req.query.r)

if (isNaN(r)
|| isNaN(d)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var per = d / r

res.json({
d: d,
r: r,
per: per
})
}
})

app.get('/pmt', (req, res) => {
var loan = parseFloat(req.query.loan)
var n = parseFloat(req.query.n)
var r = parseFloat(req.query.r)/100

if (isNaN(loan)
|| isNaN(n)
|| isNaN(r)) {
res.json({
"error": "not all input parameters are provided"
})
}
else {
var interestTerm = Math.pow((1+r/12), n)
var pmt = (loan * r/12) / (1 - (1/interestTerm))

res.json({
loan: loan,
n: n,
r: r*100,
pmt: pmt
})
}
})

app.listen(port, () => {
console.log(`listening on port \${port}`)
})

```
Posted by: Zeeshan Amjad | May 25, 2018

## My First React Component

I got  chance to play with one very famous JavaScript library React and play with it. There are two different type of component we can create in React, “Function Component” and “Class Component”. One obvious choice of component style is when we have state or lifecyle  we prefer to use “Class Component”.

Here is an example of Function component

```const MyFuncComponent(props) {
return (<h1>Hello from Function Component</h1>);
}

```

We can also write in this way

```const MyFuncComponent = props => {
return (<h1>Hello from Function Component</h1>);
}

```

And here is an example of class component.

```class MyClassComponent extends React.Component {
render() {
return (<h1>Hello from Class Component</h1>);
}
}

```

If we need state in our component or need life cycle, then class component is a choice. One more interesting thing is the above code is the return statement. It is not a string, but JSX and extension of the Java Script language. This will make writing component very easy. We don’t have to use this and can create component without it. Here is an example of it.

```const MyFuncComponent = props => {
return (
React.createElement("h1", null, "Hello from Function Component")
);
}

class MyClassComponent extends React.Component {
render() {
return (
React.createElement("h1", null, "Hello from Class Component")
);
}
}

```

Let’s create a Counter Button that display counter value, increment it when click to the maximum value upto the increment value and set it to the initial value when right click on it. There is state in this component, so we need to create a class component for this. Here is a code of CounterButton.

```class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {
init: props.init,
increment: props.increment,
counter: props.init,
max: props.max
}
}

handleClick = () => {
this.setState((prevState) => ({
counter: prevState.counter + prevState.increment >= prevState.max
? prevState.max : prevState.counter + prevState.increment
}))
};

e.preventDefault();
this.setState((prevState) => ({
counter: prevState.init
}))
}

render() {
return (
{this.state.counter}
</button>
)
}
}

```

Now le’ts resue this component in another component. Let’s create a collection of CounterButtion with different increment. We can do this with function component, because there is no state involved in it. Here is a code of it.

```const CounterButtonCollection = (props) => {
return (
<div>
<CounterButton init={0} increment={1} max={100} />
<br />
<CounterButton init={0} increment={2} max={100} />
<br />
<CounterButton init={0} increment={3} max={100} />
<br />
<CounterButton init={0} increment={5} max={100} />
</div>
);
}

```

Here is an out put of this when run in https://jscomplete.com/repl/ Posted by: Zeeshan Amjad | June 25, 2015

## Datatemplate Triggers

Sometime we need to display different values on user element than what is stored in corresponding data bind element. Such as we may store the status code in the form of integer or enum representing different states, but display some user defined string. IValueConverter is the natural choice in this situation. You can see the usage of IValueConverter here.

Alternatively we can do the same thing in XAML only with the help of DataTemplate Trigger. Let’s see we have a product class that have its name, code and status. Code is stored in the form of integer, but we want to display some user define string.

Code Snippet
public class Product
{
public string Name { get; set; }
public string Code { get; set; }
public int Status { get; set; }
}

We want to display this information in grid, but display 0 as approved, 1 as reject and 2 as a pending. Here is a DataTemplate trigger to do this.

Code Snippet
<DataTemplate>
<TextBlock x:Name="textBlock"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Status}" Value="0">
<Setter TargetName="textBlock" Property="Text" Value="Approved"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="1">
<Setter TargetName="textBlock" Property="Text" Value="Reject"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="2">
<Setter TargetName="textBlock" Property="Text" Value="Pending"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>

Note that here we use the name of TextBlock, so we can refer it latter to set the appropriate value. Also note that we are not doing binding in TextBlock, but in DataTrigger.

Here is complete C# code of the program.

Code Snippet
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfDataTemplateTrigger
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<Product> products = new ObservableCollection<Product>();
public MainWindow()
{
InitializeComponent();

products.Add(new Product() {Name = "Product 1", Code = "A101", Status = 0});
products.Add(new Product() { Name = "Product 2", Code = "D510", Status = 1 });
products.Add(new Product() { Name = "Product 3", Code = "E201", Status = 0 });
products.Add(new Product() { Name = "Product 4", Code = "M325", Status = 2 });
products.Add(new Product() { Name = "Product 5", Code = "V405", Status = 2 });

DataContext = products;
}
}

public class Product
{
public string Name { get; set; }
public string Code { get; set; }
public int Status { get; set; }
}
}

And here is complete XAML code of it.

Code Snippet
<Window x:Class="WpfDataTemplateTrigger.MainWindow"
xmlns
xmlns:x
Title="Datatemplate Trigger" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False"
<DataGrid.Columns>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="textBlock"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Status}" Value="0">
<Setter TargetName="textBlock" Property="Text" Value="Approved"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="1">
<Setter TargetName="textBlock" Property="Text" Value="Reject"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="2">
<Setter TargetName="textBlock" Property="Text" Value="Pending"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

This is an output of the program. Posted by: Zeeshan Amjad | April 1, 2015

I came across a ASP.Net MVC project and came across an interesting property ViewBag. ViewBas is an interesting property where we can add as many properties to it as we want at run time. When I saw the source code of it, it is declare dynamic that explains it. I tried to do the same thing in my simple project, but stuck with how to initialize dynamic variable. I came across EpandoObject that is for exactly same reason.

ExpandoObject implements lots of interface such as IDictionary, ICollection, IEnumerabl, and INotifyPropertyChanged. Perhaps the most interesting one is IDynamicMetaObjectProvider. This interface has only one method.

Code Snippet
public interface IDynamicMetaObjectProvider
{
DynamicMetaObject GetMetaObject(Expression parameter);
}

Let’s take a look at the example to use ExpandoObject. Here is a simple program to demonstrate this.

Code Snippet
using System;
using System.Dynamic;

class Program
{
static void Main(string[] args)
{
dynamic data = new ExpandoObject();

data.FirstName = "Zeeshan";
data.Company = "Bloomberg";

Console.WriteLine(data);
Console.WriteLine(data.FirstName);
Console.WriteLine(data.LastName);
Console.WriteLine(data.Company);
}
}

The output of this program is as expected the value of properties.

Let’s try to create our own dynamic object that does something similar. .Net already provides one class named DynamicObject exactly for this purpose. All we have to do is override TryGetMeber and TrySetMember method overloaded.

Let’s create our own dynamic object class.

Code Snippet
public class MyDynamicObject : DynamicObject
{
private readonly IDictionary<string, object> _properties = new Dictionary<string, object>();

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _properties.TryGetValue(binder.Name, out result);
}

public override bool TrySetMember(SetMemberBinder binder, object value)
{
_properties[binder.Name] = value;
return true;
}

public int Count
{
get { return _properties.Count; }
}

public IEnumerable<string> Properties
{
get { return _properties.Keys; }
}
}

We also added two additional methods in this class to give the number of properties and the name of the properties.

Here is a complete C# program to demonstrate this.

Code Snippet
using System;
using System.Collections.Generic;
using System.Dynamic;

class Program
{
static void Main(string[] args)
{
dynamic data = new MyDynamicObject();

data.FirstName = "Zeeshan";
data.Company = "Bloomberg";

Console.WriteLine(data);
Console.WriteLine(data.FirstName);
Console.WriteLine(data.LastName);
Console.WriteLine(data.Company);
Console.WriteLine(data.Count);

foreach (var name in data.Properties)
{
Console.WriteLine(name);
}
}
}

public class MyDynamicObject : DynamicObject
{
private readonly IDictionary<string, object> _properties = new Dictionary<string, object>();

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _properties.TryGetValue(binder.Name, out result);
}

public override bool TrySetMember(SetMemberBinder binder, object value)
{
_properties[binder.Name] = value;
return true;
}

public int Count
{
get { return _properties.Count; }
}

public IEnumerable<string> Properties
{
get { return _properties.Keys; }
}
}

Posted by: Zeeshan Amjad | November 19, 2014

## Convert Event to Command using Blend SDK

We saw an example of how to change the controls event into command using attached dependency property here and here. Microsoft Expression Blend SDK provide another simple way to do this.

The first step is to include the reference of System.Windows.Interactivity.dll. On 64 bit Windows, it can be find in the following location.

C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries

or

C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries

Lets make a simple example of ListBox and convert the SelectionChanged event into command. At first step Let’s create a ViewModel. The ViewModel contains the ObservableCollection to populate the Listbox, SelectedItem property to store the currently selected item and SelectedCommand property.

Code Snippet
public class CitiesViewModel : ViewModelBase
{
private ObservableCollection<string> _cities;
private string _selectedItem;

public CitiesViewModel()
{
Cities = new ObservableCollection<string>
{ "Boston", "Los Angeles", "Houston", "New York", "Chicago", "Philadelphia" };

SelectedItemCommand = new DelegateCommand<string>(SelectionChange, () => true);
}

private void SelectionChange(string value)
{
SelectedItem = value;
}

public ObservableCollection<string> Cities
{
get { return _cities; }
set
{
if (Equals(value, _cities)) return;
_cities = value;
OnPropertyChanged();
}
}

public string SelectedItem
{
get { return _selectedItem; }
set
{
if (value == _selectedItem) return;
_selectedItem = value;
OnPropertyChanged();
}
}

public ICommand SelectedItemCommand
{
get; set;
}
}

Now first include the reference of System.Windows.Interactivity in XAML.

Code Snippet
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Here is a XAML code to use expression interactivity to convert SelectionChanged event into command and bind it with SelectedItemCommand defined in CitiesViewModel. In addition it also passes the SelectedItem as a command parameter.

Code Snippet
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectedItemCommand}"
CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>

Here is complete XAML code of the program.

Code Snippet
<Window x:Class="IntractivitySample.MainWindow"
xmlns
xmlns:x
xmlns:d
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Title="Event Trigger" Height="300" Width="400">
<Grid DataContext="{Binding}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" Margin="5" HorizontalContentAlignment="Stretch" ItemsSource="{Binding Cities}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectedItemCommand}"
CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>

</ListBox>
<TextBlock Grid.Column="1" Margin="5" Text="{Binding SelectedItem}"/>
</Grid>
</Window>

And here is complete C# code of the program.

Code Snippet
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;

namespace IntractivitySample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

DataContext = new CitiesViewModel();
}
}

public class DelegateCommand<T> : ICommand
{
private Action<T> _action;
private Func<bool> _predicate;

public DelegateCommand(Action<T> _action, Func<bool> _predicate)
{
this._action = _action;
this._predicate = _predicate;
}

private void Execute(T parameter)
{
if (_action != null)
{
_action(parameter);
}
}

public bool CanExecute(object parameter)
{
if (_predicate != null)
{
return _predicate();
}

return true;
}

public void Execute(object parameter)
{
if (_action != null)
{
_action((T)parameter);
}
}

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}

public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class CitiesViewModel : ViewModelBase
{
private ObservableCollection<string> _cities;
private string _selectedItem;

public CitiesViewModel()
{
Cities = new ObservableCollection<string>
{ "Boston", "Los Angeles", "Houston", "New York", "Chicago", "Philadelphia" };

SelectedItemCommand = new DelegateCommand<string>(SelectionChange, () => true);
}

private void SelectionChange(string value)
{
SelectedItem = value;
}

public ObservableCollection<string> Cities
{
get { return _cities; }
set
{
if (Equals(value, _cities)) return;
_cities = value;
OnPropertyChanged();
}
}

public string SelectedItem
{
get { return _selectedItem; }
set
{
if (value == _selectedItem) return;
_selectedItem = value;
OnPropertyChanged();
}
}

public ICommand SelectedItemCommand
{
get; set;
}
}
}

And this is the output of the program. Posted by: Zeeshan Amjad | November 9, 2014

## Debug data binding

Sometimes debugging data binding is very time consuming. There can be several reason for data binding to not work. I came across one situation where the property is private.

Here is a small tip to debug the data binding. We can use Debugger.Break() method to put the break point and uses the converter to do this. Here is a small utility class to do this.

Code Snippet
namespace DebugBinding
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;

[ValueConversion(typeof(object), typeof(object))]
public class DebugDataBindingExtension : MarkupExtension, IValueConverter
{
#region IValueConverter

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Debugger.Break();
return value;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
Debugger.Break();
return value;
}

#endregion

#region MarkupExtension

public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}

#endregion
}
}

And here is a XAML to use this markup extension.

Code Snippet
<ListBox Margin="5" ItemsSource="{Binding Converter={local:DebugDataBinding}}"/>

Posted by: Zeeshan Amjad | May 20, 2014

## Using Tuple in ListBox

Tuple is a very handy generic utility class in .net that be very useful specially in lookup data situation. Let’s work on a simple example of displaying currency in the list box. In official ISO 4217 standard of currency code, there are currency code, number and the currency name. We can store this information in Tuple.

Code Snippet
public ObservableCollection<Tuple<string, int, string>> Currencies =
new ObservableCollection<Tuple<string, int, string>>();

Now let’s store some currencies information in it.

Code Snippet
Currencies.Add(new Tuple<string, int, string>("AED", 784, "United Arab Emirates"));
Currencies.Add(new Tuple<string, int, string>("AUD", 036, "Australian Dollar"));
Currencies.Add(new Tuple<string, int, string>("EUR", 978, "Euro"));
Currencies.Add(new Tuple<string, int, string>("GBP", 826, "Pound Sterling"));
Currencies.Add(new Tuple<string, int, string>("JPY", 392, "Japanese Yen"));
Currencies.Add(new Tuple<string, int, string>("MXN", 484, "Mexican Peso"));
Currencies.Add(new Tuple<string, int, string>("NZD", 554, "New Zeland Dollar"));
Currencies.Add(new Tuple<string, int, string>("QAR", 634, "Qatar Riyal"));
Currencies.Add(new Tuple<string, int, string>("SAR", 682, "Saudi Riyal"));
Currencies.Add(new Tuple<string, int, string>("USD", 840, "US Dollar"));

Using of Tuple in Listbox is very straight forward. We just bind Item1, Item2 etc in the Listbox. Here is complete XAML code of the program.

Code Snippet
<Window x:Class="WpfListBox.MainWindow"
xmlns
xmlns:x
Title="Tuple in Listbox" Height="300" Width="400">
<Grid>
<ListBox Margin="5,10,4.6,0.4" ItemsSource="{Binding}"
HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Item1}"/>
<TextBlock Grid.Column="1" Text="{Binding Item2}"/>
<TextBlock Grid.Column="2" Text="{Binding Item3}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>

Here is complete C# code of the program.

Code Snippet
using System;
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfListBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Tuple<string, int, string>> Currencies =
new ObservableCollection<Tuple<string, int, string>>();

public MainWindow()
{
InitializeComponent();

Currencies.Add(new Tuple<string, int, string>("AED", 784, "United Arab Emirates"));
Currencies.Add(new Tuple<string, int, string>("AUD", 036, "Australian Dollar"));
Currencies.Add(new Tuple<string, int, string>("EUR", 978, "Euro"));
Currencies.Add(new Tuple<string, int, string>("GBP", 826, "Pound Sterling"));
Currencies.Add(new Tuple<string, int, string>("JPY", 392, "Japanese Yen"));
Currencies.Add(new Tuple<string, int, string>("MXN", 484, "Mexican Peso"));
Currencies.Add(new Tuple<string, int, string>("NZD", 554, "New Zeland Dollar"));
Currencies.Add(new Tuple<string, int, string>("QAR", 634, "Qatar Riyal"));
Currencies.Add(new Tuple<string, int, string>("SAR", 682, "Saudi Riyal"));
Currencies.Add(new Tuple<string, int, string>("USD", 840, "US Dollar"));

DataContext = Currencies;
}
}
}

Here is the output of the program. Posted by: Zeeshan Amjad | April 22, 2014

## Fibonacci Word

I came across an interesting concept Fibonacci word. It is formed by repeated concatenation of symbols, usually two alphabets, using the Fibonacci numbers way.

Here are the first few words

F0 = a

F1 = ab

F2 = aba

F3 = abaab

F4 = abaababa

F5 = abaababaabaab

Let’s do this coding but first make a integer version of the program.

Code Snippet
static int[] Fibonacci(int no)
{
var fib = new int[no];

fib = 0;
fib = 1;

for (var i = 2; i < no; i++)
{
fib[i] = fib[i – 1] + fib[i – 2];
}

return fib;
}

Now let’s make the string version of the program.

Code Snippet
static string[] FibonacciString(int no)
{
var fib = new string[no];

fib = "a";
fib = "b";

for (var i = 2; i < no; i++)
{
fib[i] = fib[i – 1] + fib[i – 2];
}

return fib;
}

The integer version and the string version of the programs are very similar to each other. Let’s try to make a generic  function. This is our first attempt.

Code Snippet
static T[] Fibonacci<T>(int no)
{
var fib = new T[no];

fib = 0;
fib = 1;

for (var i = 2; i < no; i++)
{
fib[i] = fib[i – 1] + fib[i – 2];
}

return fib;
}

This program has two problem. First the initialization of the first and second elements of Fibonacci word. It can be easily solved by passing the initial values as a parameter. Here is a modified version of the program.

Code Snippet
static T[] Fibonacci<T>(int no, T first, T second)
{
var fib = new T[no];

fib = first;
fib = second;

for (var i = 2; i < no; i++)
{
fib[i] = fib[i – 1] + fib[i – 2];
}

return fib;
}

But there is still another problem. There is still a compilation error.

Error    1    Operator ‘+’ cannot be applied to operands of type ‘T’ and ‘T’

We can solve this problem with the dynamic keyword of C#. We can convert the last and second last item of the Fibonacci word using dynamic keyword before applying the concatenation words.

Here is a modified version of Fibonacci word.

Code Snippet
static T[] FibonacciGeneric<T>(int no, T first, T second)
{
if (no < 2)
return null;

var fib = new T[no];

fib = first;
fib = second;

for (var i = 2; i < no; i++)
{
dynamic last = fib[i – 1];
dynamic secondlast = fib[i – 2];

fib[i] = last + secondlast;
}

return fib;
}

Posted by: Zeeshan Amjad | March 12, 2014

## Mutual recursion with C++ lambda function

We already saw an example of doing recursion with C++ lambda function here. Here we saw that how can we use std::function to store the function pointer to call lambda function recursively, because lambda function doesn’t have any name.

Things are bit interesting in case of mutual recursion. In case of mutual recursion there are more than one functions calls each other. It means that now we need not one but two function pointers stored in C++ wrapper.

Let’s start with our first attempt to create a simple even and odd function.

Here is a simple equation of mutual recursion. In first step let’s create two wrappers for function.

Code Snippet
std::function<bool(int)> isEven;
std::function<bool(int)> isOdd;

Now lets create a function for this.

Code Snippet
isEven = [&isEven](int n) -> bool
{
if (0 == n)
return true;

else
return isOdd(n – 1);
};

isOdd = [&isOdd](int n) -> bool
{
if (0 == n)
return false;

else
return isEven(n – 1);
};

And we got the following error message.

error C3493: ‘isOdd’ cannot be implicitly captured because no default capture mode has been specified

error C3493: ‘isEven’ cannot be implicitly captured because no default capture mode has been specified

Now we have to specify the other lambda function in the lambda capture. Here is a modified version of the lambda function which implement mutual recursion.

Code Snippet
std::function<bool(int)> isEven;
std::function<bool(int)> isOdd;

isEven = [&isEven, &isOdd](int n) -> bool
{
if (0 == n)
return true;

else
return isOdd(n – 1);
};

isOdd = [&isOdd, &isEven](int n) -> bool
{
if (0 == n)
return false;

else
return isEven(n – 1);
};

Let’s see another example of mutual recursion. Here is a mutual recursive function for baby and adult rabbit pair in fibonacci sequence. Here is a C++ lambda function of this.

Code Snippet
std::function<int(int no)> babyPair;

babyPair = [&babyPair, &adultPair](int no) -> int
{
if (no == 1)
return 1;
else