Tuesday, March 24, 2009

Event Handling

Second is that event keyword adds accessor method for the event which are just like properties for the fields. While properties have get and set, event accessors have add and remove.
An event is a message sent by an object to signal the occurence of an action.

EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data.

To respond to an event, we need to do 2 things:

(1) Create a method to respond to the event. It must return void and accept two parameters: and Object and an EventArgs(or a derived class):
(Represents an event with no event data.)

private void button1_Click(object sender, EventArgs e)
{
//Method Code
}

(2) Add the event handler to indicate which method should recieve events:
this.button1.Click+=new System.EventHandler(this.button1_Click);
//Here, Click is the predefined event handler.
//We can also define our own as:
//public event ButtonEventHandler ButtonClick;
//this.button1.ButtonClick +=
//new ButtonEventHandler(button1_Click);

Here Click is a predefined EventHandler. When the event occurs, the method you specified will run.

Note that we can define the data for event, instead of using EventArgs:

public class AlarmEventArgs : EventArgs
{
private readonly bool snoozePressed = false;
private readonly int nrings = 0;
// Constructor.
public AlarmEventArgs(bool snoozePressed, int nrings) {...}
// Properties.
public int NumRings{ get { return nrings;}}
public bool SnoozePressed { get { return snoozePressed;}}
public string AlarmText { get {...}}

}

And also we can write our own the EventHandler:

public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);


The step of raise an event also has the following things:

(1) Create an event memeber:

public event AlarmEventHandler Alarm;

(2) Invoke the delegate within a method when you need to raise the event, as the following code demostrates:

AlarmEventArgs e =new AlarmEventArgs ();
if (Alarm != null)
{
//Invokes the delegates.
Alarm(this, e);
}
}

When we new an event memeber or handler, some people may ask why is it significant to use the keyworkd "event" here. It seems if we don't use key word event, like, public AlarmEventHandler Alarm; it also works, the reasons are below:

(1) Invoke restriction:
You don't want people to set the handler to be null and invoke your hander directly, see the blog here for explanation:
http://blog.voidnish.com/?p=20

(2)Event keyword allows the delegate declaration to be included in an interface specification unlike other fields and delegates which are not allowed.

(3)Event keyword adds accessor method for the event which are just like properties for the fields. While properties have get and set, event accessors have add and remove.

Another thing is that event handler can be built-in generic type:
eg:
EventHandler < MyEventArgs> temp = SampleEvent;
if (temp != null)
temp(null , new MyEventArgs(val));

Use Constraints in Generics

We use where clause to apply a constraints to a generic.

ex

class CompGen where T: IComparable
{
public T t1;
pbulic T t2;

public CompGen(T _t1, T _t2)
{
t1=_t1;
t2=_t2;
}

public T Max()
{
if(t2.CompareTo(t1)<0)
return t1;
else
return t2;

}
}

If we remove the where constraints clause, the compiler will return an error because generic type T does not contain a definition of CompareTo.

Thursday, March 19, 2009

Use Reflection to Dynamic Invoke a Method in a dll

We study a sample code below:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

class Program
{
static void Main(string[] args)
{
string path = @"C:\WINDOWS\Microsoft.NET\Framework\" +
@"v2.0.50727\System.Web.dll";

// Get the Assembly from the file
Assembly webAssembly = Assembly.LoadFile(path);

// Get the type to the HttpUtility class
Type utilType = webAssembly.GetType("System.Web.HttpUtility");

// Get the static HtmlEncode and HtmlDecode methods
MethodInfo encode = utilType.GetMethod("HtmlEncode",
new Type[] { typeof(string) });
MethodInfo decode = utilType.GetMethod("HtmlDecode",
new Type[] { typeof(string) });
// Create a string to be encoded
string originalString =
"This is Sally & Jack's Anniversary ";
Console.WriteLine(originalString);

// encode it and show the encoded value
string encoded =
(string) encode.Invoke(null, new object[] { originalString });
Console.WriteLine(encoded);

// decode it to make sure it comes back right
string decoded =
(string) decode.Invoke(null, new object[] { encoded });
Console.WriteLine(decoded);
}
}

Notice in case we don't need to specify the object type, we can use the code below:

MethodInfo meth=hastType.GetMethod("Add"); //no type parameters
meth.Invoke(hashTable, new Object[]{"Hello","Hi"}); //use Invoke "Add" method to add the Object {"Hello","Hi"} to the hashTable.