Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Send E-Mail From Client Machine To Another

******************** REMOVE ALL [] WITH <> REPECTIVELY************************




[%@ Page Language="C#" AutoEventWireup="true" CodeFile="Emailfunction-client-server.aspx.cs" Inherits="mailclient" ValidateRequest="false" %]


[!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"]

[html xmlns="http://www.w3.org/1999/xhtml"]
[head runat="server"]
[title]Send E-Mail[/title]

[script type="text/javascript"]

function emailto(ob)
{
var mail;
mail= document.getElementById("FreeTextBox1").value;
ob.href ='mailto:viplav15@yahoo.co.in? » &subject=Test? » &body=[html]'+mail+'[/html]? »';
}
[/script]

[/head]
[body]
[form id="form1" runat="server"]
[div]
[a onclick="emailto(this);" href="">Send Mail AnandInternationals[/a][/p]
[p]
[a href="" subject="Test?" body="[html"]Viplav Anand [p] [b]Pathak[/b] csesupport [/p][/html]? »"]Send Mail[/a]
[/p]
[asp:textbox id="FreeTextBox1" runat="server"]
[/ASp:TextBox]
[asp:button id="Button1" runat="server" text="Send Mail- Server" onclick="Button1_Click"]
[p][a onclick="emailto(this);" href=""]Send Mail AnandInternationals[/a]
[/p]

[/div]
[/form]
[/body]
[/html]


The software just created would be capable to send HTML enabled or Formatted Texts as Email using mailto option :

Code your e-mail functionality provider interface with this script and watch out for the results.

Create Thumbnail From Memorystream Object In .NET

When we want to read and create thumbnail from a database image field, read it and store it into a memory stream object and look into the following code. I am discussing only the key area of this functionality.


Stream strm = ShowAlbumImage(picid);


System.Drawing.Image thumbnail = new System.Drawing.Bitmap(strm);


System.Drawing.Image img = thumbnail.GetThumbnailImage(100, 100, null, IntPtr.Zero);


MemoryStream ms = new MemoryStream();


img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);


The ShowAlbumImage() is a function to return image field of the database as stream.
Then converting the stream obj into image, creating thumbnail using GetThumbnailimage function. Again it is saving to memory stream and can display using context.response.binarywrite()...

Do include required namespaces...

And the Orkut stuff is achieved of transforming an image into a thumbnail...

Export Gridview Data To PDF Format

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

Protected void btnGView to pdfclick(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}


Now we need to be made sure regarding the iTextSharp Library which does not support background color of table cells or table rows.
Hence while rendering it to the pdf format we need to modify the iTextSharp so that it exports the HTML with background color.

We have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used.

Export GridView To Word

To retrieve the records from a table fom within a database is perfectly easy via the gridview server control which can be bound via some queries specific to the requirements.

However what ought to be done when we have to export the data into a Word/Excel/PDF/CSV format ?

Does it seem tough. May be but here in we go with the simple though tricky codes :

protected void btnExportWord_Click(object sender, EventArgs e)

{

Response.Clear();

Response.Buffer = true;

Response.AddHeader("content-disposition",

"attachment;filename=GridViewExport.doc");

Response.Charset = "";

Response.ContentType = "application/vnd.ms-word ";

StringWriter sw= new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.AllowPaging = false;

GridView1.DataBind();

GridView1.RenderControl(hw);

Response.Output.Write(sw.ToString());

Response.Flush();

Response.End();

}

Disable Browser Back Buttton Functionality

Normally we have the tendency to move back and forth within the web-browser.
However in the mission critical environment we just seem to be fooled.Once I was
juts browsing through my CITIBANK account and tried to just push through the back button of the browser. the hell it was to do so AS I was immediately logged out.


So you need to know the simple though highly useful trick to just make your web-projects capable of delivering such efficiency in the mission critical environments.

Herein I chip with the simple javascript code that shall add up this functionality.
So that when you are on a web page and via server.transfer or response.redirect you get redirected to suppose webpage2.aspx from the webpage1.aspx, you can't access the former page that is (webpage1) by using the back button of your web browser - as you are on webpage1.aspx currently.

The head section of the web page must be accompanied with this code-sniffet.
REPLACE /* WITH ANGULAR BRACKETS...

/* script type = "text/javascript" */

function preventBack()
{
window.history.forward();
}

setTimeout("preventBack()", 0);

window.onunload=function(){null};

/* /script */

Dynamic DropDownList Controls

How to create dynamic DropDownList control in Asp.net?
How to retain value across postbacks ?
How to recreate the controls on each postback ?
How to dynamically attach event handlers to DropDownList control in asp.net ?



Dynamic DropDownList control in asp.net

Coding Language : C# :

Add a PreInit event to the Page and add the following snippet in it
.

Panel pnlDropDownList;

protected void Page_PreInit(object sender, EventArgs e)

{

//Create a Dynamic Panel

pnlDropDownList = new Panel();

pnlDropDownList.ID = "pnlDropDownList";

pnlDropDownList.BorderWidth = 1;

pnlDropDownList.Width = 300;

this.form1.Controls.Add(pnlDropDownList);

//Create a LinkDynamic Button to Add TextBoxes

LinkButton btnAddDdl = new LinkButton();

btnAddDdl.ID = "btnAddDdl";

btnAddDdl.Text = "Add DropDownList";

btnAddDdl.Click += new System.EventHandler(btnAdd_Click);

this.form1.Controls.Add(btnAddDdl);

//Recreate Controls

RecreateControls("ddlDynamic", "DropDownList");

}
So I have created the following controls :

* Dynamic panel pnlDropDownList and added it to the form control on the page

* Dynamic LinkButton btnAddDdl attached a Click event btnAdd_Click to it and added to the form control.

* A function called RecreateControls is being called.

On the Click event of the dynamic LinkButton I have added the following event:

protected void btnAdd_Click(object sender, EventArgs e)

{

int cnt = FindOccurence("ddlDynamic");

CreateDropDownList("ddlDynamic-" + Convert.ToString(cnt + 1));

}



As you will notice 2 function calls are made : The FindOccurence function as the name suggests gets the occurrence of the Dynamic DropDownList in the Request.Form collection. The basic idea is that I have given ID is a common pattern that is all IDs are of the form txtDynamic e.g. txtDynamic-1, txtDynamic-2 and so on.

private int FindOccurence(string substr)

{

string reqstr = Request.Form.ToString();

return ((reqstr.Length - reqstr.Replace(substr, "").Length)

/ substr.Length);

}

CreateDropDownList is used to create dynamic DropDownList. The function accepts ID as parameter .

private void CreateDropDownList(string ID)

{

DropDownList ddl = new DropDownList();

ddl.ID = ID;

ddl.Items.Add(new ListItem("--Select--", ""));

ddl.Items.Add(new ListItem("One", "1"));

ddl.Items.Add(new ListItem("Two", "2"));

ddl.Items.Add(new ListItem("Three", "3"));

ddl.AutoPostBack = true;

ddl.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);

pnlDropDownList.Controls.Add(ddl);

Literal lt = new Literal();

lt.Text = "
"
;

pnlDropDownList.Controls.Add(lt);

}

