Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday 3 June 2008

The Observer Pattern

Before we understand what an observer does, we need to define and understand the following.

The Subject     :  An object which does something...(verb) like publishing an Event, changing it's state etc. This object is the subject object. The observers are interested in getting a notification when The Subject 'does something'

The Observers :   Objects which are to be kept notified when the Subject Object's Event,State has Changed. Examples of Subject Object 'doing something' :

                - Subject Object publishes an event

                - Subject Object's State changed etc.

The publisher and the subscriber model is a good example to understand an observer pattern. (Check out Java's Action Listeners) The publisher publishes the event. Now, Let's say, a set of objects are interested in this Event and they need to perform an action based on this Event. Therefore they subscribe to this event to get a notification (callback) from the Publisher, which notifies them when the event occurs or about the event  itself.

To Give a real-life example, Consider a File Reader (program written in C# of course), which reads a file line by line to EOF. Now, let's say a list of Observers/Listeners should be notified after every line is read by the File Reader. Therefore, they register with the Subscriber (File Reader in our case), After which, they get notifications from the Subscriber whenever the File Reader finishes reading a line from the file. Let's say it also gives them the line which it has currently read in the notification mechanism.

The Observer Design

Observer

 

 

 

 

 

 

 

( really don't like the way the class designer associations behave in visual studio, MS please do something about it yaar! )

FileReader associated to IFileListener by the ListIFileListners property in the above figure. FileReader has a List<IFileListeners> field, which is used to maintain the list of registered listeners.

Now, the Code..

public interface IFileListener
{
//callback after every line is read.
void ILineRead(string LineRead);
}


public class FileReader
{
private List<IFileListener> listeners;

public FileReader()
{
listeners = new List<IFileListener>();
}

public List<IFileListener> ListIFileListener
{
get
{
return listeners;
}
set
{
listeners = value;
}
}

public void Register(IFileListener lis)
{
if (listeners.Contains(lis)) {
throw new Exception("Listener already registered..");
}
else {
listeners.Add(lis);
}
}

public void Unregister(IFileListener lis)
{
if(listeners.Contains(lis)){
listeners.Remove(lis);
}
else{
throw new Exception("Listener not registered..");
}
}
/// <summary>
///
Reads a line of text from the input file and
/// sends a callback to all registered listeners.
/// </summary>
/// <param name="filename"></param>

public void ReadFile(string filename)
{
if (File.Exists(filename)) {
TextReader txtReader = File.OpenText(filename);
string line = "";
while ((line=txtReader.ReadLine())!=null) {
foreach (IFileListener lis in listeners) {
//send callbacks to registered listeners
lis.ILineRead(line);
}
}
}
else {
throw new Exception("Input file does not exist..");
}
}

}



The Usage:



class Program:IFileListener
{
public Program()
{
FileReader reader = new FileReader();
reader.Register(this);
reader.ReadFile("textfile.txt");
}

static void Main(string[] args)
{
Console.WriteLine("testing observers..");
Program pgm = new Program();
Console.WriteLine("\npress any key to exit..");
Console.ReadKey();
}


#region IFileListener Members
/// <summary>
///
This method gets automatic call back with
/// the string line which is currently read.
/// </summary>
/// <param name="LineRead"></param>
public void ILineRead(string LineRead)
{
Console.WriteLine("Read Line: " + LineRead);
}

#endregion
}



The Text File Contents..



AAVARANA AND DA VINCI CODE: A COMPARISON

N.S. Rajaram


http://rajeev2004.blogspot.com/2007/02/literary-phenomenon-historical-novel.html


Like Dan Brown's Da Vinci Code, S.L. Bhyrappa's Aavarana is likely to have far-reaching social and political fallout that goes beyond its literary niche. In reading S.L. Bhyrappa's latest Kannada novel Aavarana, Dan Brown's best selling novel Da Vinci Code springs naturally to mind. Both have as their subject the suppression of true history and the propagation of a myth by powerful interests. In Da Vinci Code, the villain is the Catholic Church and its modern secret and sinister arm the Opus Dei. In Bhyrappa's novel, the villain is the collective of politically correct historians and 'intellectuals' who out a combination of greed and fear have suppressed the truth about Islam and its record in India. While these intellectuals—called dhimmis by the Egypt-born scholar Bat Ye'or—can boast of no Vatican or Opus Dei, they do form a powerful clique enjoying the support of successive governments who find it politically expedient to appease Islam and conceal the truth about its record and teachings. As this phenomenon is by no means limited to India, Bhyrappa's Aavarana, and the public reaction to it should be of interest far beyond its intended readership..



Dr.S.L.Byrappa is a living legend of Kannada litereature. Dr.S.L.Byrappa is one of the most popular writer and Kannada novelist. He has a Phd in Philosophy; his doctoral dissertation entitled “Satya Mattu Soundarya” (Truth and Beauty) explores complex relationships between truth, ethics, beauty, art, existence, and philosophy. He has written some of the celebrated novels like “Vamsha Vruksha”, “Daatu”, most notably his magnum opus,“Parva”.



The present novel “Avarana” meaning “veil” or “truth masking”, is his second historical novel covering the time period between 8th - 14th centuries of India. His first historical novel 'SArTa' covered the time up to 8th century. The latest novel Avarana is already going for its 10th edition2. The novel has seen nine editions

in four months after it was first published in February last. The conflict of truth v/s untruth is the topic explored in his previous novel Sakshi at individual level. AvaraNa explores the same problem at the global level. The twin objectives of the novel- explore history and expose historians, who are distorting it. In the book


Byrappa tries to show the real history of India under Moghuls. The Marxists and Seculars have created the myth that Muslim rulers were tolerant. They deny that there was mass temple destruction and mass Killing of Hindus. But, Dr.Koenraad Elst in his book “Negationism in India Concealing the record of Islam”3 writes- “The Muslim conquests,down to the 16th century, were for the Hindus a pure struggle of life and death. Entire cities were burnt down and the populations massacred, with hundreds of thousands killed in every campaign, and similar numbers deported


as slaves. Every new invader made (often literally) his hills of Hindus skulls. Thus, the conquest of Afghanistan in the year 1000 was followed by the annihilation of the Hindu population; the region is still called the Hindu Kush,i.e. Hindu slaughter. The Bahmani sultans (1347-1480) in central India made it a rule to kill 100,000 captives in a single day, and many more on other occasions. The conquest of the Vijayanagar empire in 1564 left the capital plus large areas of Karnataka depopulated. And so on.”



The Output of Program



testing observers..

Read Line: AAVARANA AND DA VINCI CODE: A COMPARISON


Read Line: N.S. Rajaram


Read Line: http://rajeev2004.blogspot.com/2007/02/literary-phenomenon-historical-novel.html


Read Line: Like Dan Brown's Da Vinci Code, S.L. Bhyrappa's Aavarana is likely to


have far-reaching



.



.



.

Read Line: large areas of Karnataka depopulated. And so on.?



press any key to exit..

Monday 2 June 2008

Hashing - Using C# and .Net Framework

A Cryptographic one-way hash function is used to generate a fixed length hash value as a transformation from a specific input. It should be computationally feasible in that it should

  • Not have the Avalanche Effect in producing the hash value
  • Given h it should be hard to find any m such that h = hash(m)
  • It should be collision resistant, i.e given an input m1, It should be hard to find another input, m2 (not equal to m1) such that  hash(m1) = hash(m2)
  • Resistant to Birthday attacks

.Net Framework BCL provides solid support to some cryptographic hash functions like MD5,SHA1,SHA128,SHA384 and SHA512. I've written a small demo program to compute hash and verify them using the listed cryptographic hash algorithms.

Class Diagram

Hashing_CS

 

 

 

 

 

 

 

 

 HashSHA 

HashSHA512 

TestHarness

Output

TestHarness_Output

Saturday 15 March 2008

Snake - 'Beta' for Compact Framework 2.0

Feeling bored that I didn't have a snake game on my phone, I wrote one for it. It just took me a day to write it and another day to polish and refactor code. There's nothing great about the features. It's just a simple snake game like the onez you 'used' to get in nokia 3310 phones, which is almost extinct nowadays.

However on the technology side,

there are two things i could accomplish.

1] I wrote a double buffering mechanism without utilizing any libraries or using DirectX. Yes!, This sample runs on plain and elegant 'winforms'. I've also used a separate mechanism to control the frame rate of the game / render loop () :-).

2] I used Asynchronous programming to smoothly fire off a pseudo-random generator , while the render loop continues in the same thread.

snake - 'beta' (simply because there aren't any great features and i don't intend to put any, unless i find myself awake on a summer night at 3am and completely jobless)

Sunday 9 March 2008

'System.IO.FileNotFoundException' while loading from Resource File (Pocket PC)

You get this exception when u try to read a bitmap from a resource file in compact framework. Even though the app. works fine, the exceptions can scare you , as it did for me, it seem to puzzle me and constantly psyched me, making me feel that i was doing something terribly insane ,therefore challenging my intellect.

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll




After painstaking analysis and innumerable Google searches i find the problem was with the CF CLR . the CLR tries to load two satellite assemblies and fails before it loads them from the current assembly (manifest resource). It's actually an issue with the .NET CF and the bug can be found here. Hmm, now i can go to bed peacefully..CF Team kiss my chaddees , bloddy hell innit?

Monday 18 February 2008

Recursive Descent XML Parsing

Hi,
A simple recursive descent parsing algorithm for parsing xml which i developed sometime back. Generally a recursive parsing algorithm is an idealistic approach for parsing xml documents with 'tree' sort of a structure. Most of the xml documents can be processed in .net using System.xml ,xpath expressions and various other techniques. But the generality for fetching the data in a certain order becomes important while processing the xml. for brevity's sake i'll consider an xml document which serializes a window.so, ideally the tree structure in the xml would look like the following.








Note the classic 'tree' structure here, i.e a 'container' node can contain other 'container' nodes as child nodes besides 'component' nodes. Therfore i used a recursive algorithm for parsing the tree.

the C# implementation:


internal void RecursiveDescentParseXML(XmlNode root)
{
XmlNode node = root;
Console.WriteLine(root.Name);
if (node.HasChildNodes)
{
XmlNodeList cnodes = node.ChildNodes;
foreach (XmlNode n in cnodes)
{
RecursiveDescentParseXML(n);
}
if (node.Name.ToString().Equals("window")) { }
else
{
Console.WriteLine("Node: " + node.Name +
" Should be added to : " + node.ParentNode.Name);
}
}
else{
Console.WriteLine("Node: " + node.Name +
" Should be added to : " + node.ParentNode.Name);
}
}