Tuesday, July 5, 2011

Events

In my last post I tried to show some example on Delegate. Here I will give another example of Events.
In windows form based application or in web based application we use events very commonly(button click, page load etc). It is something like a function or method is registered to that event and whenever the event is fired the registered method executed.
In .net Events and Delegates works hand-in-hand to provide a program's functionality. For any pre-defined dot net events or user defined custom events can be registered with any kind of method but this process is done by a delegate, which specifies the signature of the method that is registered for the event. Below is the code as an example of simple Events declaration.

 

namespace Event
{
//public delegate void MyDelegate();
public class EventProgram:Form
{
//public static event MyDelegate MyEvent;

public EventProgram()
{
Button clickMe = new Button();

clickMe.Parent = this;
clickMe.Text = "Click Here";
clickMe.Location = new Point(
(ClientSize.Width - clickMe.Width) / 2,
(ClientSize.Height - clickMe.Height) / 2);

clickMe.Click += new EventHandler(OnClickMeClicked);

// MyEvent += new MyDelegate(OnStartEvent);
// MyEvent();
}

public void OnClickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("My Button is Clicked.");
}

public void OnStartEvent()
{
MessageBox.Show("My Start Event Started :) ");
}
static void Main()
{
Application.Run(new EventProgram());
}
}
}

In the above example we are using a windows form containing a button only. Clicking on that button the registered method will be executed.

clickMe.Click += new EventHandler(OnClickMeClicked);

By this line we have assigned a delegate for the click event of the button. and the implementation of the delegate is as below :
public void OnClickMeClicked(object sender, EventArgs ea)
{
MessageBox.Show("My Button is Clicked.");
}

Look carefully that we didnot send the argument 'sender' and 'ea' but we put the method name.
Also in the same code I have added a custom event sample which is commented. Just unblock the lines of code and it will clear the understating how delegate is being used for method registering in events.

Sunday, May 1, 2011

Events in .net

In my previous post I gave an example on how to implement Delegates of .net. Similarly I will use another example of Events in .net.


Saturday, April 30, 2011

Delegates

Probably all of us heard about 'Delegates' and 'Events' when we started learning .net programming, specially in case for an interview mostly this question is common to explain about delegate and event.
Today I am not going to give any bookish definition for delegates or events, because already we have heard million times that delegate is similar to function pointer. But when we need to implement delegates in code we really fall into a big trouble. I will try to make understand by few lines of code about how to create and call the delegate or the function pointer and I hope will be a big help for the beginners :).

 
namespace Delegates
{
public delegate int Comparer(object obj1, object obj2);


public class Name
{
public string FirstName = null;
public string LastName = null;

public Name(string first, string last)
{
FirstName = first;
LastName = last;
}
public static int CompareFirstNames(object name1, object name2)
{
string n1 = ((Name)name1).FirstName;
string n2 = ((Name)name2).FirstName;

if (String.Compare(n1, n2) > 0)
{
return 1;
}
else if (String.Compare(n1, n2) > 0)
{
return -1;
}
else
{
return 0;
}
}

public override string ToString()
{
return FirstName + " " + LastName;
}
}

class SimpleDelegate
{
Name[] names = new Name[6];

public SimpleDelegate()
{
names[0] = new Name("Rashedul", "Islam");
names[1] = new Name("Tanveer", "Rahman");
names[2] = new Name("Sarwar", "Hossain");
names[3] = new Name("Shehreen", "Haider");
names[4] = new Name("Rokon", "Rok");
names[5] = new Name("Mujahidur", "Rashid");
}

static void Main(string[] args)
{
SimpleDelegate sd = new SimpleDelegate();

Comparer cmp = new Comparer(Name.CompareFirstNames);

Console.WriteLine("\nBefore Sort: \n");

sd.PrintNames();

sd.Sort(cmp);

Console.WriteLine("\nAfter Sort: \n");

sd.PrintNames();

Console.ReadKey();
}

public void Sort(Comparer compare)
{
object temp;

for (int i = 0; i < names.Length; i++)
{
for (int j = i; j < names.Length; j++)
{
if (compare(names[i], names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = (Name)temp;
}
}
}
}

public void PrintNames()
{
Console.WriteLine("Names: \n");

foreach (Name name in names)
{
Console.WriteLine(name.ToString());
}
}
}
}

In this above example of code we have used delegate which calls a function to sort an array.

The line below is the declaration of the delegate which takes take two parameters.

public delegate int Comparer(object obj1, object obj2);

In the class name there is method named 'CompareFirstNames' which takes two arguments and compares the string and also returns a integer value. Actually we are going to pointing on this method by our declared delegate 'Comparer'.
Well now its time to instantiate the delegate and call the method using the delegate. If we look at the 'Main' method we can find how the delegate has been instantiated.

Comparer cmp = new Comparer(Name.CompareFirstNames);

Look carefully the above line, we did not used two object type parameters rather we passed a method who take similarly two object type parameters. So our new instance of delegate 'cmp' is pointing to the method 'CompareFirstNames' method.

Now we called the 'sort' method which takes a delegate type argument.

sd.Sort(cmp);

In the 'sort' method, compare is simply used as a function which returns an integer value to compare.

If you run the above chunk of code and debug then I hope you concept will be more clear on how delegate works.

I hope this post will be helpful understand delegate mechanism and in the very next post I will try to add similarly simple example on another .net feature Event.

Saturday, March 12, 2011

Outlook Calender email as an attachment

Microsoft outlook user can use the advantage of creating meeting/appointment calender or scheduler. But if you have to send the calender appointment as an attachment, so that the receiver can have the option to set meeting calender on his own outlook client then you have to create an .ics file.
Today I will briefly discuss about how to create an ics file and send it to the client.

Step 1: Create the content of an .ics file.
string meetingLocation = "My Place.";
string meetingSubject = "31st Night party";
string meetingDescription = "Celebration of new year.";
System.DateTime meetingBeginDate = Convert.ToDateTime("31/12/2011 10:00:00 PM");
System.DateTime meetingEndDate = Convert.ToDateTime("1/1/2012 11:00:00 AM");
String[] contents = { "BEGIN:VCALENDAR", "PRODID:-//Flo Inc.//FloSoft//EN",
                              "BEGIN:VEVENT","DTSTART:" 
+ meetingBeginDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"),"DTEND:" 
+ meetingEndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"), "LOCATION:" 
+ meetingLocation, "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" + meetingDescription,
"SUMMARY:" + meetingSubject, "PRIORITY:3", "END:VEVENT", "END:VCALENDAR" };

Step 2: Save it to server machine[could be in temp document folder] as an ics file.

System.IO.File.WriteAllLines(Server.MapPath("test.ics"), contents);

Step 3: Attach the file into email as an email attachment.

Attachment mailAttachment = new Attachment(Server.MapPath("test.ics"));
yourMailMessage.Attachments.Add(mailAttachment);

Where yourMailMessage is an instance object of type System.Net.Mail.MailMessage .

Now if the mail is sent ,the receiver will get an appointment file as an attachment and just by double clicking on that attached file user can add meeting to his outlook client.


Rest Service using WEB API C#

This post will show a simple example of REST service built on Micrsoft WEB API framework. WEB API is an extensible framework from microsof...