What I do here is that I am creating a new DropDownList and adding Items to it. Once done that I am attaching SelectedIndexChanged Event Handler and setting the AutoPostBack property to true. Finally I am adding it to the panel pnlDropDownList.

The SelectedIndexChanged Event Handler is given below.

protected void OnSelectedIndexChanged(object sender, EventArgs e)

{

DropDownList ddl = (DropDownList)sender;

string ID = ddl.ID;

ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert",

"");

//Place the functionality here

}


The most important function is RecreateControls whose job is to recreate all the DropDownList on each postback.


private void RecreateControls(string ctrlPrefix, string ctrlType)

{

string[] ctrls = Request.Form.ToString().Split('&');

int cnt = FindOccurence(ctrlPrefix);

if (cnt > 0)

{

for (int k = 1; k <= cnt; k++)

{

for (int i = 0; i <>

{

if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString())

&& !ctrls[i].Contains("EVENTTARGET"))

{

string ctrlID = ctrls[i].Split('=')[0];

if (ctrlType == "DropDownList")

{

CreateDropDownList(ctrlID);

}

break;

}

}

}

}

}


So first find the occurrence of a particular string here ddlDynamic in the Request.Form collection and then loop through each item and keep adding the DropDownList using the CreateDropDownList function described earlier.

One important thing I need to point out which people overlook is always give unique IDs to dynamic controls when you create them.







