Class Divided

Just watched a old Frontline episode “Class Divided“. Amazing story. Teacher Jane Elliot in Riceville, Iowa started a experiment to teach her 3rd standard student on racial descrimination. After Martin Luther King assansination in 1968, She divided her class in “Blue Eyed” and “Brown Eyed”. On the first day, she told them Blue eyed people are superior to brown eyed people and it was amazing how sweet and innocent┬ákids turned into “brown eyed hating” kids. It makes me wonder if HATE is comes just as natually to us as LOVE.

Next day she turned the tables and made Brown eyed kids better. She gave preferential treatment to group of students just for one day and she saw improvement in scores for the people who were told to be superior and other way around. Now if one day can have this impact then, just imagine how much impact will it have if you multiple that with centuries of descrimination.

I loved the film. Great teacher!

Summer Sky and Leaf

Lamp

Gnostic Gospel Still running but Persian Fire Started

I went to library yesterday and saw this book that I just could not help bring home. So now I am listening to one book in the car and started reading one at home. This one is Persian Fire and written by Tom Holland who also wrote Rubicon. It is about Persian Empire. Essentially story before the Alexander. I just could get through about 20 pages till now but it seems like it definitely has a focus about Greek-Persian War.

There two interesting things I found out. There is this this third historical reference to “Aryans”. Off course everybody knows about “Third Reich and Aryans”. In India the tribes that came few thousand years through khyber pass and moved native Indian (Dravids) also called themselves Aryans. Now this book talks about tribes that lived in Zagros Mountains. One of these horse taming nomadic tribes (Median) basically brought the Assyrian (Modern day Northern Iraq) empire to its knees and destroyed it.

Astyages, Median King, had a dream (his daughter urinating without cease and his kingdom drowns) that was interpreted by his Magi (dream reader) as ‘any son of King’s daughter Mandane, would be destined to imperil the Median throne’. Now because of those King married off his daughter to a weak vassal of not so important kingdom, Persia. (Persia comes from the name of the tribe, Persua, that lived zagros and gulf coastline). After Mandane was pregnant, King dreamed again (Vine growing from between Mandane’s leg and putting all of Asia under its shadow). King waited till his grandson was born and then gave orders to kill boy. Apparently orders were defied and baby was abandoned on the mountain side where it grew up with some say Shepard or some say bandit etc. Anyway, the boy grew up to become the “Cyrus the great” founder of great Persian empire.

Now this whole story was interesting in itself but similarity of this story to the story of birth of Krishna in Mahabharata is also great. Krishna’s maternal uncle was a King Kansa and he dreamt that his sister (not daughter here) will give birth to a child that will kill him. Kansa immediately put his sister (Devki) and brother in Law (Vasudev) in the the prison. But somehow Krishna escaped and was left in Jamuna river, only to be found by people who raised cattle (Gokul). Krishna grew up and eventually killed his maternal uncle.

It is always interesting to see the similar stories in different parts of the world. One of them, being part of one of the Indian epic poems, nobody knows how much is true. For second one,  at least the characters in the story are true.

Gnostic Gospel is getting interesting too. Day before yesterday I was listening to the part where it talks about politics of monotheism. Apparently some of the gnostic believed that there are two separate gods. First God is God of old testament, he is the creator of this world but he punishes people if they don’t listen to him. He is almost vengeful, arrogant and jealous. Gnostic literature talks about how God was angry with Adam and Eve because they ate from the tree of knowledge. Why should God be jealous of Adam and Eve finding knowledge. Gnostics claim because he did not want to lose the position of absolute authority. Second god is the God of new testament, Father and One who forgives. Book talks about how one can find the roots of the slogan “I Believe in One God, Father Almighty and Creator of the World” has roots in Orthodox church trying to fight the ‘Heresy” of these two Gods.

 

Spartans

Earth! render back from out thy breast
A remnant of our spartan dead!
Of the three hundred grant but three
To make a new Thermopylae!


                               —-Lord Byron

Search Driven Shell

While coming to work today, I thought of something…

We have been using the term “Task Driven” UI for many years. But if a user sits at a computer and says “I want to Edit pictures, How do I do that?”. Most of the time end user have to navigate through start menu to find what they want. Vista Search UI also searches through the name. It does not find “Picasa” when I type in “Photo Editing”, it only finds it if I type in “pic…”. There is no way for user to know that what applications to use for certain tasks. So even though we talk about it, shell is not task driven at highest level. It is task driven if i got to explore and then i see tasks such as cut, paste depending on the context. There was a concept of categories at some point where there would be a store where app would register itself and shell can query to store to figure out something like this. Problem is to be able to provide information about app functionality in detail app authors would have to register for whole bunch of categories.

