Saturday, October 23, 2004

Events/Delegates

Have you ever wondered whats the difference between events and delegates.
Yes/no whatever, just read on....
All the documentation that I have read makes them look like pretty differnt from each other. But, but just you wait.
My question is, what you can do with events, you can easily do with delegates? Right? Confused? Think...think :)


To get started check this example,

namespace DifferenceEvDel
{
using System;
delegate void BarkHandler(string s);


class DogApplication

{
public static event BarkHandler delegate1;
public static BarkHandler event1;
static void Main(string[] args)

{
delegate1 += new BarkHandler(DogBarking);
event1 += new BarkHandler(DogBarking);
delegate1("Bow!! Bow!! used delegate");
event1("Bow!! Bow!! used event");
}

static void DogBarking(string str)
{
Console.WriteLine(str.ToString());
}
}
}
Differnt approach, same result. Now you will agree on what I said in the begining.

MSDN clearly says :
"The event keyword lets you specify a delegate that will be called upon the occurrence of some "event" in your code."

Lets check out whats new in the events, point by point:

* Event can be invoked by the class which declared it. Delegate has no such restriction. Derived classes from the class declaring the event also aren't allowed to fire the event.

namespace DifferenceEvDel

{
using System;
delegate void BarkHandler(string s);

class BlueDog
{
public static event BarkHandler event1;
public static BarkHandler delegate1;
static void Main(string[] args)

{
delegate1 += new BarkHandler(DogBarking);
event1 += new BarkHandler(DogBarking);
new BlackDog().TeaseTheDog();
Console.ReadLine();
}

static void DogBarking(string str)
{
Console.WriteLine(str.ToString());
}
}

class BlackDog
{
public void TeaseTheDog()
{
BlueDog.event1("Bow!! Bow!! used events");
//The event 'DifferenceEvDel.BlueDog.event1' can only
//appear on the left hand side of += or -=
//(except when used from within the type 'DifferenceEvDel.BlueDog')
//Comment the above line to compile
BlueDog.delegate1("Bow!! Bow!! used delegate"); // compiles fine
}
}
}
An event of BlueDog can not be invoked from BlackDog, but a delegate can be.

*Accessor specifiers

When you put an access specifier(private, public etc.) on an event it controls who can register or listen to that event. Now, how would you specify the access control for the invocation of that event? In the question lies the answer :)

There will be two access modifiers like 'public public event' which is not so intutive. So as of now Event can be invoked by the class which declared it. But there are always ways to bypass this.

*Event can be included in an interface.

This one is the most important difference from the design perspective.
Try this in the same namespace
as above

namespace DifferenceEvDel
{
interface IDog
{
//Delegate in interface, error, comment this line to compile ;)
BarkHandler delegate1; //Err: Interfaces cannot contain fields
//Event in interface, its okey, Karry on I mean Carry on

event BarkHandler event1;
}

class Dog : IDog
{
public event BarkHandler event1; // Implement the interface
static void Main(string[] args) {}
}
}

*Events have an add and remove method(like get set).You can override these, so you can find out when somebody subscribes to your event.

public event BarkHandler event1
{
add
{
Console.WriteLine("Bow!! Bow!! I got added"); msgNotifier += value;
}
remove
{
Console.WriteLine("Bow!! Bow!! I got removed"); msgNotifier -= value;
}
}

My conclusion:
"Events are nothing more then a modifier on delegate type, Like all modifiers it adds some restrictions to be enforced by the compiler.

Keep watching this space for more events on delegates.

Friday, October 22, 2004

Holiday !!

This poem comes from a ten year old girl, whom I happen to know.
I rate it as one of the best poems I have ever read.
I feel swell whenever I read this :)

Holiday means a fun making day,
It comes on Sunday.
After all the hard work and play,
I rest for the whole day.
In the evening when the Sunday is coming to an end,
I look worried-
Mom says in an angry voice "Have you studied ?"
How can I say no ?
Because she will beat me so.
Now it is the time for Monday,
And again, after six days will come Sunday.
Because of MOnday all those who are sad,
They are all mad.
And don't realize that,
Sunday will come again, come again, come again.

Datasource for DataGrid