Javascript Pop Up Yes/No Confirmation

replace all /* */ by < >




"How to get the confirmation of Yes/No from a javascript pop up and display the value on the page using ASP.NET" ?


Create a webpage main.aspx Drag and drop a hidden control and
/*button*/ control on the web form.




Step 1.

/* Button1.Attributes.Add("onclick", "getMessage()")*/



Step 2. main.aspx Add the client side-script block


/*script language="javascript" */


function getMessage()
{
var ans;
ans=window.confirm('Is it your confirmation.....?');
alert (ans);
if (ans==true)
{ alert('Yes');
document.Form1.hdnbox.value='Yes';
}
else { alert('No');
document.Form1.hdnbox.value='No';} }


/*script*/


Step 3. main.aspx.vb To display the value of the value selected by the user in the pop up write the following code :


/*Response.Write(Request.Form("hdnbox"))*/




/*/button */ ---- Closing button tag!!!


/*input id="gwProxy" type="hidden" /*input onclick="jsCall();" id="jsProxy" type="hidden" */
/*div id="refHTML" */


/*/div*/




Populate List Data

METHOD 1: Without any datasource control
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim ds As New AccessDataSource
ds = AccessDataSource1
Response.Write(ds.ConnectionString)
Dim mycon As New OleDbConnection
Dim conStr As String = ds.ConnectionString
mycon.ConnectionString = conStr
mycon.Open()
Response.Write("

" & mycon.State & "

")
Dim myCmd As New OleDbCommand
myCmd.Connection = mycon
myCmd.CommandType = Data.CommandType.Text
myCmd.CommandText = ds.SelectCommand.ToString
Try
Dim dr As OleDbDataReader = myCmd.ExecuteReader
Response.Write(dr.HasRows)
'Dim str As String = ""
While dr.Read
ListBox1.Items.Add(dr.Item("CustomerID") & _
"," & dr.Item("CompanyName") & "," & _
dr.Item("LastName") & "," & _
dr.Item("City") & "," _
& dr.Item("HomePhone"))
'Response.Write(str)
End While
dr.Close()
Catch ex As System.Data.OleDb.OleDbException
Response.Write(ex.Message)
End Try
mycon.Close()
End Sub
End Class

METHOD 2: Without any datasource control

Imports System.Data.OleDb
Partial Class CodeBound
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim ds As New AccessDataSource
ds = AccessDataSource1
Dim sqlstr As String = "Select * from Customers"
ds.SelectCommand = sqlstr
ListBox1.DataSource = ds
ListBox1.DataValueField = "CustomerID"
ListBox1.DataTextField = "CompanyName"
ListBox1.DataBind()
End Sub
End Class



List Box Control Database Access

FOR SECURE DB TRANSACTION REFER TO THE MAY 2009,CODES SECTION:
Use the namespace of the ADO.NET SQL Server Data Provider :


using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page{
private string connectionString = "Data Source=(local);Initial
Catalog=Northwind;Integrated Security=True";
private string[] employeeFields = new string[3];
private char[] splitChar = new char[1] { ',' };

protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
PopulateList(false);
}
}

protected void ListBox1_SelectedIndexChanged(object sender,
EventArgs e){
employeeFields = ListBox1.SelectedItem.Value.Split
(splitChar);
EmployeeIDTextBox.Text = employeeFields[0];
LastNameTextBox.Text = employeeFields[1];
FirstNameTextBox.Text = employeeFields[2];
}