If application exposes some kind of interface (e.g. COM?) then shell can query on. This interface will expose the the description of all commands included in the application. Shell then can index all application installed on the machine through this channel and display user right application. So user can type in Start menu “Send email” and Outlook express, Outlook, Eudora could show up because they will have commands that say “send email”.

The problem is does this becomes a installer action that application will have to somehow tell shell about how to get handle to the interface. It could either through registry for MSI apps or Manifest for ClickOnce apps.

Command is a unit of functionality

So for the search driven UI, modules of functionality needs to be separated from UI completely. It should be loosely bound and functionality needs to be searchable. In WPF, this unit of functionality can be a Command. Command is an Object that implements ICommand interface. So I wrote a small sample that helps me understand this better. This sample shows how one can use commands to implement functionality. The way I implemented it also optimizes for the scenario where UI can be changed without any code change and no need for recompilations which can be useful in customization scenarios. This is an extreme case where UI does not have any event handlers but it only uses commands to implement functionality. To be able to support search driven functionality, it does not need to be that way but it proves the point that command can be unit of functionality. This off course is also used where same functionality is exposed through multiple UI. So it fits right with search driven UI where in response to different queries, different controls (tool bar, menu) need to adjust their visualization. Since controls can execute command, it will still work the way it is supposed to. This is a scenario where application needs to build functionality that can create a contact. I have an application that has a UI to show the contact form (First name, last name) and it has separate unit of functionality that it calls from this UI. It has a searchLibrary dll that we will talk later in detail that contains this functionality. It does not need to live in separate binary but I chose to do so that I can keep clear separation.

Application

In this small application there is no code at all. Everything is done through mark up so that markup can be loaded in loose xaml form without having to recompile the EXE. Application Xaml for the app looks like this. Off course it will need lot more work to make it work in real scenario.

<Application x:Class=”CustomUI.App” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” StartupUri=”Contact.xaml”> </Application>

UI Page

Contact.xaml mentioned above is a UI page that is responsible for showing the UI that user can interact with. As I said above none of the UI has event handlers and functionality is exposed through databinding to commands.

<Page
    xmlns=”
http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=”
http://schemas.microsoft.com/winfx/2006/xaml
    xmlns:customcommands=”clr-namespace:CommandLibrary;assembly=commandlibrary”
    Title=”Contact”
    >
    <Page.Resources>
        <customcommands:ContactDataElement x:Key=”ContactDataSource”>
            <customcommands:ContactDataElement.Parameters>
                <customcommands:Parameter Name=”FirstName” Value=”Joe”/>
                <customcommands:Parameter Name=”LastName” Value=”Johnson”/>
            </customcommands:ContactDataElement.Parameters>
        </customcommands:ContactDataElement>
    </Page.Resources>

    <Page.DataContext>
        <Binding Source=”{StaticResource ContactDataSource}”/>
    </Page.DataContext>
    <StackPanel>
        <StackPanel Orientation=”Horizontal”>
            <TextBlock Grid.Column=”0″ Grid.Row=”1″ >First Name</TextBlock>
            <TextBox Grid.Column=”1″ Grid.Row=”1″ Text=”{Binding Path=[FirstName]}”></TextBox>
        </StackPanel>
        <StackPanel Orientation=”Horizontal”>
            <TextBlock Grid.Column=”2″ Grid.Row=”1″ >Last Name</TextBlock>
            <TextBox Grid.Column=”3″ Grid.Row=”1″ Text=”{Binding Path=[LastName]}”></TextBox>
        </StackPanel>
        <StackPanel Orientation=”Horizontal”>
            <Button Grid.Column=”2″ Grid.Row=”4″ Command=”{Binding Path=SaveContact}” CommandParameter=”{Binding Path=Parameters}”>Ok</Button>
            <Button Grid.Column=”3″ Grid.Row=”4″>Cancel</Button>
        </StackPanel>
    </StackPanel>
</Page>

Important things to notice here are marked in bold…

  • First bold section is just a syntax so that XAML parser can find the classes declared below in the XAML
  • Second bold section where I describe the instance of the class that I need. This in real world would be dynamically generated. But as you can see, there is a class that encapsulates the logic of contact data. It has bunch of data that it stores as name value pair
  • Third bold section is where I databind Command property of the button to SaveContact property on ContactDataElement. ContactDataElement exposes the unit of functionality of saving a contact through ‘SaveContact’ property. SaveContact property returns a command to save a contact. It also exposes the Parameters property that will be passed in as argument to execute method on ICommand.

