Thursday, 20 October 2011

How to apply for and find an Internship at Microsoft

We have posted on how you could apply to Microsoft for a scholarship to help fund your studies. If you are looking for an internship at Microsoft, then this post will definitely interest you. Microsoft accepts interns and offers Technical, Business as well as MBA Internships.
internship meeting How to apply for and find an Internship at Microsoft
If you are looking for a Technical Internship, Microsoft has the following areas to offer:
  1. Software DEvelopment
  2. Hardware Engineering
  3. User Experience
  4. Game Design
  5. Content Publishing
  6. IT & Operations
If you don’t want to waste your summer making a widget that will never see the light of day, you should definitely think of taking up an internship. And Microsoft could well, be one of the best places to be!

Taking up an internship at Microsoft could mean a lot to your career. As an intern at Microsoft, you’ll have real responsibility and real opportunities to make a difference. At the same time, you’ll also have a lot of fun with new friends and colleagues as you solve the technology challenges of the 21st century.
At Microsoft your projects matter and your team will be counting on your skills and insights. You’ll elevate your talent working along-side some of the best minds in the industry.
Visit Microsoft for more, if you decided to apply for one!

How to apply for a Students Scholarship to Microsoft

If you are looking out for some scholarship to help fund your studies, you may be happy to know that Microsoft too offers undergraduate scholarships to top students who want to study computer science and related technical disciplines.
student How to apply for a Students Scholarship to MicrosoftCurrently, Microsoft is offering four different types of technical scholarships for the 2012-2013 academic year to current undergraduate students:
  1. General Scholarships
  2. Women’s Scholarships
  3. Minority Scholarships
  4. Scholarships for Students with Disabilities
To be eligible to apply, you must be attending a school in North America. Moreover, if you are an international student currently studying in North America and meet their criteria for eligibility, you can apply regardless of your citizenship.

A Microsoft scholarship can help you pursue undergraduate studies in computer science and related technical disciplines. If selected, you will join a community of scholarship recipients from the United States, Canada and Mexico who share your passion for technology and academic excellence.
To learn more about application process, visit Microsoft.
If you need more information, get in touch with: scholars at microsoft dot com.

Screenshot Captor, a Screen Capture with a full set of scanner acquisition tools

At times, a user is required to capture a picture of what is on his screen and paste it into a document, e-mail message or some other file to demonstrate a program or a particular problem, or upload it to an image sharing website. Of many available screen shot capturing tools for Windows OS, Screenshot Captor is one. It offers some very useful features that an average user expects in an easy-to-use interface.
screenshot captor 400x300 Screenshot Captor, a Screen Capture with a full set of scanner acquisition tools
The program interface makes it easy to manage several screen-shots at once and allows users to save an image of an active window, full screen or any rectangular area as a graphics file. It endorses some basic editing features like cropping, highlighting and resizing. In a way, Screenshot Captor helps to grab screenshots with minimal intervention.
ScreenShot Captor 400x386 Screenshot Captor, a Screen Capture with a full set of scanner acquisition tools
The tool also allows you to enhance the captured screenshots with several blur and shadow effects and saves them in GIF, PNG, JPG, TIF and other formats.  All the capturing modes are easily accessible from a system tray icon or via customizable keyboard shortcuts.
It now also includes a full set of scanner acquisition tools and scanner image correction, allows a perfect capture of Windows 7 partial transparency effects and lets you easily upload screen-shots to image hosting services like Imageshack, Flickr, Photobucket, etc.
The following features make Screenshot Captor different from other screenshot utilities:
  • Full set of scanner acquisition tools and scanner image correction.
  • Perfect capture of Windows 7 partial transparency effects.
  • Easy automatic or on-demand uploading of screenshots to a wide variety of image hosting services
  • Smart auto-naming of files, and ability to embed textual comments in files.
  • Excellent multi-monitor support.
  • Optional automatic image file versioning.
  • Auto-scroll capture for windows too big for screen.
  • Deluxe thumbnail maker.
  • Quick Post-Capture PopUp Dialog.
  • Quick Screen-shot Emailer Menu.