protected void GetEmployeesRecords(){
try{
using (SqlConnection connection = new SqlConnection
(connectionString)){
string commandText = "SELECT EmployeeID, LastName,
FirstName FROM Employees";
SqlCommand command = new SqlCommand(commandText,
connection);

connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader
()){
while (dataReader.Read()){
ListBox1.Items.Add(dataReader["EmployeeID"] + "," +
dataReader["LastName"] + "," + dataReader["FirstName"]);
}
}
}
}
catch (Exception ex){
MessageLabel.Text = ex.Message;
}
}

private void PopulateList(bool operation){
GetEmployeesRecords();
if (operation)
ListBox1.Items[ListBox1.Items.Count - 1].Selected = true;
else
ListBox1.Items[0].Selected = true;

ListBox1_SelectedIndexChanged(this, EventArgs.Empty);

}


protected void NewEmployeeButton_Click(object sender, EventArgs e){
if (LastNameTextBox.Text != String.Empty &
FirstNameTextBox.Text != String.Empty){
InsertNewEmployee();
DeleteEmployeeButton.Enabled = true;
}
}
protected void DeleteEmployeeButton_Click(object sender,
EventArgs e){
DeleteEmployee();
}


private void InsertNewEmployee(){
try{
using (SqlConnection connection = new SqlConnection
(connectionString)){
string commandText = "INSERT INTO Employees(LastName,
FirstName) VALUES" + "(@LastName, @FirstName)";
SqlCommand command = new SqlCommand(commandText,
connection);

SqlParameter firstParameter = new SqlParameter();
firstParameter.ParameterName = "@LastName";
firstParameter.Value = LastNameTextBox.Text;
command.Parameters.Add(firstParameter);

SqlParameter secondParameter = new SqlParameter();
secondParameter.ParameterName = "@FirstName";
secondParameter.Value = FirstNameTextBox.Text;
command.Parameters.Add(secondParameter);

//command.Parameters.AddWithValue("@LastName",
LastNameTextBox.Text);
//command.Parameters.AddWithValue("@FirstName",
FirstNameTextBox.Text);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1){
ListBox1.Enabled = true;
ListBox1.Items.Clear();
PopulateList(true);
}
NewEmployeeButton.Enabled = false;
NewButton.Enabled = true;
}
}
catch (Exception ex){
MessageLabel.Text = ex.Message;
}
}


private void DeleteEmployee(){
try{
using (SqlConnection connection = new SqlConnection
(connectionString)){
string commandText = "DELETE FROM Employees WHERE
EmployeeID = @EmployeeID";
SqlCommand command = new SqlCommand(commandText,
connection);

SqlParameter parameter = new SqlParameter("@EmployeeID",
EmployeeIDTextBox.Text);
command.Parameters.Add(parameter);

connection.Open();
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1){
ListBox1.Items.Clear();
PopulateList(true);
}
}
}
catch (Exception ex){
MessageLabel.Text = ex.Message;
}
}

protected void NewButton_Click(object sender, EventArgs e){
ListBox1.Enabled = false;
ListBox1.SelectedIndex = -1;
EmployeeIDTextBox.Text = "You can't enter a value here";
LastNameTextBox.Text = String.Empty;
FirstNameTextBox.Text = String.Empty;
NewButton.Enabled = false;
NewEmployeeButton.Enabled = true;
DeleteEmployeeButton.Enabled = false;
}
}

When you run the page, after replacing the auto-generated code with the above code, you will get a populated list of employees and, as in the previous article, when you select another employee the text boxes are updated to reflect that new selection as shown in the next screen shot.




When you click the New Employee button on the ListBox control, the New Employee button itself and the DELETE Employee button will all be disabled, and the Insert Employee button will be enabled with empty text boxes so you can enter the first name and the last name of the employee as shown in the next screen shot.



