Wednesday, September 8, 2010

DELEGATES AND EVENTS

Delegates
Delegates are a construct for abstracting and creating objects that reference methods and can be used to call those methods. Delegates form the basis of event handling in C#. A delegate declaration specifies a particular method signature. References to one or more methods can be added to a delegate instance. The delegate instance can then be "called" which effectively calls all the methods that have been added to the delegate instance. A simple example:


delegate void Procedure();

class DelegateDemo
{
static void Method1()
{
Console.WriteLine("Method 1");
}
static void Method2()
{
Console.WriteLine("Method 2");
}
void Method3()
{
Console.WriteLine("Method 3");
}

static void Main()
{
Procedure someProcs = null;
someProcs += new Procedure(DelegateDemo.Method1);
someProcs += new Procedure(DelegateDemo.Method2);
DelegateDemo demo = new DelegateDemo();
someProcs += new Procedure(demo.Method3);
someProcs();
}
}

In this example, the delegate is declared by the line delegate void Procedure();
This statement is a complete abstraction. It does not result in executable code that does any work. It merely declares a delegate type called Procedure which takes no arguments and returns nothing. Next, in the Main() method, the statement Procedure someProcs = null; instantiates a delegate. Something concrete has now been created.
The assignment of someProcs to null means that it is not initially referencing any methods. The statements someProcs += new Procedure(DelegateDemo.Method1); and someProcs += new Procedure(DelegateDemo.Method2);
add two static methods to the delegate instance. (Note: the class name could have been left off of DelegateDemo.Method1 and DelegateDemo.Method2 because the statement is occurring in the DelegateDemo class.)
The statement someProcs += new Procedure(demo.Method3); adds a non-static method to the delegate instance.

For a non-static method, the method name is preceded by an object reference. When the delegate instance is called, Method3() is called on the object that was supplied when the method was added to the delegate instance. Finally, the statement someProcs(); calls the delegate instance. All the methods that were added to the delegate instance are now called in the order that they were added.

Methods that have been added to a delegate instance can be removed with the -= operator:
someProcess -= new Procedure(DelegateDemo.Method1);
In C# 2.0, adding or removing a method reference to a delegate instance can be shortened as follows:
someProcess += DelegateDemo.Method1;
someProcess -= DelegateDemo.Method1;
Invoking a delegate instance that presently contains no method references results in a NullReferenceException.
Note that if a delegate declaration specifies a return type and multiple methods are added to a delegate instance, then an invocation of the delegate instance returns the return value of the last method referenced. The return values of the other methods cannot be retrieved (unless explicitly stored somewhere in addition to being returned).

Events
An event is a special kind of delegate that facilitates event-driven programming. Events are class members which cannot be called outside of the class regardless of its access specifier. So, for example, an event declared to be public would allow other classes the use of += and -= on the event, but firing the event (i.e. invoking the delegate) is only allowed in the class containing the event. A simple example:


delegate void ButtonClickedHandler();
class Button
{
public event ButtonClickedHandler ButtonClicked;
public void SimulateClick()
{
if (ButtonClicked != null)
{
ButtonClicked();
}
}
...
}


A method in another class can then subscribe to the event by adding one of its methods to the event delegate:
Button b = new Button();
b.ButtonClicked += MyHandler;
Even though the event is declared public, it cannot be directly fired anywhere except in the class containing the event.
Events are used extensively in GUI programming and in the System.Windows.Forms namespace.

Difference Between ToString() vs Convert.ToString() vs (string) cast

There is a simple but important difference between these three…

ToString() raise exception when the object is null

So in the case of object.ToString(), if object is null, it raise NullReferenceException.

Convert.ToString() return string.Empty in case of null object

(string) cast assign the object in case of null

So in case of MyObject o = (string)NullObject;

The StringBuilder and String classes provide ways to perform string manipulation. If your program requires many manipulations, then the StringBuilder class will likely be more efficient than using the String class. The String class provides an immutable object, which means that once the value of the string instance is set, it cannot be changed. Even though it appears that the application is changing the value of the string instance, it is actually returning a new instance of the String class in memory. For this reason, the StringBuilder class will likely cause less overhead in your application. This set of samples shows some basic manipulation using both the StringBuilder and String classes.


Contents:
The following examples will show how to use the StringBuilder class to append, insert, and replace text within a StringBuilder instance. It will also show how to use the String class to copy, split, and find a substring within a given String instance.
The self-extracting archive contains all source code for this set of samples. The file contains the following directories:

• Code: Contains subfolders for all the samples (see descriptions below):
• BuilderAppend
• BuilderInsert
• BuilderReplace
• StringCopy
• StringSplit
• StringSubstring
• Doc: Contains all documentation, including descriptions of samples, installation instructions, and information on how to use the sample application.
• Misc: Contains any additional files required to run the sample application.