Pros:
  • Simple to use
  • Great variety of capturing options
  • Many filters and effects to apply
  • Doesn’t take up much resources
Cons:
  • Causes problems while trying to apply some effects
  • Requires a learning curve
In all, Screenshot Captor establishes itself as a decent full featured screenshot capturing program for Windows. It is free for personal use, but you have to request for a license key, every six months.

Microsoft Debuts AT&T's Mango-Powered Windows Phone 7 Handsets

Microsoft showed off three Mango-powered Windows Phone 7 handsets that AT&T will be selling during the upcoming holiday season.
The smartphones were announced by the wireless carrier last month, but the public couldn't touch and feel the phones until their debut at the All Things D Asia Conference in Hong Kong.
Windows Phone 7 president Andy Lees unveiled the devices, which were manufactured by HTC and Samsung. There are the:
  • HTC Titan, with a spacious 4.7-inch display and front and rear cameras housed in a brushed aluminum shell that's only 9mm thick.
  • Samsung Focus S, with a 4.3-inch AMOLED display, front and rear cameras, a 1.4 GHz processor, super-thin profile and support for 4G speeds.
  • Samsung Focus Flash, the economy model in the group, with a 3.7-inch AMOLED display and 1.4 GHz processor.
Pricing and availability details haven't been released by AT&T.
Microsoft Debuts AT&T's Mango-Powered Windows Phone 7 HandsetsThe HTC TitanMicrosoft blogger Ben Rudolph gushed that the phones are "simply beautiful," but truth be told, though, if you were shown photos of the phones side by side, you would be hard-pressed to tell them apart. The handsets do look attractive, although for style in a Windows Phone 7 model, I still believe LG leads the pack with its recently released Jil Sander designer handset.
Unveiling of the AT&T handsets came on the same day that Microsoft announced it was "opening the spigot" on Mango, which it has been slowly rolling out since its release three weeks ago.
"I told you we planned to balance quality with speed," Eric Hautala, Microsoft’s general manager for customer experience engineering, wrote in a company blog. "And for three weeks we’ve been watching quality while sending update notices to a growing fraction of phones."
"It’s gone well," he continued. "So today we’re fully opening the spigot -- slightly ahead of schedule -- and making Mango available to nearly everyone in the current delivery pool."
He added that owners of some Windows Phone 7 models would be receiving a firmware update next week to enable their phones to take advantage of some of Mango's features.
Microsoft Debuts AT&T's Mango-Powered Windows Phone 7 HandsetsThe Samsung Focus SHis colleague Lees is expected to be a busy fellow in the weeks leading up to the holiday season. Lees will be the point man in Microsoft's campaign to win converts to the platform. Mango's release will make that job easier, although Lees still has to cope with the platform’s inability to support dual-core processors, something competitors Apple and Google have already adopted.
More Mango fireworks can be expected next week when Nokia holds its Nokia World show in London. At the event, it's believed the Finnish handset maker will introduce its new line of mobiles based on the Microsoft operating system. Earlier this year, the ailing Nokia announced that it was putting all its eggs in the Windows Phone 7 basket as a strategy to reverse its declining fortunes.

How to select the Best Mobile Phone..............?