Our custom DataSource for Microsoft .Net DataGrid is finally working, fully!! I guess Chandra will not be able to find one more bug ;)
The problem was with the Allow New property.When you click in the last row of grid with asterisk, it changes to a pencil image.As soon as you click in the last row, the 'AllowNew' function of datasource (IBindingList.AddNew) is called.This adds a new object to the internal collection of data source. This object is in temporary state and its addition to datasoure will be cancelled if the user makes no changes to it and selects any other row or when he presses escape key. When you start typing in the last row a new row with asterisk sign will be added and the state of the object added to thecollection will be made permanent. The problem arises when the user does not makes any change and selects some already existing row.
In our datalist class as soon as the AddNew function is called we add an object and Raise an OnListChnaged event.But when the user cancels the operation the newly added row is removed from the Grids Internal Collection but there is no way we can get notified about this.The missing communication link can be taken care of by implementing IEditableObject in the class whose object will be stored in the DataList.But still there are problems. The DataGrid calls the item's IEditableObject.CancelEdit() function when you press ESC on an new row or activate a different row. But it never fires the ListChanged event nor does it remove the item from the data list. So there is no way for the list to remove the invalid new row from the data list.A new flag should be added, (called isNew) to the object that will be stored in the DataList.This should be exposed by either making it public or by using an internal property.By default it will be false but when a new object is added by using IbindingList.AddNew then it will be set to true using the exposed property.Check the implementation for more details and use of 'isNew'. As I don't feel like writing about it :)
For once the documentation/sample in MSDN are misleading and do not work.
Summary:
If you want to pass your own collection as DataSource for MS .NET DataGrid then implement IBindingList interface in your collection. If you want a strongly typed collection then use CollectionBase class as your base class otherwise use ArrayList. Most importantly, do not forget to implement IEditableObject interface in your classes whose objects you are going to store in your own collection.

Monday, September 13, 2004

Memory use in .NET

I was tinckering around with Performance Monitoring in .NET.
Here is something I found out
"Task manager in Windows shows the memory requested by the Application and not the memory used by the application"
From my side
"If a application has requested and has been allocated more memory (remember it may or may not be using it) then you need not get worried about it and say Oh!! my app using so much memory and try and optimize it because when OS needs the unused memory , ( when OS is low on available memory and some other application is requesting for it ) it will reclaim it automatically."
As of now its consistent with the results I am getting.
For amusement, create a simple Win App in Dot Net, run it and chk the memory usage in task manager.
Now maximize and minimize it and again chk the memory used by it.
For answer go to
.Net Urban Legend

The Curious Incident Of Dog In the Night

Some books in which a kid is narrating a story....

  • Catcher In the Rye
  • To Kill A Mocking Bird
  • The Curious Incident Of Dog In the Night
  • Life Of Pie

I get full kicked whenever I am reading such stuff. Its so nice to know that there are like minded people who had the same kind of feelings as kid, as you had. For example in 'The Curious Incident of Dog In the Night' this Boone chap dislikes strangers just like I do, though I act as if it does not matter, but I do. I have this uneasy feeling, may be some where I am trying to judge that person which is a bad habit but I do it. It takes a lot of time for me to reach a certain comfort level. There was only one single instance in my life when I approached a person. It never worked out the way I wanted it to.I don't know whether it was worth it or not, sometimes I am depressed about it.But as Boone says in the Dog book 'In life there are no straight answers'.

An Ideal Boy agrees, and moves on.

Saturday, September 04, 2004

Russian school hostage crisis

I and the public know.
What all schoolchildren learn.
Those to whom evil is done.
Do evil in return.
-W.H. Auden, poet (1907-1973)

No matter what their cause is, those who hide behind
children to save there lives, those who kill children
are not human beings.
Show no mercy towards them.

If you have a cause and you want to fight for it then
it should be man to man, face to face.

Is this what Kuran teaches Muslisms?
Do these people have faith in any religion?
I doubt....


Friday, September 03, 2004

Missing Class

Namespace: System.Reflection

Remarks: Represents a missing Object. This class cannot be inherited. Missing is used to invoke a method with a default argument. Only one instance of Missing ever exists.