How to Use

Run the self-extracting archive to install the sample files. All of the examples here are separate console applications that can be opened in Visual Studio.NET and run accordingly.

Description


StringBuilder.Append
The Append method takes the specified argument and appends it to the end of the existing value held in a StringBuilder object. This example is a console application that asks the user to input his/her name. The application takes the name entered by the user and appends it to the greeting that is held in the StringBuilder object Greeting. The Append method of the StringBuilder class has 19 overloads. This example uses the Append method of the String object to append Name to the Greeting. The StringBuilder Greeting is initialized with no value, and the value Good Morning is appended to the string representation. Next, the name the user enters is appended to this greeting with the code:

Greeting.Append(", "+Name+"!");

StringBuilder.Insert
The Insert method takes a specified argument and inserts the value at the specified location within the existing value of the StringBuilder object. This example is a console application similar to the Append example. The application takes the name entered by the user and inserts it at the specified location. The Insert method has 18 overloads. This example uses the Insert method of the String object to insert the name you enter after the words "Good Morning" and before the "!" with the following code:

Greeting.Insert(12, ", "+Name);

The first argument is an integer value representing the location within the string to insert the value. The second argument is the value to insert into the existing string. If the integer value supplied is greater than the length of the string value contained within the StringBuilder object (for example, if the value 35 is entered here), an exception of type System.ArgumentOutOfRangeException will occur.

StringBuilder.Replace
The Replace method searches the existing string value and replaces all instances of the value with another specified value. This example builds on the Insert example by asking the user to also enter a nickname into the application. If the user has entered a name and a nickname, then the application will replace the original name with the nickname in the StringBuilder Greeting object with the following code:

Greeting.Replace(Name, Nickname);

String.Copy
The Copy method of the String class creates a new instance of a string with the same value as the string being copied. In this example the user enters some text, and that value is placed into a string object named inputText. The application copies this value into the new object named copiedText and appends some additional text in the following code:

string inputText = Console.ReadLine();
string copiedText = string.Copy(myText);
copiedText+=" more text";

Notice that the Copy method is a static method of the String class and therefore is called using the class name and not the instance name.

String.Split and String.Join
The Split method identifies a substring within the specified string delimited by one or more characters. The substring values are placed into a string array. In this example, the string instance textOriginal contains the value "Value 1, Value 2, Value 3". The application calls the Split method and initializes the textarray string array with the following code:

string[] textArray = text.Split(',');

The example then loops through all of the values in the array and writes them to the screen.
The Join method of the String class concatenates a specified character string within values of a string array and produces a single string. In this example, the textarray string array is re-joined using a ":" with the following code:

string newJoin = string.join(":", textArray);

Notice that the Join method is a static method of the String class and therefore is called using the class name and not the instance name.

String.Substring
The Substring method returns a string representation from a specified start point. This method has two overloads where one method also accepts a length argument. In this example, a string is extracted from the original string instance beginning at the 4th character and having a length of 3.

string Contained = originalString.Substring(4, 3).ToString();



C# Code: SQL & MS-Access DB Connection Class

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

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

OleDbConnection con1,con2;

private void btn_SQL_Click(object sender, EventArgs e)
{
MessageBox.Show(CLSConnection.SQLGetConnection().ToString());
try
{
con1 = new OleDbConnection(CLSConnection.SQLGetConnection());
//No need of adding CLSConnection's class namespace, B/c that class is with inthis namespace only..
con1.Open();
MessageBox.Show("SQL Connection State ::"+ con1.State.ToString());

if (con1.State == ConnectionState.Open)
{
lb_SQL.Text = "SQL Connection Opened..";
lb_SQL.ForeColor = Color.Green;
}
else
{
lb_SQL.Text = "SQL Connection Failed..";
lb_SQL.ForeColor = Color.Red;
}
}
catch (Exception ex)
{
lb_SQL.Text = "SQL Connection Failed..";
lb_SQL.ForeColor = Color.Red;
MessageBox.Show(ex.Message);
}
}