With  new cell phones being launched every week in the market, it is at times very difficult to select a model …. now a days people are facing a problem of “plethora of choices “(i personally feel its an uphill task  to select the phone that best suits you in today’s time  ). So I have posted  some key points that will surely help you to decide which phone suits you the BEST ….. or else reading this will surely help you to lower the number of options …
mobiles How to select the Best Mobile Phone
So let the Search begin :–
Everybody has different priorities or likings but most of us will definitely consider the following factors while deciding (however it may not be in the same order )
  1. Cost :- The first thing that comes to one’s mind is to set the limit of your spending (because often you end up spending  10 – 20 % more than you actually planned earlier as  its a human tendency .. you cant help it  )
  2. Specification of Mobile :- Please ensure that the mobile phone that you are going to buy meets the minimum requirements  (we are never satisfied but yes we  do have an acceptance level above which we  start feeling satisfied ) which includes Processor , Built in memory (or a memory card) , Operating System (discussed in full detail later ) , Network Technology(GSM or CDMA) ,3-G Support .etc.
  3. Camera and Multimedia Features :- Amongst youth,  good camera and sound quality  is a top priority,  as mobile phones are the most common forms of entertainment, so try not to compromise on these features.
  4. Operating System :- With the launch of Google’s Android in 2007 a wide variety of operating systems are available with you  (Android is among the best ) so try to choose the best operating system  (or latest ) as the ease of using the phone depends on your operating system along with the processing speed of your mobile phone . Multiple choices for Operating Systems are now available in market such as  Android , Symbian , Windows etc .
  5. 3-G support :- Now a days 3G support capacity is a must with most of the service providers switching to 3 -G across the globe.
  6. Looks:- For many of us first thing that clique is the “zing of Looks” in a mobile phone.Looks can never be ignored it’s a very important deciding factor (especially with women clip image002 How to select the Best Mobile Phone) a good display and dashing looks is a very deadly combination  .
  7. Touch screen Or Key pad :- All  smart phones now a days come with touch screens and a good sensitive screen is always good to have (Capacitive screen must be preferred ) . Touch screen phones give you a whole lot better experience than the  phones without it, so going  for phones with both touch screen and keypad is better (Strongly consider this point if you communicate more via sms )

How to send email from C#

The Microsoft .NET framework provides two namespaces, System.Net and System.Net.Sockets for managed implementation of Internet protocols that applications can use to send or receive data over the Internet . SMTP protocol is using for sending email from C#. SMTP stands for Simple Mail Transfer Protocol . C# using System.Net.Mail namespace for sending email . We can instantiate SmtpClient class and assign the Host and Port . The default port using SMTP is 25 , but it may vary different Mail Servers .
The following C# source code shows how to send an email from a Gmail address using SMTP server. The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 and also using NetworkCredential for password based authentication.
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
  SmtpServer.Port = 587;
  SmtpServer.Credentials =
new System.Net.NetworkCredential("username", "password");





using System;
using System.Windows.Forms;
using System.Net.Mail;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add("to_address@mfc.ae");
                mail.Subject = "Test Mail";
                mail.Body = "This is for testing SMTP mail from GMAIL";

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

You have to provide the necessary information like your gmail username and password etc.

Wednesday, 19 October 2011

Windows 8 will startup in 8 seconds

http://www.youtube.com/watch?v=Qeiu0JnpMk0&feature=player_embeddedicrosoft today demoed the startup time for its new work-in-process operating system, Windows 8.
Windows 8 Video: Windows 8 will startup in 8 seconds
The key difference in the way Windows 8 shutdowns is that instead of closing the kernel session the way Windows 7 does, Windows 8 will hibernate it. This session 0 hibernate data file is much smaller as compared to the full hibernate data file, as a result it takes much less time to write to disk. You can read more about how Windows 7 currently shutdowns here.
Using this technique with boot gives Windows 8 a significant advantage for boot times, since reading the hiberfile in and re-initializing drivers is much faster on most systems.
Another important thing to note about Windows 8’s new fast startup mode is that, while Windows does not do a full “Plug & Play” enumeration of all drivers, it will still do initialize drivers in this mode.
This new fast startup mode will yield benefits on almost all systems, whether they have a spinning HDD or a solid state drive (SSD), but for newer systems with fast SSDs it is downright amazing.
Check out the video below to see for yourself:
Those of you like the old way of re-starting Windows, have an option in the UI to revert back to the Windows 7 shutdown/cold boot behavior, or since that’s likely a fairly infrequent thing, you can use the new /full switch on shutdown.exe. From a cmd prompt, run: shutdown /s /full / t 0  to invoke an immediate full shutdown. Also, choosing Restart from the UI will do a full shutdown, followed by a cold boot, says Microsoft.
In this quick startup mode, Windows 8 may take around 3-4 seconds to start, whereas from a cold start, you will get an 8 second boot!