Enter the first name and the last name for the new employee.
Note that you don't have any choice that allows you to cancel the operation, except closing the browser or navigating to another website. If you want this behavior you can provide a cancel button, and in its click event handler enable the controls and set the ListBox-selected index to the first item or the last item or something similar. When you click on the Insert Employee button, the new employee record will be entered in the database's Employees table and the ListBox's SelectedIndex has been set to that new employee item.
Your result maybe different from mine if you have made changes to the Northwind database. I myself make a lot of changes to this database, especially if I'm writing an article, so don't worry about it as long as it's working as it should be. You can download the T-SQL script that creates this database from Microsoft's web site, if you haven't done that already. Now you can delete that new record by clicking the DELETE Employee button.
Note how the ListBox control selects the last item only when you INSERT or DELETE a record, but when the page is first loaded it's set to the first item on the list.




Software Serial Keys

Open Source World- An Overview

Open source software community has in itself been a remarkable industry well capable of producing some of the best tools in the Software testing as well as software development world. Let us have a quick look into some of the quality births that Software industry has witnessed from the OPen source community.


Amarok is a powerful music player for Linux and Unix, MacOS X and Windows with an intuitive interface. It makes playing the music you love and discovering new music easier than ever before - and it looks good doing it!

Some of the goals of the project are to make Amarok more customizable through widgets, and improving the playlist editor. Project ideas are welcome.
Drupal

Drupal is a free software package that allows an individual or a community of users to easily publish, manage and organize a wide variety of content on a website.

There are several ideas for projects including improving the general UI of the Drupal management interface, assisting in building a platform for usability communication in the Drupal community.
Gallery

Gallery is an open source project with the goal to develop and support leading photo sharing web application solutions. It gives you an intuitive way to blend photo management seamlessly into your own website whether you’re running a small personal site or a large community site.

This project is interested in learning more about their users. Project activities would include user research activities such as surveys, interviews, creating user groups and personas, and competitive analysis.


GeneMANIA is a tool for generating hypotheses about gene function. GeneMANIA helps you predict the function of your favorite genes and gene sets. The simple, intuitive web interface is backed by powerful analysis software and a large data warehouse containing extensive amounts of existing functional genomics data, and also includes a Cytoscape-based advanced visualization tool to enable browsing of query results and creation of publication-ready figures.

This project is interested in improving the UI design of it’s desktop tool, which contains additional functionality that is not included in the webbased tool.
GNOME User Management Tool

Ubuntu is a community developed operating system that is perfect for laptops, desktops and servers. Whether you use it at home, at school or at work Ubuntu contains all the applications you’ll ever need, from word processing and email applications, to web server software and programming tools.

This project is interested in redesigning in evaluating and redesigning the existing user management tool in the GNOME desktop environment.


Kadu is an open source gadu-gadu protocol instant messenger client for Linux, BSD and Mac.

They are interested in making Kadu a multi-protocol instant messenger. This would involve refining existing user research documentation such as personas and scenarios based on a previous survey, and redesigning the configuration UI to support managing multiple protocols.
KOrganizer

KOrganizer provides management of events and tasks, alarm notification, web export, network transparent handling of data, group scheduling, import and export of calendar files and more.

This project is interested in improving the editing tools for adding appointments, TODO entries, and journal items.


OLM is a web-based marking system that includes an early submission and testing system in support of test driven development.

This project is interested in fixing known issues and integrating new functionality into the user interface.
SemNotes

SemNotes is a semantic note taking tool for KDE4, built on top of Nepomuk-KDE. SemNotes links notes to the data that is available on the user’s desktop. The data stored about a note consists of: a title, content, tags, creation and last modification time.

This project is interested in improving their user interface and running a usability evaluation with the new changes on a range of users.
Ubuntu Add/Remove… Software

Ubuntu is a community developed operating system that is perfect for laptops, desktops and servers. Whether you use it at home, at school or at work Ubuntu contains all the applications you’ll ever need, from word processing and email applications, to web server software and programming tools.

This project is interested in evaluating the Add/Remove… software tool with several small usability evaluations which will provide design recommendations for UI changes.

Peridically Refreshing Webpage

