Tuesday, April 26, 2011

Object Oriented Programming Concepts

Object-oriented problem solving approach is very similar to the way a human solves daily problems. It consists of identifying objects and how to use these objects in the correct sequence to solve the problem. In other words, object-oriented problem solving can consist of designing objects whose behavior solves a specific problem. We can use following approaches

Abstraction is the process or result of generalization by reducing the information content of a concept or an observable phenomenon, typically in order to retain only information which is relevant for a particular purpose. For example, abstracting a leather soccer ball to a ball retains only the information on general ball attributes and behaviour. Similarly, abstracting happiness to an emotional state reduces the amount of information conveyed about the emotional state. Computer scientists use abstraction to understand and solve problems and communicate their solutions with the computer in some particular computer language.


Polymorphism is a simple concept that you understand right now, as it is prevalent through life. You are a person, which person is a base type and you are a more specific representation of that type. There are many people that inherit that type, of which you are a concrete implementation of that type: you have your own beliefs, attributes, and qualities that go beyond just a general person. For instance, we all have a blood type, shoe size, arm length, and many other properties. But we each add our own implementation to the person interface.

You drive an automobile, which this type has properties like wheel size, engine size, gas tank size, and other properties. The automobile you drive is a concrete implementation of the automobile interface. It has additional features, like sliding doors, logo type, cd changer slot count, moon roof lever location, or other various properties that are specific to the make/model of the car. In addition, automobile may have certain behaviors like open/close door, open trunk, turn wheel, and other behaviors that would be specific to an automobile.

In OO programming, using the automobile example, Automobile would be the base class, and each automobile manufacturer would have its own implementation. For instance, Honda has V-Tec technology, which is in its own implementation. Volvo uses diesel engines, which is the TDI technology. More importantly, you may add an added level of detail between automobile and the make/model implementation, such as Car, Truck, or Suv supertypes, to provide more relevant information.


Think of encapsulation as a black box; data is sent to a method, a lot of work goes on using the data, of which you don't know or care about. An output is returned to the caller. That is the process of encapsulation, or information hiding.

Thursday, April 21, 2011

Export data from XML to SQL Server

Some times  we need that we want to transfer the data from a XML file to the sql server.I know that there are several ways to do that.But this methods is quite simple and sort and obviously very fast.

Only we need to read xml file into a dataset then simply write this data to SQL server by SQLBulkCopy Command.And you are done.

        DataSet ds = new DataSet();
        DataTable dt = ds.Tables[0];
       // dt.Columns.Remove("HotelID");
       // dt.Columns.Remove("HotelFileName");
       // dt.Columns.Remove("HotelName");
       // dt.Columns.Remove("CityID");
       // dt.Columns.Remove("CityFileName");
       // dt.Columns.Remove("CityName");
       // dt.Columns.Remove("StateID");
       // dt.Columns.Remove("StateFileName");
       // dt.Columns.Remove("StateName");
       // dt.Columns.Remove("CountryFileName");
       // dt.Columns.Remove("CountryName");
       // dt.Columns.Remove("FolderName");
       // dt.Columns.Remove("FileName");
       // dt.AcceptChanges();
        string strconnection = "Data Source=Shert-PC;Initial Catalog=hotel;Integrated Security=True";
        SqlConnection con = new SqlConnection(strconnection);
        SqlBulkCopy sbc = new SqlBulkCopy(con);
        sbc.DestinationTableName = "tbl_xml"; 
        sbc.BulkCopyTimeout = 100000000;

Wednesday, April 20, 2011

Prevent Sql Injection in ASP.Net

A successful SQL injection attack enables a malicious user to execute commands in your application's database by using the privileges granted to your application's login. The problem is more severe if your application uses an over-privileged account to connect to the database. For example, if your application's login has privileges to eliminate a database, then without adequate safeguards, an attacker might be able to perform this operation.
Common vulnerabilities that make your data access code susceptible to SQL injection attacks include:
    * Weak input validation.
    * Dynamic construction of SQL statements without the use of type-safe parameters.
    * Use of over-privileged database logins.
To prevent the sql injection please copy and paste the following code into your app_code folder.And add a handler into your web.config files as follows-

    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=,  Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>      
    <add name="InjectFilter" type="Inject.InjectFilter"/>

and put the fololowing code into a class.
And your code is ready to use no external function or code to validate each input ot whatever you can use this in any new website or even old sites without making too much changes.

Happy Coding!!!!!!!!!!!!!!

 In C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.VisualBasic;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Inject
    public class InjectFilter : IHttpModule
        //Defines the set of characters that will be checked.
        //You can add to this list, or remove items from this list, as appropriate for your site
        public static string[] blackList = {
        ";--",  "/*", "*/", "@@","/script","xp_", "b.js", " char "," nchar "," varchar ", " nvarchar ", " alter ",
        "cast(",   " declare ",   "delete from",   "drop table",   "exec(",  "execute ",   "insert into",  "sysobjects ",
        "syscolumns ",  " update ", "<script>"
        public void Dispose()
        //Tells ASP.NET that there is code to run during BeginRequest
        public void Init(HttpApplication app)
            app.BeginRequest += app_BeginRequest;
        //For each incoming request, check the query-string, form and cookie values for suspicious values.
        private void app_BeginRequest(object sender, EventArgs e)
            HttpRequest Request = (sender as HttpApplication).Context.Request;
            foreach (string key in Request.QueryString)
            foreach (string key in Request.Form)
            foreach (string key in Request.Cookies)
        //The utility method that performs the blacklist comparisons
        //You can change the error handling, and error redirect location to whatever makes sense for your site.
        private void CheckInput(string parameter)
            for (int i = 0; i <= blackList.Length - 1; i++)
                if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
                    //Handle the discovery of suspicious Sql characters here
                    //generic error page on your site                  

                    if (HttpContext.Current.Request.RawUrl.ToLower().IndexOf("/admin") < 0 && HttpContext.Current.Request.RawUrl.ToLower().IndexOf("/merchant") < 0 && HttpContext.Current.Request.RawUrl.ToLower().IndexOf("/cutesoft_client")<0)

Monday, April 18, 2011

rename file if already exists in database while uploading

I like to use the the way windows allows for unique file or folders: New Folder --> New Folder (2) if the folder exists.
string fileName = /* your file path */
string newFileName = fileName;
int count = 2;
while (System.IO.File.Exists(newFileName))
    if(fileName.EndsWith("\\")) fileName = fileName.Remove(fileName.Length-1);

    string dir = fileName.Substring(0,fileName.LastIndexOf("\\"));
    string fName = fileName.Replace(dir, "");
    string name = fName.Split('.')[0];
    string ext = fName.Split('.')[1];
    newFileName = dir + string.Format("{0} ({1}).{2}", name, count.ToString(), ext);
// Here you would use your unique newFileName
I hope I understood you correctly

How To Add A Background Image In Gmail ?

You mean to add image in your email.if yes then you need to
1)Go to settings
2)Select Labs
3)Enable “Inserting images”
4)Save changes.

Now if you wish to add image in signature.follow these steps
1)Go to settings
2)under the general tab find Signature
3)For inserting an Image in the signature.first you have to upload the image in free image hosting sites.

for eg:go to imageshack.us. browse for the image you want to upload.and click upload.after its uploaded,copy the direct link