Evolution of the Task Manager – From Windows 3 to Windows 8 w

The Task Manager is one of the most widely used apps in the Windows operating system. It has a long history, having first showed up in early versions of Windows as a simple utility to close and switch between programs.
In Windows 3, the Task Manager was just a simple utility to close and switch between programs and over the years several features and functionality has been added to it to make it what it is today in Windows 7. Using the Task Manager in Windows 7, you can now close applications, to find out detailed data about your processes, to start or stop services, to monitor your network adaptor, or even to perform basic system administrator tasks for currently logged on users.
See how the Task Manager has evolved from Windows 3 to Windows 7.
windows 3 task list manager Evolution of the Task Manager   From Windows 3 to Windows 8
windows nt task manager Evolution of the Task Manager   From Windows 3 to Windows 8
windows xp task manager Evolution of the Task Manager   From Windows 3 to Windows 8
Windows 8 goes a step further and adds much more. The Task Manager in Windows 8 will add many new features and even make changes to its UI.
The new Task Manager in Windows 8 looks much cleaner and focused now and does not overwhelm the user with too many details.
windows 8 task manager 1 Evolution of the Task Manager   From Windows 3 to Windows 8
But should he require more details, he can always click on the More details button.
windows 8 task manager Evolution of the Task Manager   From Windows 3 to Windows 8
Now if a particular process consumes above-normal resources, the column header will change its color to red/orange to draw your attention to it. This is the Heat Map.
Watch the video to learn more about the new Task Manager in Windows 8.
To learn about it, visit MSDN.

QTranslate: A free Translator Utility for Windows 7

QTranslate is a free Windows utility that translates texts using online translation services. Once the text is entered in a text-box, it automatically detects the language and displays the desired output in the second text-box.
QTranslate 7 QTranslate: A free Translator Utility for Windows 7
Input is translated using the most popular online language translation service – The Google Translate (default). However, one is free to choose any other online sources provided below;
  • Yahoo! Babel Fish
  • Microsoft Translator
  • Promt Mobile
  • SDL
QTranslate 11 600x355 QTranslate: A free Translator Utility for Windows 7
Translations can be performed from within applications, such as browsers, PDF readers, word processors, etc. The program also includes a built-in spell checking utility that tracks spelling of the provided inputs and translated texts.
The text entered is invariably translated in English, by default, but one has the option to select any preferred language from the drop-down menu for translation.
Translation services can be toggled by clicking on any of the web service names from the bottom of the interface.
QTranslate has two modes of translation by mouse selection,
  • Show icon- A program icon appears near the cursor whenever a text is highlighted or selected. Clicking on the icon opens up a window that displays translation of the selected text.
  • Show translation- Instantly displays the translated text of the selected text in a pop-up window. The headset icon on the right bottom of both text-boxes is readily accessible that can make the tool speak the text.
Qtranslate4 400x224 QTranslate: A free Translator Utility for Windows 7
The program also provides a virtual keyboard that has the capability to scan and view history page. To access the keyboard, click the keyboard icon residing at top right corner of the main interface and select desired language from the drop down menu.
QTranslate 6 QTranslate: A free Translator Utility for Windows 7
Main features of QTranslate in a nutshell:
  • Translates text in any application that supports text selection (Acrobat Reader, Google Chrome, Microsoft Word, Microsoft Outlook, Skype, etc.)
  • Text to speech synthesis and spell checking
  • Word suggestion/auto-complete (Ctrl+Space)
  • History of translations (Ctrl+H)
  • Virtual keyboard
Other settings for QTranslate can be configured from the system tray menu (Options). QTranslate 5 QTranslate: A free Translator Utility for Windows 7