The following META tag can be used as a trigger to automatically refresh the page every n seconds:

meta http-equiv="Refresh" content="nn"


This element can be used only within the HEAD element.

Peridical refreshing

The following META tag can be used as a trigger to automatically refresh the page every n seconds:

meta http-equiv="Refresh" content="nn"


This element can be used only within the HEAD element.

Int32.Parse(), Convert.ToInt32(), and Int32.TryParse() A Comparison

Int32.parse(string)
-------------------------

Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent.
When s is null reference, it will throw ArgumentNullException.
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.


Example:
------------------

string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";

int result;
bool success;

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException


Convert.ToInt32(string)
----------------------------------

Convert.ToInt32(string s) method converts the specified the string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
When s is null reference, it will return 0 rather than throw ArgumentNullException
If s is other than integer value, it will throw FormatException.
When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException

Example:
result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException



Int32.TryParse(string, out int)
---------------------------------------------

Int32.Parse(string, out int) method converts the specified the string representation of 32-bit signed integer equivalent to out variable, and returns true if it parsed successfully, false otherwise. This method is available in C# 2.0
When s is null reference, it will return 0 rather than throw ArgumentNullException.
If s is other than integer value, the out variable will have 0 rather than FormatException.
When s represents a number less than MinValue or greater than MaxValue, the out variable will have 0 rather than OverflowException.

Example:-
-------------
success = Int32.TryParse(s1, out result); //-- success => true; result => 1234
success = Int32.TryParse(s2, out result); //-- success => false; result => 0
success = Int32.TryParse(s3, out result); //-- success => false; result => 0
success = Int32.TryParse(s4, out result); //-- success => false; result => 0


Convert.ToInt32 is better than Int32.Parse, since it return 0 rather than exception. But, again according to the requirement this can be used. TryParse will be best since it handles exception itself always.

Open Web Page in a new window

The following HTML code will enable you to open a web page in a new window:


A HREF="http://www.yourdomain.com" TARGET="_blank"


If you're linking to a lot of other web sites within your web page and would like to open all of your links in a new window, this HTML code is for you.

The following HTML code will enable you to open all of your links in a new window. Place this code between your HEAD tag within your HTML:

base target="main"

Multicast Delegate

A delegate (object) which simultaneously executes more than one method dynamically can be called as a multicast delegate.

In all of my previous examples, I attached a delegate to one and only one method every time. Now, we are going to assign more than one method to the same delegate. In other words, the moment "invoke()" gets executed, all the methods (addresses of methods) attached to the delegate get executed.

Let us see an example of this:



'multi-cast delegate


Public Class Form7




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)


Dim deleg As Calculate




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


deleg = AddressOf obj.Add


deleg = System.Delegate.Combine(deleg, New Calculate(AddressOf obj.Multiply))


'deleg.Invoke()


deleg()


End Sub


End Class



From the above, the most important lines are the following:



deleg = AddressOf obj.Add


deleg = System.Delegate.Combine(deleg, New Calculate(AddressOf obj.Multiply))



The first line says that the "Add" method must be assigned to the "deleg" object. The second line says that another method, "Multiply," must be assigned to the "deleg" object, to keep existing.

Finally, all the methods in the delegate get executed using the following line:

deleg()

Delegates To Methods Returning Values


In
all of the previous examples, I concentrated only on methods which do not return any values. Now, let us concentrate on delegates which can be used to call methods returning values (say, functions in a class).

Let us add one more class as follows:



Public Class Sample03


Private _x As Integer


Private _y As Integer




Public Sub New()




End Sub




Public Sub New(ByVal a As Integer, ByVal b As Integer)


_x = a


_y = b


End Sub




Public Property X() As Integer


Get


Return _x


End Get


Set(ByVal value As Integer)


_x = value


End Set


End Property




Public Property Y() As Integer


Get


Return _y


End Get


Set(ByVal value As Integer)


_y = value


End Set


End Property




Public Function GetSum() As Integer


Return (Me.X + Me.Y)