4)There is an image icon in the signature box.click on that and paste the direct link you copied from imageshack.us

That it. have a nice day

Create HTML Signatures Right Inside Gmail

Gmail Signatures Step-by-Step

Step 1: Go to Gmail Settings –> Labs and enable “Canned Responses” as well as “Inserting Images.”

Step 2: Compose a new message in Gmail and create a signature just like you would compose any other email message. Be creative!

You can either upload logos and icons* from the computer or use images that are already on the web. I suggest the former style as that will permanently embed the image into your email signature.

[*] You can find images of icons through Google Image Search. Go to Advanced options under image search and type 12 for height and width (use 16px if you are looking to add slightly bigger icons). While optional, you may also select the filetype as PNG or GIF for transparent backgrounds - see example.

Step 3: Once your happy with the formatting and layout of your new “HTML signature,” go to the Canned Response menu and Save – give some logical name like “Personal” for a signature that you want to attach to your personal emails

String.PadLeft Method

Returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character.
This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

PadLeft(Int32) Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length.
PadLeft(Int32, Char)    Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.
Example :- 1.ToString().PadLeft(4,'0')
Will show the results as "0001"
Source : -http://msdn.microsoft.com/en-us/library/system.string.padleft.aspx

Thursday, April 14, 2011

Call WebMethod from Javascript in ASP.NET

I needed to be able to remove a session variable from javascript so this post will
talk about how to call a webmethod from javascript to remove a session item. I will
be utilizing a JS file, ASP.NET page with a WebMethod exposed in it and an asp.net
user control. The basis of this is a few things: First we need an

<pre><asp:scriptmanager></pre> on the ASPX page with the EnablePageMethods property set to true:

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
            <uc1:ucMyControl ID="ucMyControl1" runat="server" />

Second we need to expose a static function in our ASPX code behind so it can be available to our javascript file.

    public static string ClearSessionItem(string item)
        if (HttpContext.Current.Session[item] != null)
             return "true";
             return "false";

Note the [WebMethod] above the function and that the function is static. This is what allows us to make it available to the javascript file.

Please make sure to add the statement using System.Web.Services; into the ASPX page, otherwise [WebMethod] will throw an error when compiling.

Third we need a ScriptProxyManager on the ASCX control with a reference to your JS file. This will also take care of including the JS file for your control as well so there is no need to add the <script src=....> tag. Put this as the first thing in your ASCX control.

<asp:ScriptManagerProxy ID="smp1" runat="server">
        <asp:ScriptReference Path="myJSFile.js" />