Facebook launches inline translation tool using Bing Translator

In today’s busy world many parents remain unaware of their kid’s online activities. While you can always use Windows Live Family Safety to track and monitor activities, there are hundreds of programs out in the market that assure to protect and monitor your children online they cost a monthly subscription fee. Moreover, they are difficult to install.
qustodio 400x310 Monitor your child’s Online Activity with Qustodio, a free Parental Control program for Windows 7
Qustodio is a free program that monitors your kid’s online activities, their participation in social networks, chat programs and their surfing behavior. In a way, it helps to set healthy access limits, protect against inappropriate content and online predators.
The free parental control program’s advanced technology ensures that no content escapes from its supervision. The innovative Qustodio accommodates some best in class parental control, Internet monitoring features that are lacking even in some top priced solutions.
Some key benefits of using the program:
  1. Monitor social networking behaviors- Get instant alerts of your child’s suspicious activity when they are using any chat programs or surfing web.
  2. Tampering protection- No matter how technically advanced your kid is the freeware is tamper-proof and does not allow any manipulation with it.
  3. Limit online access- Sets healthy limits for your child’s online time. Also, the program’s web portal enables you to monitor and manage their activity from any location or device.
To download and install qustodio simply follow these steps:
  • Visit the official website
  • Click on the download link
  • Double-Click on the downloaded installer
  • The installer will start installing the app
  • Click on ‘Install’
  • Click on ‘Next’ and create an account with Qustodio if you do not have one.
  • Fill in all the essential details and click on ‘Next’
  • Enter the number of children that will be using the computer.
  • Enter  the names of children, click on ‘Next’
  • Furnish  basic credentials of your kids and click on ‘Next’ for one more time
  • Choose one account for all kids
Key Features of Qustodio:
  • Monitors social networking sites such as Facebook and Twitter of all friends and connections
  • Picks out bad content on sites immediately and classifies all websites dynamically
  • Endorses a cool and informative monitoring dashboard readily accessible from any device
  • Totally child proof
  • freeware
It is always a good idea to create a system restore point first before trying out any new software. Qustodio is compatible with Windows 7, Vista and XP.

Download VirtualBox 4.1.4 and get into the world of Virtualization

Oracle VM VirtualBox is a powerful and free x86 virtualization package for enterprise as well as home use. It was originally created by a software company named Innotek GmbH, which was then purchased by Sun Microsystem. It is now being developed and maintained by Oracle Corporation as part of its family of virtualization products. When installed on existing operating systems, it provides a virtual environment so that additional guest operating systems can be loaded and run, each with its own virtual environment.
Virtual box 600x427 Download VirtualBox 4.1.4 and get into the world of Virtualization
VirtualBox’s supported host operating systems list include:
  1. Windows 7
  2. Windows Vista
  3. Windows XP
  4. Linux
  5. Mac OS X
  6. Solaris
  7. OpenSolaris
VirtualBox also allows limited virtualization of Mac OS X guests on Apple hardware.
According to surveys conducted in 2011 by LinuxJournal and LifeHacker, VirtualBox was the most popular virtualization product and received over 50% of the vote. This application is full free as it is open source. It was initially offered by Innotek under a proprietary software license but in January 2007, VirtualBox Open Source Edition (OSE) was released as free software.

How does VirtualBox work

A virtual machine is created for a particular guest OS, a user can self-reliantly configure any virtual machine (VM). The host OS and guest OSs and applications can communicate with each other through a virtualized network facility provided by VirtualBox. Each GuestOS can be started, paused and stopped freely within its own simulated or virtual machine (VM).
Hard disks are emulated in a VirtualBox-specific container format called “Virtual disk image” (VDI), which are stored as “.vdi” files.
VirtualBox also provides graphics support through a custom virtual graphics card.
VirtualBox also virtualize following Network Interface Cards:
  • AMD PCnet PCI II (Am79C970A)
  • AMD PCnet-Fast III (Am79C973)
  • Intel Pro/1000 MT Desktop (82540EM)
  • Intel Pro/1000 MT Server (82545EM)
  • Intel Pro/1000 T Server (82543GC)