End Function




Public Function GetProduct() As Integer


Return (Me.X * Me.Y)


End Function




End Class



The above class contains two methods, "GetSum()" and "GetProduct()," which return values of type integer. To access those methods using delegates, you can code as follows:


'delegates to functions


Public Class Form5


Delegate Function Calculate() As Integer




Dim delegCalc As Calculate


Dim obj As New Sample03(10, 20)




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


delegCalc = AddressOf obj.GetSum


MessageBox.Show("Sum = " & delegCalc())


'MessageBox.Show("Sum = " & delegCalc.Invoke())


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


delegCalc = AddressOf obj.GetProduct


MessageBox.Show("Product = " & delegCalc())


'MessageBox.Show("Product = " & delegCalc.Invoke())


End Sub




End Class


"Callback"
is one of the most important features of delegates. Let us start with an example. To make things easier to understand, I added a new class as follows:



Public Class Sample04




Delegate Sub FactorFound(ByVal FactorValue As Integer)




Private _x As Integer




Public Sub New()




End Sub




Public Sub New(ByVal a As Integer)


_x = a


End Sub




Public Property X() As Integer


Get


Return _x


End Get


Set(ByVal value As Integer)


_x = value


End Set


End Property




Public Sub FindFactors(ByVal delgFoundFactor As FactorFound)


For i As Integer = 1 To _x


If _x Mod i = 0 Then


delgFoundFactor(i)


End If


Next


End Sub




End Class



The most important method from the above class is the following:



Public Sub FindFactors(ByVal delgFoundFactor As FactorFound)


For i As Integer = 1 To _x


If _x Mod i = 0 Then


delgFoundFactor(i)


End If


Next


End Sub



The method accepts a parameter of type "delegate" which is declared at module level as follows:


Delegate Sub FactorFound(ByVal FactorValue As Integer)


That means the calling program can execute the "FindFactors" method by passing the address of another method. The address, which is passed to "FindFactors," can be invoked within the same "FindFactors" method.

In simple words, the calling program executes "FindFactors" by giving permission to the "FindFactors" method to execute (internally inside "FindFactors") another method (address) passed to it.

The following sample can be considered a caller for this demonstration:



'implementing callback methods using delegates


Public Class Form6




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Me.ListBox1.Items.Clear()


Dim obj As New Sample04(Me.TextBox1.Text)


obj.FindFactors(AddressOf FactorAvailable)


End Sub




Private Sub FactorAvailable(ByVal FactorValue As Integer)


Me.ListBox1.Items.Add(FactorValue)


End Sub


End Class



From the above, you can observe that "FactorAvailable" is passed to the "FindFactors" method. The "FactorAvailable" method gets executed with the following statement in the "FindFactors" method:



delgFoundFactor(i)

Delegates With Parameters

In my previous example, you were introduced to simple delegates. Now, I shall extend the same with parameters.

To help us understand "delegates with parameters," I added a new class as follows:



Public Class Sample02


Private _x As Integer


Private _y As Integer




Public Sub New()




End Sub




Public Sub New(ByVal a As Integer, ByVal b As Integer)


_x = a


_y = b


End Sub




Public Property X() As Integer


Get


Return _x


End Get


Set(ByVal value As Integer)


_x = value


End Set


End Property




Public Property Y() As Integer


Get


Return _y


End Get


Set(ByVal value As Integer)


_y = value


End Set


End Property




Public Sub Increment(ByVal IncrementValue As Integer)


_x += IncrementValue


_y += IncrementValue


End Sub




Public Sub Add()


MessageBox.Show("Sum = " & (Me.X + Me.Y))


End Sub




Public Sub Multiply()


MessageBox.Show("Product = " & (Me.X * Me.Y))


End Sub


End Class



You can observe that a new method, "Increment" (which accepts a parameter), is added. Let us try to access it using delegate. The following is the code:



'delegate with parameters


Public Class Form4




Delegate Sub Calculate()


Delegate Sub IncreaseValues(ByVal value As Integer)