Fourth we need the code from the JS file to bring it all together:

   function ClearSessionItem(key) {
       //alert("I made it inside ClearSessionItem: " + key);     
       //now call server side method
       PageMethods.ClearSessionItem(key, OnSucceeded, OnFailed);

   function OnSucceeded(result, userContext, methodName) {
       if(result == "true")
            //do something
            //do something

   function OnFailed(error, userContext, methodName) {
       if (error !== null) {
          alert("An error occurred: " + error.get_message());


Anywhere in your javascript you can call the ClearSessionItem() method. Such as

function MyFunction(item){    

Also you could call it via an onclick event with an HTML element such as:

<pre><span onclick="ClearSessionItem('MySessionItem')">Clear Item</span></pre>

Of course you can use this concept for almost about anything. It allows you to not have a seperate
ASMX file (Web Service) in your project. Again, the concept here allows you to call
a server side method inside javascript.

Handling Postbacks in ASP.Net while using UrlRewriting

Handling Postbacks

If the URLs you are rewriting contain a server-side Web Form and perform postbacks, when the form posts back, the underlying URL will be used. That is, if our user enters into their browser, /Products/Beverages.aspx, they will still see in their browser's Address bar, /Products/Beverages.aspx, but they will be shown the content for ListProductsByCategory.aspx?CategoryID=1. If ListProductsByCategory.aspx performs a postback, the user will be posted back to ListProductsByCategory.aspx?CategoryID=1, not /Products/Beverages.aspx. This won't break anything, but it can be disconcerting from the user's perspective to see the URL change suddenly upon clicking a button.
The reason this behavior happens is because when the Web Form is rendered, it explicitly sets its action attribute to the value of the file path in the Request object. Of course, by the time the Web Form is rendered, the URL has been rewritten from /Products/Beverages.aspx to ListProductsByCategory.aspx?CategoryID=1, meaning the Request object is reporting that the user is visiting ListProductsByCategory.aspx?CategoryID=1. This problem can be fixed by having the server-side form simply not render an action attribute. (Browsers, by default, will postback if the form doesn't contain an action attribute.)
Unfortunately, the Web Form does not allow you to explicitly specify an action attribute, nor does it allow you to set some property to disable the rendering of the action attribute. Rather, we'll have to extend the System.Web.HtmlControls.HtmlForm class ourselves, overriding the RenderAttribute() method and explicitly indicating that it not render the action attribute.
Thanks to the power of inheritance, we can gain all of the functionality of the HtmlForm class and only have to add a scant few lines of code to achieve the desired behavior. The complete code for the custom class is shown below:
namespace ActionlessForm {
  public class Form : System.Web.UI.HtmlControls.HtmlForm
     protected override void RenderAttributes(HtmlTextWriter writer)
        writer.WriteAttribute("name", this.Name);

        writer.WriteAttribute("method", this.Method);



        if (base.ID != null)
           writer.WriteAttribute("id", base.ClientID);
The code for the overridden RenderAttributes() method simply contains the exact code from the HtmlForm class's RenderAttributes() method, but without setting the action attribute. (I used Lutz Roeder's Reflector to view the source code of the HtmlForm class.)
Once you have created this class and compiled it, to use it in an ASP.NET Web application, start by adding it to the Web application's References folder. Then, to use it in place of the HtmlForm class, simply add the following to the top of your ASP.NET Web page:
<%@ Register TagPrefix="skm" Namespace="ActionlessForm" 
   Assembly="ActionlessForm" %>
Then, where you have
, replace that with: and replace the closing
tag with:

Wednesday, April 13, 2011

Redirect HTTP to HTTPS with IIS 7

Getting onto two years ago now I wrote an article that has become quite popular that detailed three methods to redirect HTTP to HTTPS. At that time there wasn't a lot in the way of options for URL manipulation on IIS, and Helicon's ISAPI Rewrite 2 was the de facto standard. Now there are several options for rewriting URL's on IIS, and users of IIS 7 are able to take advantage of Microsoft's own URL Rewrite module. In this guide we'll look at how you can use Microsoft's URL rewrite module to transparently redirect HTTP to HTTPS.

For this guide to work you'll need;

  • IIS 7 installed

  • Microsoft URL Rewrite Module installed

  • Create HTTPS bindings to your IIS website and assign certificate

  • Ensure Require SSL is NOT checked under SSL Settings for your website

Once you have this done you can simply copy and paste the following code between the <rules> and </rules> tags in your your web.config file in your website root directory.

<rule name="HTTP to HTTPS redirect" stopProcessing="true">

  <match url="(.*)" />


      <add input="{HTTPS}" pattern="off" ignoreCase="true" />


  <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />


From here all you have to do is save your web.config file and test that the redirection is working. Hopefully this guide has helped you to enabled HTTP to HTTPS redirection for your website on IIS 7 using the Microsoft URL Rewrite Module. If you have any feedback or comments please post below, and if you have specific support requests please post in the forums

GOOGLE IME - Type anywhere in your language


Google Input Method: Type anywhere in your language

Smart, easy to use and intuitive!
Google Transliteration IME is an input method editor which allows users to enter text in one of the supported languages using a roman keyboard. Users can type a word the way it sounds using Latin characters and Google Transliteration IME will convert the word to its native script. Note that this is not the same as translation -- it is the sound of the words that is converted from one alphabet to the other, not their meaning. Converted content will always be in Unicode.
Google Transliteration IME is currently available for 22 different languages - Amharic, Arabic, Bengali, Farsi (Persian), Greek, Gujarati, Hebrew, Hindi, Kannada, Malayalam, Marathi, Nepali, Oriya, Punjabi, Russian, Sanskrit, Serbian, Sinhalese, Tamil, Telugu, Tigrinya and Urdu.
  • Offline Support
    No dependency on internet connection.
  • Word Completions
    Dictionary based word completions for prefixes.
  • Personalized Choices
    Remember user corrections along with macro and canonical support.
  • Easy Keyboard
    Dictionary enabled keyboard to enter rare and complex words.
  • Quick Search
    Single click web search for highlighted word.
  • Cool Customization
    Customize suggestions page size, display font and more
Google Transliteration IME is an input method editor which allows users to enter text in one of the supported languages using a roman keyboard. Users can type a word the way it sounds using Latin characters and Google Transliteration IME will convert the word to its native script. Note that this is not the same as translation -- it is the sound of the words that is converted from one alphabet to the other, not their meaning. Converted content will always be in Unicode. For example, typing "hamesha" transliterates into Hindi as: Hindi transliteration example and typing "salaam" transliterates into Persian as: Farsi transliteration example
Google Transliteration IME is available for 22 different languages - Amharic, Arabic, Bengali, Farsi (Persian), Greek, Gujarati, Hebrew, Hindi, Kannada, Malayalam, Marathi, Nepali, Oriya, Punjabi, Russian, Sanskrit, Serbian, Sinhalese, Tamil, Telugu, Tigrinya and Urdu.
Sample status window and the edit window for Hindi IME are shown below. For simplicity, Hindi IME is used as an example at most places in this help page.
Hindi IME
To install, download (If you are on a 64-bit Windows, make sure you have selected the 64-bit radio button in the download page) and run the installer and follow the instructions on screen.
  • More than one language IME can be installed on the same client machine.
  • Requirements are Windows 7/Vista/XP 32-bit/64-bit operating systems.
  • Only one instance of IME will be installed per machine but the configuration is done for each user using IME.
    Install Window
    Install Window
    Install Window

To uninstall, follow these steps:
  1. Click on the "Start" menu.
  2. Select "Control Panel" and then go to "Add or Remove Programs".
  3. In the program list, select the "Google <Language> Input", click on "Change/Remove" button.
  4. By default, "Retain my personal data with settings" option will be checked, which will not clean your personal customizations like display font, user correction cache etc., as part of uninstall. Uncheck the option, if you want to clean all your personal settings information.
  5. In the "Uninstall Google <Language> Input" dialog box, click "Yes".
    Uninstall Window
If you want to use IME with any application like notepad, you must first open the application and then open our IME. IME can be opened by clicking on the language bar on the desktop and then selecting the IME language icon or through a shortcut key if it's already configured. To close IME, you can change the language in language bar or try right clicking on the current application to see whether it supports 'Close IME' popup menu option or by closing the current application.
Displaying Language Bar
  • In desktop, right click on tool bar and select Toolbars -> Language bar
    Language Bar

Enabling Language Bar
If the 'Language bar' option is not visible in 'Toolbars', then it needs to be enabled through control panel:
Windows 7/Vista
  1. Control Panel -> Regional and Language Options -> Keyboard and Languages tab
  2. Click on Change keyboards... button to open Text services and input languages dialog
  3. Navigate to Language Bar tab
  4. Enable the radio button Docked in the taskbar under Language Bar section
  5. Apply all settings and try to display language bar as mentioned in previous section.
Windows XP
  1. Go to Control Panel -> Regional and Language Options -> Languages tab -> Text services and input languages (Details) -> Advanced Tab
  2. Make sure that under System configuration, option Turn off advanced text services is NOT checked.
  3. Go to Control Panel -> Regional and Language Options -> Languages tab -> Text services and input languages (Details) -> Settings Tab
  4. Click Language Bar
  5. Select Show the Language bar on the desktop. Click OK.
  6. If you are installing the IME for East Asian language or Right-To-Left language, go to Control Panel -> Regional and Language Options -> Languages Tab
  7. Make sure that options Install files for complex scripts and right to left languages and Install files for East Asian languages are checked in the checkboxes. This requires installation of system files and the system will prompt to insert the Operating System Disc.
  8. Apply all settings and try to display language bar as mentioned in previous section.

IME Shortcut
A shortcut key sequence can be applied to the IME as follows which can be used to quickly enable IME for any in-focus application:
Windows 7/Vista
  1. Control Panel -> Regional and Language Options -> Keyboard and Languages tab
  2. Click on Change keyboards... button to open Text services and input languages dialog
  3. Navigate to Advanced Key Settings tab
  4. If Google <Language> Input is not listed in Installed Services box, then click Add and in Add Input language dialog box, go to the language for which you want to enable IME in the languages tree and expand the node. Check the checkbox next to Google <Language> Input in the list.
  5. In Hot keys for input languages Select To <Language> - Google <Language> Input
  6. Press Change Key Sequence
  7. Select Enable Key Sequence
  8. Select option like Left ALT + SHIFT + Key 1
  9. Apply all changes
  10. Now opening an application like notepad and pressing Left ALT + SHIFT + Key 1 should open the IME.
Windows XP
  1. Control Panel -> Regional and Language Options -> Languages tab -> Text services and input languages (Details) -> Settings Tab
  2. If either <Language> or Google <Language> Input not listed in Installed Services box, then click Add and in Add Input language dialog box, select <Language> in Input language and Google <Language> Input in Keyboard layout/IME. Click OK
  3. Press Key Settings
  4. In Hot keys for input languages, Select Switch to <Language>-Google <Language> Input
  5. Press Change Key Sequence
  6. Select Enable Key Sequence
  7. Select option like Left ALT + SHIFT + Key 1
  8. Apply all changes
  9. Now opening an application like notepad and pressing Left ALT + SHIFT + Key 1 should open the IME.
Status Window
Whenever you enable our IME for an application either through a shortcut or through language bar, its status window will be visible on the screen. By default it will be placed at the bottom right corner of your desktop which can also be moved around. It is used for more configuration and controlling various features of our IME. It has three to five icons (depending on the language and features available) with leftmost being the application icon. Next to it are IME language indicator button, keyboard button (not present for Amharic and Tigrinya), canonical mode button (This button will be present if you have any canonical schemes associated with the IME) and menu button in that order.
Status Window
Edit Window
When the IME is enabled for an application like notepad and you start typing, IME displays the edit window with the typed text and the corresponding word choices in IME language. In the below example, user has typed 'googl' and the IME has displayed five choices numbered 1 to 5.
Edit Window
Navigation and Selection
By default the leftmost choice will be highlighted indicating active choice. Active choice can be changed by navigating other choices through BOTTOM-ARROW or TAB key - which moves the selection to the right; or through UP-ARROW or SHIFT+TAB keys - which moves the selection to left. To select one of the choices as the new word for your application, use ENTER key which inserts the active choice to the application at its current cursor position. Using SPACE or any other PUNCTUATION CHARACTER also inserts the active choice to the application along with the typed punctuation character. Exception will be when IME thinks that there is a better choice of word containing the punctuation character as part of the word itself. All the above controls only insert the active choice (highlighted) into the application. Another way to insert any choice even if it is not active is using its position number as: CTRL+<choice_number>.
Word Completions
When you type a word, the choices displayed in edit window will be either in BLACK or BLUE color. Intuitive partial word choices for the typed content are displayed in BLACK color which will always be grouped on the left side. If there are any better dictionary-based word completions for the typed content, they are displayed in BLUE color and grouped on the right side.
In the example being discussed, IME displays only 5 choices in the edit window which is the page size setting of the edit window. It can be configured through the menu button of the status window. If there are more choices than the page size set, then it will be displayed in the next page. Page navigation can be done through the small arrow buttons at the right bottom corner of the edit window or through PageUP and PageDown keys. Even when you navigate the choices with arrow or tab keys, the control moves to the next or previous page from either end of the edit window.
At anytime while typing in edit window, if you click the Google image on top right corner of the edit window, it triggers a web search for the active/highlighted choice in google.com. Search can also be triggered for non-active choice by right-clicking on any choice and then clicking the Search... drop-down button.
User Cache
There will be scenarios where the leftmost choice is not the one you are looking for and you select some other choice (second choice in the below example for typed word 'program') which will be inserted into the application.
User Cache
IME remembers this selection for the current user and when the user next types 'program' again, the last selected choice will now be displayed as the leftmost choice. To share this information across all applications for a user, this is persisted at user level even after closing the application. But this persisting behavior can be disabled through the 'Disable User Cache' option from menu button of status window. Note that caching doesn't apply if you select word completions. It is only for word choices shown in BLACK color.
User Cache
Switch to English
If you want to add both roman alphabet (typically English) content and IME language content to any application, there is an easy way to switch between the two. In one mode IME gives you choices in its language and in another mode it just emits what you have typed. Toggling can be done by clicking the IME language button in status window or through shortcuts: CTRL+G or F12.
Toggle Language
When you don't get some words as expected choices for any rare complex words; you can use the flexible keyboard to input any possible word. You can open the keyboard by clicking the keyboard button on status window or through the shortcut CTRL+K. Mouse is used to enter characters from the IME keyboard which also triggers word completions in the edit window. Keyboard can be closed by clicking the keyboard button again on status window or through shortcut keys: CTRL+K or ESC. There is also option to enter Zero Width Joiner (ZWJ) and Zero Width Non Joiner (ZWNJ) characters.
You can customize many features through IME's menu. Options available through the menu popup in status window are:
  • Change or activate one of the available canonical schemes (Option available only if there is atleast one scheme in the Schemes directory).
  • Select the font and size to be used to display the choices in IME language inside edit window (Suggestion Font).
  • Select the font and size to be used to display the English/Roman characters inside edit window.
  • Set the page size for edit window to restrict its size through number of choices.
  • Enable or disable the persistence of user cache.
  • Add/Edit or Delete macros using Manage Macros option.
  • Information about the IME like version.
  • Help, linking to this page.
Special Cases
There are some special cases in how IME behaves for some characters in some languages:
  • Example in Arabic for special case of SPACE where it is part of the typed word.
    SPACE Special
  • Example in Arabic for special case of PUNCTUATION where it is part of the typed word.
  • Example in Greek for special case of CAPITALIZATION where only first character being in uppercase in input retains its casing.
    Camelcase Special
  • Example in Greek for special case of CAPITALIZATION where all uppercase word in input retains its casing.
    Camelcase Special
  • Example in Greek for special case of DIGITS where number is converted digit wise instead of its whole value.
    Digit Special
User Defined Macros
IME supports adding custom user defined macros. Macros are short character sequences mapped to a word of your choice. When you type a character sequence, if there is a word corresponding to that sequence in the user-defined macros collection then it will be shown as the first choice in the Edit Window. You can manage the macros by choosing the 'Manage Macros...' option from the IME's menu.
Macros Menu
When you select this option the 'Manage Macros' dialog opens, allowing you to add, modify and delete the set of macros.
Macros Dialog
Adding a Macro entry
Click on the 'Add' button. This will add an empty row to the Macros List. You can double click (or select the cell and press F2) on the cell to add the new Macro entry.
  • Macro Text should consist of only alpha-numeric characters and the length should not exceed 100 characters. Macro Text is case-sensitive.
  • Macro Target should not contain any spaces and the length should not exceed 50 characters.

Removing a Macro entry
Select the cells you want to delete (Use Shift+Click to select a range or Ctrl+Click to select multiple disconnnected cells) and click on the 'Delete' button. Note that you cannot delete single cells. If you delete a cell, the full row will be deleted.
Modifying and Saving Macro Entries
  • You can edit any cell by double clicking it (or selecting the cell and pressing F2 key).
  • You can cancel the edit anytime by pressing the 'Esc' key or clicking outside the cell. Press the 'Enter' key to complete the edit.
  • After all edits are completed you need to click on the 'Save' button to save your changes.
  • You can click on the 'Discard' button anytime to discard all the changes made so far (after the previous save action).
Once you have the Macros in place you can use them while typing. For example if 'Mon' is mapped to Macro Text in the Macros, then when you type 'Mon' you will see Macro Text as the first option.
Macros In Action
Custom Canonical Transliteration Schemes
Transliteration IME supports adding custom transliteration schemes. Defining a scheme is done in a text file with a .scm extension. Once the scheme file is created you need to place it in the Schemes directory and when you start the IME the next time, it will automatically pick up the scheme files and provide you a menu option to choose one of the available schemes.
Canonical Schemes Menu

list of Ping Servers

Even the world’s best blog is nothing if no one can find it. Making sure your pages are indexed by search engines (and optimized for that purpose) is a good start, but you need to let some other guys know, too. Those guys are known as ping servers.
Basically, when you post a new article you “ping” these servers with the address (permalink) of your new post, they then schedule a crawl to include your new post in their database, which is then spidered by others, including search engines.
So, how do you do this? You can do it manually, or you can add a list of ping servers to your blogging engine (most engines support this).
Here’s my list:
  • http://rpc.technorati.com/rpc/ping
  • http://rpc.pingomatic.com/
  • http://api.feedster.com/ping
  • http://api.moreover.com/RPC2
  • http://api.my.yahoo.com/RPC2
  • http://xping.pubsub.com/ping/
  • http://ping.blo.gs/
  • http://ping.feedburner.com
  • http://ping.syndic8.com/xmlrpc.php
  • http://ping.weblogalot.com/rpc.php
  • http://rpc.blogrolling.com/pinger/
  • http://rpc.icerocket.com:10080/
  • http://rpc.newsgator.com/
  • http://rpc.weblogs.com/RPC2
  • http://topicexchange.com/RPC2
  • http://www.blogdigger.com/RPC2
  • http://www.blogstreet.com/xrbin/xmlrpc.cgi
  • http://www.newsisfree.com/RPCCloud
  • http://ping.weblogs.se/
  • http://blogmatcher.com/u.php
  • http://coreblog.org/ping/
  • http://www.blogpeople.net/servlet/weblogUpdates
  • http://bulkfeeds.net/rpc
  • http://trackback.bakeinu.jp/bakeping.php
  • http://ping.myblog.jp
  • http://ping.bitacoras.com
  • http://ping.bloggers.jp/rpc/
  • http://ping.blogmura.jp/rpc/
  • http://xmlrpc.blogg.de
  • http://1470.net/api/ping
  • http://bblog.com/ping.php
  • http://blog.goo.ne.jp/XMLRPC
  • http://api.feedster.com/ping.php
  • http://api.moreover.com/ping
  • http://api.my.yahoo.com/rss/ping
  • http://bitacoras.net/ping
  • http://blogdb.jp/xmlrpc
  • http://mod-pubsub.org/kn_apps/blogchatt
  • https://phobos.apple.com/WebObjects/MZFinance.woa/wa/pingPodcast
  • http://ping.amagle.com/
  • http://ping.cocolog-nifty.com/xmlrpc
  • http://pinger.blogflux.com/rpc/
  • http://ping.exblog.jp/xmlrpc
  • http://pingqueue.com/rpc/
  • http://ping.blogg.de/
  • http://ping.rootblog.com/rpc.php
  • http://rcs.datashed.net/RPC2/
  • http://rpc.blogbuzzmachine.com/RPC2
  • http://rpc.britblog.com/
  • http://rpc.tailrank.com/feedburner/RPC2
  • http://rpc.wpkeys.com/
  • http://services.newsgator.com/ngws/xmlrpcping.aspx
  • http://signup.alerts.msn.com/alerts-PREP/submitPingExtended.doz
  • http://www.a2b.cc/setloc/bp.a2b
  • http://www.bitacoles.net/ping.php
  • http://www.blogoole.com/ping/
  • http://www.blogoon.net/ping/
  • http://www.blogroots.com/tb_populi.blog?id=1
  • http://www.blogshares.com/rpc.php
  • http://www.blogsnow.com/ping
  • http://www.holycowdude.com/rpc/ping/
  • http://www.lasermemory.com/lsrpc/
  • http://www.imblogs.net/ping/
  • http://www.mod-pubsub.org/kn_apps/blogchatter/ping.php
  • http://www.newsisfree.com/xmlrpctest.php
  • http://www.popdex.com/addsite.php
  • http://www.snipsnap.org/RPC2
  • http://www.weblogues.com/RPC/
  • http://bulkfeeds.net
  • http://thingamablog.sourceforge.net/ping.php
  • http://pingoat.com/goat/RPC2
  • http://xmlrpc.blogg.de/
  • http://zing.zingfast.com
  • http://blogbot.dk/io/xml-rpc.php
  • http://www.catapings.com/ping.php
  • http://effbot.org/rpc/ping.cgi
  • http://rpc.wpkeys.com
  • http://rpc.britblog.com
  • http://ping.fakapster.com/rpc
  • http://pinger.blogflux.com/rpc
  • http://blogsearch.google.com/ping/RPC2
  • http://rpc.icerocket.com:10080
  • http://rpc.pingomatic.com
  • http://blogupdate.org/ping/
  • http://www.feedsky.com/api/RPC2
  • http://bitacoras.net/ping/
  • http://rcs.datashed.net/RPC2
  • http://euro.weblogs.com
  • http://www.bitacoles.net/notificacio.php
  • http://ping.blogoon.net/
  • http://www.weblogues.com/ping/
  • http://blo.gs/ping.php
  • http://www.weblogalot.com/Ping/
  • http://www.packetmonster.net/xmlrpc.php
  • http://blogsearch.google.com/ping
  • http://www.blogupdate.org/ping/
  • http://blogupdate.org/sverige/ping/
  • http://rcs.datashed.net/RPC2
  • http://ping.feeds.yahoo.com/RPC2/
  • http://www.syndic8.com/xmlrpc.php
  • http://pingoat.com/
  • http://www.mod-pubsub.org/ping.php
  • http://www.weblogues.com/RPC
  • http://rpc.odiogo.com/ping/
  • http://www.bloglines.com/ping/
  • http://api.feedset.com/ping
  • http://rpc.pingomatic.com/RPC2

Points To Improve Your Website Contact Form

No website is complete is without the contact form. Many people do not pay much importance to the contact form but you have to know that it is the one the most vital parts of your website. If it is not properly developed you might end up losing your prospective clients, which is a heavy price to pay. Many at times it can be frustrating and confusing to the user, so plenty of thought is put into developing a contact form understanding its significance. Here are some tips that will help you developing a good contact form.

Offer Contact Options

With the help of a contact form, you can turn a semi-interested customer into a client. Every contact form should be helpful to a user and should be developed keeping the user perspective in mind. While being helpful to users and useful in categorizing the type of request in order to prioritize and for data mining later–many drop down boxes do not provide with sufficient options to choose from. This will cause confusion among your users. So always, make the options available like “others” which will be easy for the user and can help him with not being confused especially when he is not able to determine the type of need.

Keep it Short

Who likes to write long stories in a contact form, neither does anyone have the time to do it. Therefore, it is better to make use of radio buttons and check boxes. This will reduce the time spent by the user but be sure to label them correctly and avoid technical terms or jargon’s which will be a big turn off for the user. Try to keep it as simple as possible.
Reduce the number of compulsory fields on your contact form. Ask what is needed and do not burden them with a lot of compulsory information.  Limit the number of compulsory questions.
If you see certain contact, forms are annoyingly long. So try to keep your contact form limited to the necessary information only. Sometimes users will leave by seeing a long contact form.

Submission Confirmation

Another problem that you must have noticed after submitting a contact form is that you receive an error message, a blank page or you will be sent back to the contact page. How can the user be sure that the information has been sent? Therefore, to avoid that always have a thank you page assuring them that their request has been submitted. Always make sure that this page is properly working at all times.

Be Careful with Captcha

Many contact forms have CAPTCHA, which is very much needed to cut down on spam. On many contact forms, I have seen that the image verification is so distorted that you cannot read it and keep on entering it and it comes back with errors. So if you are using a distorted image have an audio clip that will speak out the letters and numbers in the image for you. The best option is have a CAPTCHA that is quiet readable. Do not let it be a turn off for the users.

Source : - http://www.dragonblogger.com/6-points-improve-website-contact-form/

Google Changes SEO Game with Instant Search

With the new Google Instant Search now as you type for search terms Google will update the SERP pages in real time as you are typing and try to predict what you are looking for.
I was going to do a search for “Real Time Search” but while typing in Real Time into Google Search bar it assumed I was looking for Real Time Flight Tracker and already had displayed search results.
Google Changes SEO Game with Instant Search
In theory had I found what I was looking for with my first 2 keywords I may not have even typed further, so what this means is that bloggers, companies and users targeting keywords now must consider that Google will display results before they finish typing.  You not only need to use the “base keywords” of SEO terms, but look to see what Google tries to “assume” and possibly leverage some of those as well to increase your chances of your page showing up while a user is typing and hopefully they will see and stop before they type past what you were targeting.
No doubt about it, this change alters the SEO Landscape and no matter what the mega bloggers tell you, there is nobody with enough experience except Google themselves who will be able to tell you how to optimize for this new methodology of search.  I also this can lead to search distraction as a user may not even finish typing their search only to find a link to another site which may take their interest away form their original search topic.
Well, this is one Technology Blogger who is curious to see how this will affect the SERP rankings and SEO of my sites and I am wondering if there will be negative or positive results.

What Does “Pinging a Site” Do?

What Does “Pinging a Site” Do?

Okay, so what is pinging? You have probably heard of webmasters say, “I’ve got to ping my site” or ask, “Should I ping my site?” So, what is pinging and what does it really do? Lets take a look in the dictionary.


–verb (used without object)
1.to produce a sharp sound like that of a bullet striking a sheet of metal.
2.a pinging sound.  

Okay, maybe the definition of pinging isn’t exactly what webmasters are referring to, but pinging basically means that you are trying to notify sites that you made a change on a website that doesn’t have to be yours particularly.
Why webmasters mention this? It is most likely to be link building related which has to do with search engine optimization. Pinging simply gives a nudge to search engines like Google that your site has made an update, and will probably help to get your site indexed faster, although it isn’t 100%.
Some Situations You May Want to Ping
  • You got a quality backlink from an out of date site.
  • You want to rank for a keyword “quicker” than other sites.
  • You just like to ping because you like seeing some productive work done without you having to do anything.
Some Common Myths of “Pinging”
Q: Does pinging frequently help improve my site’s traffic?
A: Pinging does not really have any power on whether or not it will improve a site’s traffic performance, all it does is what it designed to do – notify sites about new updates and speed up the process. (Most site platforms already have autopinging configurations installed, so it isn’t really necessary, unless you really have to.)
Q: Does pinging give your site more superiority in ranking in the search engines?
A: I believe what webmasters are trying to say is that are webmasters that ping before other webmasters, have an upper hand just because the search engines found their sites first? The answer, is no, Google only ranks by the effort you put into link building and ranks your site accordingly to your site’s efforts of being search engine optimized as well. They don’t look at who wrote this first or whatever, they simply look for the most qualifying sites, that have nothing correlated to pinging what so ever.

Source : -http://www.mooladays.com/2009/06/10/what-does-pinging-a-site-do/

Working with Global.asax file in ASP.NET

Working with the ASP.NET Global.asax file

The Global.asax file, sometimes called theASP.NET application file, provides a way to respond to applicationor module level events in one central location. You can use thisfile to implement application security, as well as other tasks.Let's take a closer look at how you may use it in your applicationdevelopment  efforts.


The Global.asax file is in the root applicationdirectory. While Visual Studio .NET automatically inserts it in allnew ASP.NET projects, it's actually an optional file. It's okay todelete it—if you aren't using it. The .asax file extension signalsthat it's an application file rather than an ASP.NET file that usesaspx.

The Global.asax file is configured so that anydirect HTTP request (via URL) is rejected automatically, so userscannot download or view its contents. The ASP.NET page frameworkrecognizes automatically any changes that are made to theGlobal.asax file. The framework reboots the application, whichincludes closing all browser sessions, flushes all stateinformation, and restarts the application domain.


The Global.asax file, which is derived from theHttpApplication class, maintains a pool of HttpApplication objects,and assigns them to applications as needed. The Global.asax filecontains the following events:

Application_Init: Fired when an application initializes or is firstcalled. It's invoked for all HttpApplication object instances.

Application_Disposed: Fired just before an application isdestroyed. This is the ideal location for cleaning up previouslyused resources.

Application_Error: Fired when an unhandled exception is encounteredwithin the application.

Application_Start: Fired when the first instance of theHttpApplication class is created. It allows you to create objectsthat are accessible by all HttpApplication instances.

Application_End: Fired when the last instance of an HttpApplicationclass is destroyed. It's fired only once during an application'slifetime.

Application_BeginRequest: Fired when an application request isreceived. It's the first event fired for a request, which is oftena page request (URL) that a user enters.

Application_EndRequest: The last event fired for an applicationrequest.

Application_PreRequestHandlerExecute: Fired before the ASP.NET pageframework begins executing an event handler like a page or Webservice.

Application_PostRequestHandlerExecute: Fired when the ASP.NET pageframework is finished executing an event handler.

Applcation_PreSendRequestHeaders: Fired before the ASP.NET pageframework sends HTTP headers to a requesting client (browser).

Application_PreSendContent: Fired before the ASP.NET page frameworksends content to a requesting client (browser).

Application_AcquireRequestState: Fired when the ASP.NET pageframework gets the current state (Session state) related to thecurrent request.

Application_ReleaseRequestState: Fired when the ASP.NET pageframework completes execution of all event handlers. This resultsin all state modules to save their current state data.

Application_ResolveRequestCache: Fired when the ASP.NET pageframework completes an authorization request. It allows cachingmodules to serve the request from the cache, thus bypassing handlerexecution.

Application_UpdateRequestCache: Fired when the ASP.NET pageframework completes handler execution to allow caching modules tostore responses to be used to handle subsequent requests.

Application_AuthenticateRequest: Fired when the security module hasestablished the current user's identity as valid. At this point,the user's credentials have been validated.

Application_AuthorizeRequest: Fired when the security module hasverified that a user can access resources.

Session_Start: Fired when a new user visits the application Website.

Session_End: Fired when a user's session times out, ends, or theyleave the application Web site.

The event list may seem daunting, but it can beuseful in various circumstances.

A key issue with taking advantage of the eventsis knowing the order in which they're triggered. TheApplication_Init and Application_Start events are fired once whenthe application is first started. Likewise, theApplication_Disposed and Application_End are only fired once whenthe application terminates. In addition, the session-based events(Session_Start and Session_End) are only used when users enter andleave the site. The remaining events deal with applicationrequests, and they're triggered in the following order:














A common use of some of these events issecurity. The following C# example demonstrates various Global.asax events with the Application_Authenticate event used to facilitate forms-based authentication via a cookie. In addition, theApplication_Start event populates an application variable, whileSession_Start populates a session variable. The Application_Errorevent displays a simple message stating an error has occurred.

The Global.asax file is the central point forASP.NET applications. It provides numerous events to handle variousapplication-wide tasks such as user authentication, applicationstart up, and dealing with user sessions. You should be familiarwith this optional file to build robust ASP.NET-basedapplications.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. 

Source :- http://www.techrepublic.com/article/working-with-the-aspnet-globalasax-file/5771721

Tuesday, April 12, 2011

The Nullable Structure

The Nullable Structure

One of the problems with most value types is the inability to specify that they contain an undefined value. This is unlike reference types, which may hold a null reference to indicate that they have no value. The Nullable structure resolves this issue.

Nullable Values

Most value types do not provide a means to indicate that they contain an undefined value. Unlike reference types, which are null by default and can be set to a null reference in code, uninitialised value types contain a default value that lies within their normal range. One way to work around the problem is to designate a particular value to indicate that a variable is undefined. For example, if you have a variable that should only contain positive integers, you may decide that -1 indicates that the user has yet to provide a value. This is problematic when all possible values could are valid. For example, you may wish to have a Boolean with three states: true, false and undefined. This is often the case when working will nullable information from databases.

The Nullable type is a structure that solves the problem of representing undefined values. It is a generic type that acts as a wrapper to any value type, adding the ability to store a null value. It also adds some useful methods and properties that make working with nullable value types easy. The type only permits wrapping of value types, as it would be meaningless to create a nullable version of a reference type, which is already nullable by definition. To prevent you from attempting this, the generic type parameter employs a value-type constraint.

NB: Nullable numeric types have been discussed as part of the C# Fundamentals Tutorial. Here they were seen using the ? syntax, where int? is equivalent to Nullable. It should be noted that any value type, including custom structures, can be made nullable using the Nullable structure.

Using Nullable

There are several ways in which a nullable type can be instantiated. The first way that we will examine is using a constructor. The Nullable structure defines two constructors. The default constructor has no parameters and creates a value that is initially set to null. The second constructor accepts a single argument of the type being wrapped. When used, this generates a nullable variable that contains the provided value.

In the sample code below, two nullable integers are instantiated. The first will contain the value 10 and the second will be null.

Nullable value = new Nullable(10);
Nullable nullValue = new Nullable();

The Nullable structure also permits values to be assigned directly to variables. The assigned value may be of the type expected or null. The process employs implicit casting from T to Nullable to create the new values.

Nullable value = 10;
Nullable nullValue = null;

HasValue and Value Properties

The Nullable structure provides various methods and properties that make working with nullable values easy. The first two that we will look at are the HasValue and Value properties. The HasValue property returns a Boolean value that is true if the type contains a defined value and false if it is null.

Try adding the sample code below after the two previous declarations to see the property in action:

bool hasValue;
hasValue = value.HasValue;      // true
hasValue = nullValue.HasValue;  // false

The Value property returns a non-nullable version of the value held in the nullable type. However, if the variable is set to a null reference, reading this property throws an InvalidOperationException. In many cases it is sensible to check the HasValue property before attempting to read the Value.

int nonNullable;
nonNullable = value.Value;      // 10
nonNullable = nullValue.Value;  // Exception

GetValueOrDefault Method

The GetValueOrDefault method provides a second means for reading the value from a nullable type. When used with no parameters, the method returns the wrapped value if one is present. If the value is null, the method returns the default value for the wrapped type. In the case of our wrapped integers, the default value is zero:

nonNullable = value.GetValueOrDefault();        // 10
nonNullable = nullValue.GetValueOrDefault();    // 0

If you do not wish to retrieve the type's default value when null, you can provide your own default value by passing it to the method as the only argument. The following code demonstrates this by returning 99 for null values.

nonNullable = value.GetValueOrDefault(99);      // 10
nonNullable = nullValue.GetValueOrDefault(99);  // 99


We have already seen that a non-nullable value can be implicitly cast to a nullable version of the same type. This was seen in the second code sample with the line:
Nullable value = 10;

There is no support for implicit casting of a nullable value to its non-nullable counterpart. However, the Nullable structure does implement explicit casting. The following assignment is therefore valid:
nonNullable = (int)value;

The BigInteger Structure in ASP.NET4.0

The BigInteger Structure

Under some circumstances the standard integer data types provided by the .NET framework provide a range of values that is restrictive. The BigInteger structure, introduced in version 4.0 of the framework, removes the size limits.

What is a BigInteger?

The .NET framework version 4.0 introduced a new structure named BigInteger. This structure allows integer values of any size to be represented, unlike the previous integer types that had a fixed range of allowable values. BigIntegers allows you to store and process very large values without the risk of overflow exceptions and without considering the use of checked or unchecked arithmetic in most situations. These improvements do come with some limitations however, as it is not always as easy to work with BigIntegers as it is with the earlier types.

In this article we will see some examples of the use of BigInteger values and the operators, methods and properties of the new structure. To follow the examples, create a new console application. The BigInteger type is found in the System.Numerics.dll assembly, so add a reference to the assembly to your project. Finally, the structure is found in the System.Numerics namespace, so add the following using directive to your code file:

using System.Numerics;

Creating a BigInteger

Instantiating a BigInteger is easy when you wish to initialise it with a value that is within the range of one of the previously available numeric data types. For example, we can create a new BigInteger and apply an integer value to it using the assignment operator as follows:

BigInteger big = 1000000;

The above statement works because the integer types allow implicit casting to BigInteger. We can also instantiate a new BigInteger using the default constructor for the type. In this case the new value will be zero:

BigInteger big = new BigInteger(); // 0

Many other BigInteger constructors exist. Most include a single parameter that is used to initialise the new value. You can pass a 32-bit or 64-bit integer or unsigned integer or a double to the argument. For example, the next line of code initialises a BigInteger with the maximum value that can be assigned to an unsigned 64-bit integer.

BigInteger big = new BigInteger(ulong.MaxValue); // 18446744073709551615

The three methods describe above can only be used to create BigIntegers with values the lie within the range of one of the types available in earlier versions of the .NET framework. This limitation exists because you cannot define a BigInteger literal in C#. If you wish to initialise a variable with a larger value, you can use the final overloaded version of the constructor. This has a single parameter that accepts an array of bytes. The array represents a standard value using little endian byte order, meaning the least significant byte is the first element in the sequence.

BigInteger big = new BigInteger(new byte[] { 0, 0, 16, 99, 45, 94, 199, 107, 5 }); // 100000000000000000000

The last method of initialising a BigInteger is to parse a value from a string. This is particularly useful when the value is to be entered by the user. As with other numeric types, the BigInteger structure supports the use of Parse and TryParse to attempt to convert a string to a value. These methods can be used with specified number styles if required. The following simple example uses Parse with default options.

BigInteger big = BigInteger.Parse("100000000000000000000");

Source :-  http://www.blackwasp.co.uk/BigInteger.aspx

C# Events and Delegates in ASP.net

C# Events

Events can be added to a class to allow it to indicate when a specific action has occurred or is about to occur. Subscribers may then react to the event.

What is an Event?
In the first fourteen parts of the C# Object-Oriented Programming tutorial we have described the creation of classes with methods, properties and other structures. Each of these is similar because it allows a direct command to be given to a class or object within the flow of a program. This is similar to the early programming languages, which simply processed a sequence of commands and loops until complete.
The sequential or procedural method of programming is limited to this type of processing. However, C#'s object-oriented approach is also event-driven. This means that as activities occur, a class may raise events to indicate the action that happened and to pass related information to other classes that have subscribed to the event. These may be used for various purposes including indicating the progress of a long-running process.
A key advantage of using events is that a class that publishes an event does not need to know the details of the subscribers at design-time. As events are based upon delegates, the subscribers are only added when the program is running.

Creating an Event
There are three parts to creating an event handler within a class. Firstly a delegate is required. The delegate is used to hold the details of the subscribers to the event. Secondly, a public event is created. This event is visible externally to the class and used for creating the event subscriptions. It is also the member that is visible using Visual Studio's Intellisense feature. Finally, a method is created within the class. The method contains the code that fires the event. Each of these three elements is described in the following sections.
To provide an example of the use of events, we will create a new program containing a class that represents a car. When the car's speed exceeds a safety limit, an event will be fired. To begin, create a new console application named "EventDemo". Add a class file named "Car" to the project and add the following code to the class to create a read-only Speed property and an Accelerate method. The _safetySpeed variable holds the maximum speed permitted and will be used later.

class Car
    private int _speed = 0;
    private int _safetySpeed = 70;
    public int Speed
return _speed;       
    public void Accelerate(int mph)
       _speed += mph;   
Creating the Delegate

The delegate for an event is declared using the standard syntax for any delegate. However, it should be declared with a data type of void as events are multicasting. This means that multiple subscribers can be attached to a single event with each being notified of the event in turn.

The delegate's signature is important as this is the signature that subscribers will see. To comply with the expected standards, the signature should contain two parameters. The first parameter should be an object named 'source'. This will contain a reference to the object that raised an event. The second parameter should be of the type EventArgs and should be named 'e'. EventArgs is a special class that can be derived from to create custom classes for passing information when an event fires. This is described later in this article.

In this example we will add an event to the Car class that is raised when the car exceeds the safety limit speed. To create the delegate for this event, add the following code to the namespace (outside of the class definition).
delegate void SpeedLimitExceededEventHandler(object source, EventArgs e);

Declaring the Event

The event is the publicly visible element of the class. It can be subscribed to by other classes that wish to react to the event being fired. The event is declared by prefixing its name with the event keyword and the name of the delegate that the event will be based upon. To create the event for the Car class, add the following to the class:
public event SpeedLimitExceededEventHandler SpeedLimitExceeded;
Creating an Event Method

An event method is a single method used to raise an event. Although it is not strictly necessary to create such a method, it is advantageous as it makes maintenance of the code simpler and allows derived classes to override the functionality and alter the manner in which events are fired.

To create the event method for the SpeedLimitExceeded event, add the following code to the Car class.

public virtual void OnSpeedLimitExceeded(EventArgs e)
    if (SpeedLimitExceeded != null) SpeedLimitExceeded(this, e);

There are several items to note in this method. Firstly, the method is marked as virtual. This keyword will be described in detail later in the tutorial. It means that the functionality of this method may be overridden and changed by classes that are derived from the Car class.

The method is named using the name of the event and the prefix 'On'. This is a simple convention that developers expect to see. The event method requires only a single parameter containing the event arguments for the raised event. This parameter holds all of the information that is to be passed to the event subscribers.

Within the method's code block, an if statement checks to see if the event is set to null. This conditional statement checks that there is at least one subscriber to the event as if there are no subscribers, firing the event would cause an exception to be thrown. If the test is passed, the event is raised as if it where a method, passing a reference to the current object and the event arguments that were passed in the parameter.

Calling the Event Method

To complete the sample Car class, the event method needs to be called when the car accelerates past the safety speed. Amend the Accelerate method as follows so that the event is raised when the car's speed changes from below or equal to the safety speed to above it.

public void Accelerate(int mph)
    int oldSpeed = _speed;
    _speed += mph;

    if (oldSpeed <= _safetySpeed && _speed > _safetySpeed)
        OnSpeedLimitExceeded(new EventArgs());

Subscribing to an Event

To subscribe to an event, a reference to a method must be added to the event. This is achieved in a similar manner to adding references to a multicast delegate. Each method that is to be called when the event is raised is added to the event using the addition compound assignment operator (+=). The signature of the added methods must match that of the delegate that the event is based upon.
Adding the CarSpeedLimitExceeded Method

In the car example, we will add a new method that captures the event that occurs when a car exceeds the safety speed. This method, named CarSpeedLimitExceeded, is added to the Program class of the console application. It will extract the speed from the source object and output a warning message. The two parameters of the method match the event delegate and will receive the Car object raising the event and the associated event arguments. Add the following method to the Program class:

static void CarSpeedLimitExceeded(object source, EventArgs e)
    Car car = (Car)source;
    Console.WriteLine("Speed limit exceeded ({0}mph)", car.Speed);

Subscribing to the SpeedLimitExceeded Event

Now that the event has been created and a method exists that will react to the event, we will create a Car object and subscribe to its event. Add the following code to the Main method of the program:

Car car = new Car();
car.SpeedLimitExceeded += new SpeedLimitExceededEventHandler(CarSpeedLimitExceeded);

The first line of code above creates a new Car object. The second line using the compound assignment notation to link the CarSpeedExceeded method to the SpeedLimitExceeded event of the object. Now when the event is fired, the linked method will be executed.

To test the event, modify the Main method as follows and execute the program:

static void Main(string[] args)
    Car car = new Car();
    car.SpeedLimitExceeded +=
        new SpeedLimitExceededEventHandler(CarSpeedLimitExceeded);

    for (int i = 0; i < 3; i++)
        Console.WriteLine("Speed: {0}mph", car.Speed);


Speed: 30mph
Speed: 60mph
Speed limit exceeded (90mph)
Speed: 90mph


Removing Event Subscriptions

As with delegates it is important to release event references when they are no longer required. To end a subscription use the subtraction compound operator (-=). For example, to unsubscribe and release the CarSpeedLimitExceeded reference, you can use the following code:
car.SpeedLimitExceeded -= new SpeedLimitExceededEventHandler(CarSpeedLimitExceeded);
Event Arguments

Earlier in this article I mentioned the use of event arguments. These contain additional information that is passed when an event is raised. So far, we have been using a basic EventArgs object to represent these event arguments. The EventArgs class contains no properties that make it useful in itself. To provide the additional information we need to create a new class derived from EventArgs with the additional properties that we wish to pass.
Creating a Custom EventArgs Class

New classes for passing event arguments should inherit from EventArgs. Inheritance is beyond the scope of this article and will be explained later in the tutorial. However, to show the use of event arguments we will create such a class for the speeding car example.

To begin, create a new class file containing a class named SpeedEventArgs. To indicate that the class is derived from EventArgs, the base class name is added after the new class' name with the two separated by a colon (:). The new class requires a single property that holds the excess speed for cars travelling faster than their safe speed. The final code for the class is therefore:

class SpeedEventArgs : EventArgs
    private int _excessSpeed;

    public int ExcessSpeed
            return _excessSpeed;
            _excessSpeed = value;

To use the event arguments with our existing event, several modifications need to be made. Firstly, the delegate for the event must be updated to replace EventArgs with SpeedEventArgs as follows:
delegate void SpeedLimitExceededEventHandler(object source, SpeedEventArgs e);

The OnSpeedLimitExceeded method's signature needs to be updated to use the new type:
public virtual void OnSpeedLimitExceeded(SpeedEventArgs e)

Next the call to the OnSpeedLimitExceeded needs to be modified. The Accelerate method will now calculate the difference between the car's current speed and the safety speed. This will be assigned to the event argument property so that it can be passed to subscribing methods. The updated Accelerate method is as follows:

public void Accelerate(int mph)
    int oldSpeed = _speed;
    _speed += mph;

    if (oldSpeed <= _safetySpeed && _speed > _safetySpeed)
        SpeedEventArgs e = new SpeedEventArgs();
        e.ExcessSpeed = _speed - _safetySpeed;

Finally, the subscribing method's signature within the Program class must be updated to accept the new event arguments and react accordingly:

static void CarSpeedLimitExceeded(object source, SpeedEventArgs e)
    Car car = (Car)source;
    Console.WriteLine("Speed limit exceeded by {0}mph", e.ExcessSpeed);

These changes mean that the excess speed is now reported by the event itself. As there is no requirement for the program to know what the car's safety limit is, this provides a good example of encapsulation. Execute the program to see the new results.

Source :- http://www.blackwasp.co.uk