Up to eight network adapters can be attached at once, but only four are configurable through the graphical interface.
In the category of sound cards VirtualBox can virtualize:
  1. Intel HD Audio
  2. Intel ICH AC’97 device and
  3. SoundBlaster 16 cards.
A USB 1.1 controller can also be emulated which allows a user to use any USB devices attached to the host on the guest.
Conclusion
VirtualBox is the most common application used to run different virtual desktops on a host OS. It is the best application for testing new operating systems. We have already seen how to install Windows 8 on VirtualBox. If you want to improve the VirtualBox experience from the Windows 7 start menu try VBoxLaunch. It is free of cost because it is open source but its some of the special features which come in VirtualBox Extension Pack are under a closed source.

Collection initializer in C# 3.0

1. Collection initializer is new feature of C# 3.0
2. Collection initializer gives a simple syntax to create instance of a collection.
3. Any object that is implementing System.Collections.Generic.ICollection<T> can be initialized with collection initializer.
Let us say, we have a class
Student.cs




public  class Student
    {
       public string FirstName { get; set; }
       public string LastName { get; set; }
    }

Now if we want to make collection of this class and add items of type student in that collection and retrieve through the collection, we need to write below code
Program.cs




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> lstStudent = new List<Student>();
            Student std = new Student();
            std.FirstName = "Dhananjay";
            std.LastName = "Kumar ";
            lstStudent.Add(std);
            std = new Student();
            std.FirstName = "Mritunjay ";
            std.LastName = "Kumar";
            lstStudent.Add(std);
            foreach (Student resstd in lstStudent)
            {
                Console.WriteLine(resstd.FirstName);
            }
            Console.Read();
        }
    }

Output
clip_image002
In above code,
1. An instance of List of Student is getting created.
2. An instance of the Student is getting created.
3. Using the Add method on the list, instance of being added to list of students.
4. Using For each statement iterating through the list to get the values. Now, if instance of Student class can be assigned to List of student at the time of creation of instance of list then we call it automatic collection initializer.
clip_image004
If we see the above syntax
1. It is highly readable.
2. It is single statement.
3. Instance of Student class is getting added on the fly. And we can retrieve the values as below,
clip_image005
In retrieving implicit type local variable is being used to fetch the different instance of the student in list of student
Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> lstStudent = new List<Student>()
                                         {
                                             new Student{FirstName ="Dhananjay" ,LastName="Kumar"},
                                             new Student {FirstName ="Mritunjay", LastName ="Kumar"}
                                         };
            foreach (var r in lstStudent)
            {
                Console.WriteLine(r.FirstName);
            }
            Console.Read();
        }
    }

Output
clip_image007

How it internally works?
A collection initializer invokes the ICollection<T>.Add(T) method for each specified element in order. In the above example , it will call
ICollection<Student>.Add(instance of Student )

Introduction to Delegates and Events

This lesson introduces delegates and events. Our objectives are as follows:
  • Understand What a Delegate Is
  • Understand What an Event Is
  • Implement Delegates
  • Fire Events

Delegates