private void btn_MSA_Click(object sender, EventArgs e)
{

MessageBox.Show(CLSConnection.MSAGetConnection().ToString());
try
{
con2 = new OleDbConnection(CLSConnection.MSAGetConnection());
//No need of adding CLSConnection's class namespace, B/c that class is with inthis namespace only..
con2.Open();
MessageBox.Show("MS-Access Connection State ::"+con2.State.ToString());

if (con2.State == ConnectionState.Open)
{
lb_MSA.Text = "MS-Access Connection Opened..";
lb_MSA.ForeColor = Color.Green;
}
else
{
lb_MSA.Text = "MS-Access Connection Failed..";
lb_MSA.ForeColor = Color.Red;
}
}
catch (Exception ex)
{
lb_MSA.Text = "MS-Access Connection Failed..";
lb_MSA.ForeColor = Color.Red;
MessageBox.Show(ex.Message);
}
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Configuration;

namespace Connection_Config_Class1
{
class CLSConnection
{
//
public static string sqlconstr; // Static Data field
public static string SQLGetConnection()// Static Method
{
sqlconstr =
ConfigurationSettings.AppSettings["SQLConSetting1"].ToString();
return sqlconstr;
}

public static string msaconstr; // Static Data field
public static string MSAGetConnection()// Static Method
{
msaconstr =
ConfigurationSettings.AppSettings["AccessConSetting1"].ToString();
return msaconstr;
}
}
}

"
[?xml version="1.0" encoding="utf-8" ?>
[configuration>

[add key="SQLConSetting" value="Provider=sqloledb; Data Source=.;Initial
Catalog=master;Integrated Security=True"/>
[add key="SQLConSetting1" value="Provider=sqloledb; Data Source=.;Initial
Catalog=master;User ID=sa;Password=123"/>

[add key="AccessConSetting" value="Provider=Microsoft.JET.OLEDB4.0;data source
=.;Integrated security=true; database=master"/>
[add key="AccessConSetting1" value="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=\EmployeeDB.mdb"/>
[!-- -->
[/appSettings>
[/configuration>
"

C# Code: Arthimatic Calculation by Taking 3 Operands Using Properties Concept -III


/// D.A.Applic_ of Arthimatic Calculation by Taking 3 Operands Using Properties Concept.
/// Conditions:
/// 1. Operand1 should be in range -100 to 100.
/// 2. Operand2 should be lessthan Operand1 & should not be Zero.
/// 3. Operand1 & Operand2 are Wrie-Only Property whereas Operand3 is Read-Only Property
/// 4. Computation of Methods(Add,Sub,Mul,Div) should be in seperate Class file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Property_Calulator1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

Math obj = new Math();

private void btn_SetValues_Click_1(object sender, EventArgs e)
{
obj.Operand1 = int.Parse(txt_oper1.Text);
obj.Operand2 = int.Parse(txt_oper2.Text);

foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
ctrl.Enabled = true;
}
}

private void btn_GetValue_Click_1(object sender, EventArgs e)
{
txt_result.Text = obj.Result.ToString();
}

private void btn_Plus_Click_1(object sender, EventArgs e)
{
obj.Add();
}

private void btn_Subtact_Click_1(object sender, EventArgs e)
{
obj.Sub();
}

private void btn_Multiply_Click_1(object sender, EventArgs e)
{
obj.Mul();
}

private void btn_Division_Click_1(object sender, EventArgs e)
{
obj.Div();
}

int oper1, oper2;
private void txt_oper1_Validating(object sender, CancelEventArgs e)
{
//Validating for "Oper1"Textbox must be acceptable b/w the Range -100 to 100
if(txt_oper1.Text.Trim().Length!=0)
oper1 = Convert.ToInt32(txt_oper1.Text);

if (oper1 > -100 && oper1 < 100)
return;
else
{
MessageBox.Show("Operand1 value should be in -100 to 100 Range");
e.Cancel = true;
}
}

private void txt_oper2_Validating(object sender, CancelEventArgs e)
{
//Validating for "Oper2" value should be less than "Oper1" & Should not be zero
if (txt_oper2.Text.Trim().Length != 0)
oper2 = Convert.ToInt32(txt_oper2.Text);
if (oper2 < oper1 && oper2 != 0)
{
btn_SetValues.Enabled = true;
return;
}
else
{
MessageBox.Show("Operand2 value should be Lessthan Operand1 &
Operand2 should not be Zero");
e.Cancel = true;
}
}

private void Form2_Load(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
//MessageBox.Show(ctrl.GetType().ToString());
if(!(ctrl is TextBox) && !(ctrl is Label))
ctrl.Enabled = false;

txt_result.Enabled = false;
}
}

private void txt_oper1_KeyPress(object sender, KeyPressEventArgs e)
{
//MessageBox.Show(Convert.ToInt32(e.KeyChar).ToString());
if (char.IsDigit(e.KeyChar)==false && Convert.ToInt32(e.KeyChar)!= 8
&& Convert.ToInt32(e.KeyChar) != 45)
{
MessageBox.Show("Enter Numeric Values Only..");
e.Handled = true;
}
}
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Property_Calulator1
{
class Math
{
/// Property Fields
private int _operand1;
private int _operand2;
private double _result;

/// Properties
public int Operand1
{
set { _operand1 = value; }
}

public int Operand2
{
set { _operand2 = value; }
}

public double Result
{
get { return _result; }
}

public double GetValue()
{
return Result; //return _result;
}

public void Add()
{
_result = _operand1 + _operand2;//Result = Operand1 + Operand2;
}

public void Sub()
{
_result = _operand1 - _operand2;
}

public void Mul()
{
_result = _operand1 * _operand2;
}

public void Div()
{
_result = _operand1 / _operand2;
}
}
}¬¬¬

C# Code:Arthimatic Calculation by Taking 3 Operands Using Properties Concept -II


/// D.A.Applic_ of Arthimatic Calculation by Taking 3 Operands Using Properties Concept.
Conditions: 1. Operand1 & Operand2 are Wrie-Only Property whereas Operand3 is Read-Only Property
2. Computation of Methods(Add,Sub,Mul,Div) should be in seperate Class file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Property_Calulator1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

Math obj = new Math();

private void btn_SetValues_Click(object sender, EventArgs e)
{
obj.Operand1 = int.Parse(txt_oper1.Text);
obj.Operand2 = int.Parse(txt_oper2.Text);
btn_GetValue.Enabled = false;
}

private void btn_GetValue_Click(object sender, EventArgs e)
{
txt_result.Text = obj.Result.ToString();
}

private void btn_Plus_Click(object sender, EventArgs e)
{
obj.Add();
btn_GetValue.Enabled = true;
}

private void btn_Subtact_Click(object sender, EventArgs e)
{
obj.Sub();
btn_GetValue.Enabled = true;
}

private void btn_Multiply_Click(object sender, EventArgs e)
{
obj.Mul();
btn_GetValue.Enabled = true;
}

private void btn_Division_Click(object sender, EventArgs e)
{
int b = int.Parse(txt_oper2.Text );
if (b != 0)
{
obj.Div();
btn_GetValue.Enabled = true;
}
else
MessageBox.Show("Operand2 must not be zero");
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Property_Calulator1
{
class Math
{
/// Property Fields
private int _operand1;
private int _operand2;
private double _result;

/// Properties
public int Operand1
{
set { _operand1 = value; }
}

public int Operand2
{
set { _operand2 = value; }
}

public double Result
{
get { return _result; }
}

public double GetValue()
{
return Result; //return _result;
}

public void Add()
{
_result = _operand1 + _operand2;//Result = Operand1 + Operand2;
}

public void Sub()
{
_result = _operand1 - _operand2;
}

public void Mul()
{
_result = _operand1 * _operand2;
}

public void Div()
{
_result = _operand1 / _operand2;
}
}
}

C# Code for Arthimatic Calculation by Taking 3 Operands Using Properties Concept -I


/// D.A.Applic_ of Arthimatic Calculation by Taking 3 Operands Using Properties Concept.
Conditions:
Operand1 & Operand2 are Wrie-Only Property whereas Operand3 is Read-Only Property
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

//Property Fields
private int _operand1;
private int _operand2;
private int _result;

//Properties
public int Operand1
{
set { _operand1 = value; }
}
public int Operand2
{
set { _operand2 = value; }
}
public int Result
{
set { _result = value; }
get { return _result; }
}

private void btn_SetValues_Click(object sender, EventArgs e)
{
Operand1 = int.Parse(txt_oper1.Text);
//_operand1 = int.Parse(txt_oper1.Text);
Operand2 = int.Parse(txt_oper2.Text);
//_operand2 = int.Parse(txt_oper2.Text);
}

private void btn_GetValue_Click(object sender, EventArgs e)
{
txt_result.Text = Result.ToString();
//txt_result.Text = obj.Result.ToString();
}

private void btn_Plus_Click(object sender, EventArgs e)
{
Result = _operand1 + _operand2;//Result = Operand1 + Operand2;
btn_GetValue.Enabled = true;
}

private void btn_Subtact_Click(object sender, EventArgs e)
{
Result = _operand1 - _operand2;//Result = Operand1 - Operand2;
btn_GetValue.Enabled = true;
}

private void btn_Multiply_Click(object sender, EventArgs e)
{
Result = _operand1 * _operand2;//Result = Operand1 * Operand2;
btn_GetValue.Enabled = true;
}

private void btn_Division_Click(object sender, EventArgs e)
{
int b = int.Parse(txt_oper2.Text);
if (b != 0)
{
Result = _operand1 / _operand2;//Result = Operand1 / Operand2;
btn_GetValue.Enabled = true;
}
else
MessageBox.Show("Operand2 must not be zero");
}
}
}

Followers