ContactDataElement

This is a class that I created so that I can store the parameters and command in one place. This way my UI can data bind to this object and UI can invoke the command. Here are the top things that this class supports.

  • This object supports indexer so that databinding can be done to properties that are stored in array of parameters. E.g. FirstName and its value is stores as a parameter object in the Collections. To be able to databind it, it needs to support syntax of ContactDataElement[“FirstName”], hence the indexer.
  • It has a property that returns a value of type ICommand. This is used to bind to controls command property so that control can call execute that command. ContactDataElement could support more command semantic such as delete contact, create new etc.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace CommandLibrary
{
    public class ContactDataElement
    {
        private Collection<Parameter> _parameters;
        private SaveContactCommand _savecontactcommand;

        public ContactDataElement()
        {
            _savecontactcommand = new SaveContactCommand();
            _parameters = new Collection<Parameter>();
        }
      
        public Collection<Parameter> Parameters
        {
            get { return _parameters; }
            set { _parameters = value;}
        }

        public ICommand SaveContact
        {
            get { return _savecontactcommand; }
        }

        public object this[string name]
        {
            get
            {
                Parameter namevalue = null;
                foreach (Parameter p in _parameters)
                {
                    if (p.Name.Equals(name))
                        namevalue = p;
                }
                return namevalue.Value;

            }
            set
            {
                Parameter namevalue = null;
                foreach (Parameter p in _parameters)
                {
                    if (p.Name.Equals(name))
                        namevalue = p;
                }
                namevalue.Value = value as string;

            }
        }
    }
}

SaveContact Command

This is a object that implements ICommand. It knows how to save a contact. Here are the two important things about this class.

  • Execute method encapsulates the functionality that needs to be exposed. In the example, I just show a message box in the execute call but imagine talking to database, webservice or file IO api to be able to save the contact.
  • Parameters Property: This is used to pass the data to execute method.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using System.Windows;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace CommandLibrary
{

    public class SaveContactCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        public delegate void CanExecuteChangedHandler(object sender, EventArgs e);

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            string data = null ;
            Collection<Parameter> parameters = parameter  as Collection<Parameter>;
            foreach (Parameter p in parameters)
            {
                data += p.Name + “*” + p.Value + “*”;
            }
            MessageBox.Show(“Saving to Store ” + data);
        }

        protected void ExecuteChanged(object sender, EventArgs e)
        {
            CanExecuteChanged(this, e);
        }
    }
}

Here is some extra information that does not pertain to this particular information…

FormPost

One could implement support for Formpost in the similar way. Only that really changes is execute method where you can post to a webserver and an extra property on the data element to store the URL where you are supposed to post back. Here I take the same parameters. Create a string out of it that is seperated using ‘&’. Then I create a webrequest for the URL specified write the string to stream and make a webrequest.

        public void Execute(object parameter)
        {
            Collection<Parameter> parameters = parameter as Collection<Parameter>;
            Console.WriteLine(“Post Collection using WebRequest”);

            WebRequest myHttpWebRequest = WebRequest.Create(_url);
            myHttpWebRequest.Method = “POST”;
            string postData = null;

            foreach (Parameter p in parameters)
            {
                postData += p.Name + “=” + p.Value + “&”;
            }

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] byte1 = encoding.GetBytes(postData);
            myHttpWebRequest.ContentType = “application/x-www-form-urlencoded”;
            myHttpWebRequest.ContentLength = byte1.Length;
            Stream newStream = myHttpWebRequest.GetRequestStream();
            newStream.Write(byte1, 0, byte1.Length);
            WebResponse myresponse = myHttpWebRequest.GetResponse();
            Object o = XamlReader.Load(myresponse.GetResponseStream());
            NavigationWindow ns = Application.Current.MainWindow as NavigationWindow;
            ns.Navigate(o);

        }

Other controls

Not all control expose Command properties and not interaction with control can cause command to be executed. E.g. TextBox does not expose a command property and what if I want (for some weird reason) want to execute a command on mouse over on a button or something. I could always implement a custom a control that inherits from TextBox and supports the commanding in the inherited class by implementing ICommandSource. From the customization perspective, this is where this method breaks down. There must be a better way to do this.