During previous lessons, you learned how to implement reference types using language constructs such as classes and interfaces. These reference types allowed you to create instances of objects and use them in special ways to accomplish your software development goals. Classes allow you to create objects that contained members with attributes or behavior. Interfaces allow you to declare a set of attributes and behavior that all objects implementing them would publicly expose. Today, I'm going to introduce a new reference type called a delegate.
A delegate is a C# language element that allows you to reference a method. If you were a C or C++ programmer, this would sound familiar because a delegate is basically a function pointer. However, developers who have used other languages are probably wondering, "Why do I need a reference to a method?". The answer boils down to giving you maximum flexibility to implement any functionality you want at runtime.
Think about how you use methods right now. You write an algorithm that does its thing by manipulating the values of variables and calling methods directly by name. What if you wanted an algorithm that was very flexible, reusable, and allowed you to implement different functionality as the need arises? Furthermore, let's say that this was an algorithm that supported some type of data structure that you wanted to have sorted, but you also want to enable this data structure to hold different types. If you don't know what the types are, how could you decide an appropriate comparison routine?  Perhaps you could implement an if/then/else or switch statement to handle well-known types, but this would still be limiting and require overhead to determine the type. Another alternative would be for all the types to implement an interface that declared a common method your algorithm would call, which is actually a nice solution. However, since this lesson is about delegates, we'll apply a delegate solution, which is quite elegant.
You could solve this problem by passing a delegate to your algorithm and letting the contained method, which the delegate refers to, perform the comparison operation. Such an operation is performed in Listing 14-1.
Listing 14-1. Declaring and Implementing a Delegate: SimpleDelegate.cs
using System;

// this is the delegate declaration
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;
    }

   
// this is the delegate method handler
    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[5];

    public
SimpleDelegate()
    {
        names[0] =
new Name("Joe", "Mayo");
        names[1] =
new Name("John", "Hancock");
        names[2] =
new Name("Jane", "Doe");
        names[3] =
new Name("John", "Doe");
        names[4] =
new Name("Jack", "Smith");
    }

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

       
// this is the delegate instantiation
       
Comparer cmp = new Comparer(Name.CompareFirstNames);

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

        sd.PrintNames();

        // observe the delegate argument
        sd.Sort(cmp);

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

        sd.PrintNames();
    }

    // observe  the delegate parameter
    public void Sort(Comparer compare)
    {
        object temp;

        for
(int i=0; i < names.Length; i++)
        {
            for (int j=i; j < names.Length; j++)
            {
                // using delegate "compare" just like
                // a normal method
                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());
        }
    }
}

The first thing the program in Listing 14-1 does is declare a delegate. Delegate declarations look somewhat like methods, except they have the delegate modifier, are terminated with a semi-colon (;), and have no implementation. Below, is the delegate declaration from Listing 14-1.
public delegate int Comparer(object obj1, object obj2);
This delegate declaration defines the signature of a delegate handler method that this delegate can refer to. The delegate handler method, for the Comparer delegate, can have any name, but must have a first parameter of type object, a second parameter of type object, and return an int type. The following method from Listing 14-1 shows a delegate handler method that conforms to the signature of the Comparer delegate.
    public static int CompareFirstNames(object name1, object name2)
    {
        ...
    }

Note: The CompareFirstNames method calls String.Compare to compare the FirstName properties of the two Name instances. The String class has many convenience methods, such as Compare, for working with strings. Please don't allow the implementation of this method to interfere with learning how delegates work. What you should concentrate on is that CompareFirstNames is a handler method that a delegate can refer to, regardless of the code inside of that method.
To use a delegate, you must create an instance of it. The instance is created, similar to a class instance, with a single parameter identifying the appropriate delegate handler method, as shown below.
        Comparer cmp = new Comparer(Name.CompareFirstNames);
The delegate, cmp, is then used as a parameter to the Sort() method, which uses it just like a normal method. Observe the way the delegate is passed to the Sort() method as a parameter in the code below.
        sd.Sort(cmp);
Using this technique, any delegate handler method may be passed to the Sort() method at run-time. i.e. You could define a method handler named CompareLastNames(), instantiate a new Comparer delegate instance with it, and pass the new delegate to the Sort() method.

Events

Traditional Console applications operate by waiting for a user to press a key or type a command and press the Enter key. Then they perform some pre-defined operation and either quit or return to the original prompt that they started from. This works, but is inflexible in that everything is hard-wired and follows a rigid path of execution. In stark contrast, modern GUI programs operate on an event-based model. That is, some event in the system occurs and interested modules are notified so they can react appropriately. With Windows Forms, there is not a polling mechanism taking up resources and you don't have to code a loop that sits waiting for input. It is all built into the system with events.
A C# event is a class member that is activated whenever the event it was designed for occurs. I like to use the term "fires" when the event is activated. Anyone interested in the event can register and be notified as soon as the event fires. At the time an event fires, registered methods will be invoked.
Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires. Listing 14-2 shows a couple different ways to implement events.
Listing 14-2. Declaring and Implementing Events: Eventdemo.cs
using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void Startdelegate();