Now when will you use this? When you have to pass a variable by ref set it to Missing.Value this is comparable to passing null to the function. Necessary because the C# null cannot be passed by reference.

Tuesday, August 31, 2004

Schadenfreude

Call me evil, but revenge is sweet. And now even the scientists back me.So if you feel cheated and hurt then its about time you pay him/her back as best as you can.

Kill-Bill

Thursday, August 26, 2004

And the song which I am singing these days....

Why does it always rain on me?

Sunday, August 22, 2004

The song which motivated millions.

Vande Maataram

Saturday, August 21, 2004

Who is Aurobindo?

That's the question somebody asked me last week, when I was in Pondicherry. Felt sick. I think if things continue the way they are soon all we will remember is Nehru,Indira, Rajeev and if I am not a bit over the top, Sonia too.
How many people are aware of the work of the likes of Bankim, Tilak, Vivekananda,Subramania Bharati, Tagore and Lala Lajpat Rai.
Nobody cares. In todays newspaper you can see half page advertisement of Tourism Ministry, with pictures of Rajeev Gandhi claiming how he transformed the Indian tourism industry. Bullshit, it just reflects the congress mantra "Lick your way up".
Just to give you a fare idea of the state of tourism industry, Shrilanka attracts more tourists then India. Come on somebody ask them to cut the crap.


Friday, July 02, 2004

Toothpaste

I am using Dabur Red toothpaste these days.

Comments made by my flatmates :
Neeraj: "Its different. It makes me nostalgic"
and Smarty was his usual dumb self
"It will make your teeth shine, Wow!! so much foam."

Smarty deserves a midnight cold water bath and willl get it very soon.

But its going to make you feel nostalgic only when you have used
Dabur Lal Dantmanjan when you were a kid.
Who can forget the classic ad associated with this product.

The middle aged Master-ji says "Bachchon yeh hai hamare danton ki banaawat. Raju tumhare daant to motiyon jaise chamak rahe hain"
And Raju replys "Kyon na hoon masterji, main dabur ka lal dantmanjan jo
istemal karta hoon"
Another smart-ass student follows up with "Aur Master-ji Aap ke daant?"
and then comes the jingle
"Danton ki kare hifajat moti sa chamkaye dabur laal dant manjan se mukhda khil khil jaye"

I cannot forget masterji's face in this ad and i cannot forget masterji's decaying teeth.
Wonder why they don't make such ads these days :(

Later they started showing a censored version of the ad where the "Aur Masterji, app ke dant?" part was cut because there was protest from Teachers Association.

Thursday, July 01, 2004

Blabber

I am in the 'Free pool', a term some management guy
has invented in my company to replace the usual 'Bench'
which was invented by some other management guy in some
other company, or is that the same guy who has shifted
from the other company.

I think I am brain dead.

Now, what will happen if I tell this to some people
overhere? The very next moment sombody will crack a PJ.
'Oh!! Do you have any?'
That kills me. It really does. But sometimes its really
fun to crack such PJ and check out the reaction.
Scene 1:
If I do this to any of my friends then all I am going to get
is a cold stare and total silence or an occasional burp or at max
a @#$% off.
Scene 2:
A mix of dumb guys and some girls, even one will do. And I repeat
the act. Oh, Boy!! I don't want to talk about it anymore.

Whats going on in my mind, sneeeek preview:
Its soo boring
Kya aap close up karte hain
I'll attend the interview
I'll not attend the interview
Will it rain if I go to Nandi Hill on Sunday
Where will we go for lunch today
Somebody mail me
Where is Jaggi
Main Dabur ka Lal Dant Manjan istemaal karta hoon
Dell QuiteKey Keyboard, thats a lie, its not quite at all
Its a long post
Its my third post
Who will read this
Gogo need a goggle

Again I am bored
Bored....................................................

Friday, May 28, 2004

Who is An Ideal Boy?

This is from one of the posters that we had in our K.G. classrooms. I have one, right here in my cubicle.

1. Gets up early
2. Brushes teeth daily
3. Respects elders
4. Takes bath daily
5. Goes for morning walk
6. Prays almighty
7. Studies attentively
8. Helps others
9. Respects elders
10. Takes part in sports
11. Joins N.C.C.
12. Attends social activities