Dim delegCalc As Calculate


Dim delegIncrease As IncreaseValues




Dim obj As New Sample02(10, 20)




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


delegCalc = AddressOf obj.Add


delegIncrease = AddressOf obj.Increment


delegIncrease(100)


delegCalc()


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


delegCalc = AddressOf obj.Multiply


delegIncrease = AddressOf obj.Increment


delegIncrease(100)


delegCalc()


End Sub




End Class



Let us try to understand this step by step. Consider the following first:



Delegate Sub IncreaseValues(ByVal value As Integer)



"IncreaseValues" is a delegate type of class now. However, it only accepts methods (which can be executed later) with just one parameter of type integer.



Dim obj As New Sample02(10, 20)


delegIncrease = AddressOf obj.Increment



As the "Increment" method accepts a parameter of type integer, it can be assigned to the delegate object we declared earlier.

Finally, the method gets executed with a value of 100 using the statement:



delegIncrease(100)



A delegate declaration can have multiple parameters, not only one. And further, those parameters could be of any type, from primitive data types to reference types!


Delegates Basics

A delegate allows us to encapsulate a reference to a method inside an object -- a delegate object, to be precise. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Before trying to understand the above, let us work with a simple example. The following is a sample class:


Public Class Sample01

Private _x As Integer

Private _y As Integer


Public Sub New()


End Sub


Public Sub New(ByVal a As Integer, ByVal b As Integer)

_x = a

_y = b

End Sub


Public Property X() As Integer

Get

Return _x

End Get

Set(ByVal value As Integer)

_x = value

End Set

End Property


Public Property Y() As Integer

Get

Return _y

End Get

Set(ByVal value As Integer)

_y = value

End Set

End Property


Public Sub Add()

MessageBox.Show("Sum = " & (Me.X + Me.Y))

End Sub


Public Sub Multiply()

MessageBox.Show("Product = " & (Me.X * Me.Y))

End Sub

End Class



The above class has two private fields ("_x" and "_y") which are only accessible within the class, and not outside the class. Further, it has two public properties and two public methods, "Add" and "Multiply." Note that public members are accessible even outside the class.

To test the above class, add a new form with two buttons and a label. Modify your code to match the following:


'without using delegates

Public Class Form1


Dim obj As New Sample01(10, 20)


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

obj.Add()

End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

obj.Multiply()

End Sub


End Class


There is nothing new in the above form. We are simply instantiating an object based on the "Sample01" class and calling its methods. We will do the same in the next section, but with "Delegates."

In the previous section, a class named "Sample01" was introduced. The following is a simple "delegate" way of coding:


'sample of using delegate


Public Class Form2




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Dim delg As New Calculate(AddressOf obj.Add)


delg.Invoke()


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


Dim delg As New Calculate(AddressOf obj.Multiply)


delg.Invoke()


End Sub


End Class



Let us try to understand it step by step. First of all we have the following:


Delegate Sub Calculate()


The line says that "Calculate" is a delegate. Even though its signature looks like a method, it is actually a class. Consider "Calculate" to be a named class of yours having its own functionality to invoke "methods of other objects dynamically."

Further proceeding we have the following:


Dim obj As New Sample01(10, 20)


It is simply an instantiation. Further on we have the following:


Dim delg As New Calculate(AddressOf obj.Add)


As previously described, "Calculate" is a class. And now, "delg" is an instance of the class "Calculate," which is "authorized" to access and execute the method named "obj.Add()".

The "obj.Add()" method gets executed when the following statement is invoked:


delg.Invoke()


Finally, a delegate is simply an object which can execute methods of other objects dynamically at run time.

To make all of this simpler, the above can also be written as follows:



'Without creating instances of a delegate and without using invoke


Public Class Form3




Delegate Sub Calculate()


Dim obj As New Sample01(10, 20)


Dim deleg As Calculate




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


deleg = AddressOf obj.Add


deleg()


End Sub




Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


deleg = AddressOf obj.Multiply


deleg()


End Sub


End Class