class Eventdemo : Form
{

    // custom event
    public event Startdelegate StartEvent;

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

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

        // an EventHandler delegate is assigned
        // to the button's Click event
        clickMe.Click += new EventHandler(OnClickMeClicked);

        // our custom "Startdelegate" delegate is assigned
        // to our custom "StartEvent" event.
        StartEvent += new Startdelegate(OnStartEvent);

        // fire our custom event
        StartEvent();
    }

    // this method is called when the "clickMe" button is pressed
    public void OnClickMeClicked(object sender, EventArgs ea)
    {
        MessageBox.Show("You Clicked My Button!");
    }

    // this method is called when the "StartEvent" Event is fired
    public void OnStartEvent()
    {
        MessageBox.Show("I Just Started!");
    }

    static
void Main(string[] args)
    {
        Application.Run(
new Eventdemo());
    }
}

Note: If you're using Visual Studio or another IDE, remember to add references to System.Drawing.dll and System.Windows.Forms.dll before compiling Listing 14.2 or just add the code to a Windows Forms project. Teaching the operation of Visual Studio or other IDE's is out-of-scope for this tutorial.
You may have noticed that Listing 14-2 is a Windows Forms program. Although I haven't covered Windows Forms in this tutorial, you should know enough about C# programming in general that you won't be lost. To help out, I'll give a brief explanation of some of the parts that you may not be familiar with.
The Eventdemo class inherits Form, which essentially makes it a Windows Form. This automatically gives you all the functionality of a Windows Form, including Title Bar, Minimize/Maximize/Close buttons, System Menu, and Borders. A lot of power, that inheritance thing, eh?
The way a Windows Form's application is started is by calling the Run() method of the static Application object with a reference to the form object as its parameter. This starts up all the underlying Windows plumbing, displays the GUI, and ensures that events are fired as appropriate.
Let's look at the custom event first. Below is the event declaration, which is a member of the Eventdemo class. It is declared with the event keyword, a delegate type, and an event name.
    public event Startdelegate StartEvent;
Anyone interested in an event can register by hooking up a delegate for that event. On the next line, we have a delegate of type Startdelegate, which the event was declared to accept, hooked up to the StartEvent event. The += syntax registers a delegate with an event. To unregister with an event, use the -= with the same syntax.
        StartEvent += new Startdelegate(OnStartEvent);
Firing an event looks just like a method call, as shown below:
StartEvent();
This was how to implement events from scratch, declaring the event and delegate yourself. However, much of the event programming you'll do will be with pre-defined events and delegates. This leads us to the other event code you see in Listing 14-2, where we hook up an EventHandler delegate to a Button Click event.
        clickMe.Click += new EventHandler(OnClickMeClicked);
The Click event already belongs to the Button class and all we have to do is reference it when registering a delegate. Similarly, the EventHandler delegate already exists in the System namespace of the .NET Frameworks Class Library. All you really need to do is define your callback method (delegate handler method) that is invoked when someone presses the clickMe button. The OnClickMeClicked() method, shown below, conforms to the signature of the EventHandler delegate, which you can look up in the .NET Framework Class Library reference.
    public void OnClickMeClicked(object sender, EventArgs ea)
    {
        MessageBox.Show("You Clicked My Button!");
    }

Any time the clickMe button is pressed with a mouse, it will fire the Click event, which will invoke the OnClickMeClicked() method. The Button class takes care of firing the Click event and there's nothing more you have to do. Because it is so easy to use pre-defined events and delegates, it would be a good idea to check if some exist already that will do what you need, before creating your own.