Overview of Microsoft .NET Framework
Overview of Microsoft .NET Framework
Net Programming
Unit -I
Visual Studio .NET
History of Microsoft .NET
In June 2000, Microsoft is an innovative computing platform planned to
simplify application development and deployment in the Internet age.
The Microsoft .NET Framework is an environment for building,
deploying, and running robust, scalable distributed applications.
In March 2002 Microsoft released final version of the .NET framework.
The Microsoft .NET platform provides all the tools, core services and
technologies to build distributed web, windows, and mobile and speech
applications.
Visual Studio .NET
Visual Studio .NET is an Integrated Development Environment(IDE)
for building, testing and debugging a variety of applications such as, Windows
applications, Web applications, classes and custom controls, even console
applications.
It provides numerous tools for automating the development process,
visual tools to perform many common design and programming tasks, and
more features.
Visual Studio is an environment for developing all types of
applications, from a simple Windows application to a complete Web
application involving databases and XML files.
Microsoft .NET Framework
Introduction
•
Components of .NET Framework
•
Common Language Runtime (CLR)
NET Framework Base Classes
User and Program Interfaces
• Architecture of the .NET Framework
• Advantages of .NET Framework
Introduction
Microsoft introduced the .NET framework to make applications more
interoperable.
Interoperability of applications means the ability of applications
developed in different languages to be able to work together and exchange
information with each other.
1
I MSc CS .Net Programming
The objective of the .NET Framework is to bring various programming
languages and services together.
It is designed to make significant improvements in,
Code reusability
Code specialization
Resource management
The .NET Framework consists of all the technologies that help in creating
and running applications that are,
Robust: Applications those are strong
Scalable: Applications that can be extended
Distributed: Applications that runs on computers of different networks.
The .NET offers a complete suite for developing and deploying
applications. This suite consists of,
.NET Products
.NET Services
.NET Framework
.NET Products
Microsoft has introduced Visual Studio .NET, which is a tool for
developing .NET applications by using programming languages, such as Visual
Basic, Visual C# and Visual C++.
.NET Services
.NET helps to create software as Web Services.
A Web Service is an application that is accessible through standard
internet protocol such as Hypertext Transfer Protocol (HTTP) and
Simple Object Access Protocol (SOAP).
.NET Framework
It is the foundation on which we design, develop and deploy
applications.
It is reliable and simplified programming model that helps to build
robust applications.
Components of .NET Framework
The .NET Framework consists of the following components,
Common Language Runtime(CLR)
.NET Framework Base Classes
User and Program Interfaces
2
I MSc CS .Net Programming
Components of .NET Framework
3
I MSc CS .Net Programming
4
I MSc CS .Net Programming
JIT compilation
IL is converted into machine language by the JIT compiler.
Garbage Collection
The garbage collection process begins after the JIT compilation and
manages the allocation and deallocation of memory for an application.
During the creation of object, the CLR allocates memory for the object
from managed heap.
A managed heap is a region of the memory that is available for
program execution. If sufficient memory is not available on the managed heap,
the garbage collection process is invoked.
The code developed in .NET is called managed code. The CLR manages
the compilation and execution of the managed code to ensure proper
functioning of the code.
Code execution
5
I MSc CS .Net Programming
6
I MSc CS .Net Programming
Architecture of the .NET Framework
8
I MSc CS .Net Programming
9
I MSc CS .Net Programming
Creating Applications and Solutions
10
I MSc CS .Net Programming
Solution Explorer window:-
The Solution Explorer window lists the solution name, the project name
and all classes that are used in the project.
We can open a file existing in a project by double clicking the file in the
Solution Explorer window.
Output window:-
The output window displays messages for the status of various features
provided in the visual studio .NET IDE.
During compilation, this window displays the current status. After the
compilation process is complete, it gives the number of errors that occurred
during compilation.
Open this window by selecting View Output window or by pressing
Ctrl+W+O keys.
Contents
• Creation of applications
• IDE Components
• IDE Menu
• Compiling and Executing applications
Creation of application
Step1: Start Page
Select Start All Programs Microsoft Visual Studio 2008. The
Start Page - Microsoft Visual Studio window will be
displayed.
13
I MSc CS .Net Programming
Step2: Starting a New Project
Select File New Project. The New Project dialog box will be
displayed.
14
I MSc CS .Net Programming
IDE Components
• Toolbox
• Solution Explorer
• Output Window
• Properties Windows
• Task List Window
• Code / Design view
Toolbox
The Toolbox is a palette of developer objects, or controls, that are
placed on forms or web pages, and then code is added to allow the user to
interact with them.
An example would be TextBox, Button and ListBox controls.
15
I MSc CS .Net Programming
Output window
The output window displays messages for the status of various features
provided in the visual studio .NET IDE.
During compilation, this window displays the current status. After the
compilation process is complete, it gives the number of errors that occurred
during compilation.
Open this window by selecting View Output window or by pressing
Ctrl+W+O keys.
IDE Menu
File Menu
The File menu contains commands for opening and saving projects, or
project items, as well as the commands for adding new or existing items to the
current project.
Edit Menu
The Edit menu contains the usual editing commands.
View Menu
This menu contains commands to display any toolbar or window of the
IDE.
Project Menu
This menu contains commands for adding items to the current project.
Build Menu
The Build menu contains commands for building (compiling) a project.
The two basic commands in this menu are the Build and Rebuild All
commands.
17
I MSc CS .Net Programming
Debug Menu
This menu contains commands to start or end an application, as well as
the basic debugging tools.
Data Menu
This menu contains commands which use with projects that access
data.
Format Menu
The Format menu, which is visible only while you design a Windows or
Web form, contains commands for aligning the controls on the form.
Tools Menu
This menu contains a list of tools. The Macros command of the Tools
menu leads to a submenu with commands for creating macros.
Window Menu
This is the typical Window menu of any Windows application. In
addition to the list of open windows, it also contains the Hide command,
which hides all Toolboxes and devotes the entire window of the IDE to the code
editor or the Form Designer.
Help Menu
This menu contains the various help options.
Compiling and Executing application
Steps to compile and execute the application
1. Select Build Build Solution to compile the application.
2. Select Debug Start Debugging or press F5 to execute the application.
Variables
In Visual Basic, variables are the placeholders used to store values
during a program’s execution.
A variable has a name and a value.
Example:-
The variable UserName, for example, can have the value “Jaya,” and the
variable Discount can have the value 0.35.
UserName and Discount are variable names, and “Jaya” and 0.35 are
their values.
Whenever a variable is declared VB allocates space in the computer
memory.
18
I MSc CS .Net Programming
Rules for Naming a Variable:-
• The first letter must be an alphabet.
• Underscore is allowed but special characters are not allowed.
• Whitespaces are not allowed.
• The max length can be upto 255 characters.
• Keywords are not allowed to use as variables.
• Variable names in [Link] are case-insensitive.
• Must be unique within its scope.
Declaring Variables:-
In most programming languages, variables must be declared in advance.
[Link] encourages the declaration of variables. When declare a variable,
also need to specify its type.
To declare a variable, use the Dim statement followed by the variable’s
name, the As keyword, and its type.
Syntax:-
Dim variable-name As Data type
Dim var-name1, var-name2, and var-name3 As Data type
Dim var-name1 As type-1, var-name2 As type-2, var-name3 As type-3
Examples:
Dim meters As Integer
Dim greetings As String
Multiple variables of the same or different type in the same line can also
declare as follows:
Dim Qty As Integer, Amount As Decimal, CardNum As String
[Link] documentation is strictly typed, which means that a variable
has a specific type and can’t store a value of a different type to the variable.
Variable Initialization
[Link] can also allow initializing variables in the same line that
declares them. The following line declares an Integer variable and initializes it
to 3,045:
Dim distance As Integer = 3045
This statement is equivalent to the following statements:
Dim distance As Integer
distance = 3045
19
I MSc CS .Net Programming
It is also possible to declare and initialize multiple variables, of the same
or different type, on the same line:
Dim quantity As Integer = 1, discount As Single = 0.25
Working with variables:-
Scope of variable:-
A variable also has a scope.
The scope (or visibility) of a variable is the section of the application that
can see and manipulate the variable.
The scope of variable is determined by the way it has been declared. It is
the range from which the variable can be referenced a procedure, a form and
etc.
Types of scope:-
Local Variable (or) Procedure level scope
Block Variable (or) Block-level scope
Form Variable (or) module-level scope
Public variables (or) global scope
Static variable
Local Variable (or) Procedure level scope
If a variable is declared within a procedure, only the code in the specific
procedure has access to that variable. This variable doesn’t exist for the rest of
the application.
When the variable’s scope is limited to a procedure, it’s called local.
Example:-
Private Sub Button1_Click
Dim i, Sum As Integer // Local variable
End Sub
A Variable Scoped in Its Own Procedure
Private Sub Button1_Click(ByVal sender As Object, _
ByVal e As [Link]) Handles [Link]
Dim i As Integer
Dim Sum As Integer
For i = 0 to 100 Step 2
Sum = Sum + i
Next
MsgBox “The sum is “ & Sum
End Sub
20
I MSc CS .Net Programming
Block variable or block-level scope
Variables introduced in a block of code, such as an If statement or a
loop, are local to the block but invisible outside the block.
Example:-
For i = 0 to 100 Step 2
Dim sqrValue As Integer // Block variable
next
A Variable Scoped in Its Own Block
Private Sub Button1_Click(ByVal sender As Object, _
ByVal e As [Link]) Handles [Link]
Dim i, Sum As Integer
For i = 0 to 100 Step 2
Dim sqrValue As Integer
sqrValue = i * i
Sum = Sum + sqrValue
Next
MsgBox “The sum of the squares is “ & Sum
End Sub
The sqrValue variable is not visible outside the block of the For…Next
loop.
Form variable (or) module-level scope
Variables declared outside any procedure in a module are visible from
within all procedures in the same module, but they’re invisible outside the
module.
Form level variables are declared in the general section of form using
Private keyword.
Example:-
Public class Form1
Private a, b As Integer
Private sum As Double
End Class
Public variables (or) global scope
Public variables are visible from any part of the application.
Use the Public statement to declare a public variable.
21
I MSc CS .Net Programming
Example:-
Function RunningAvg(ByVal newValue As Double) As Double
CurrentTotal = CurrentTotal + newValue
TotalItems = TotalItems + 1
RunningAvg = CurrentTotal / TotalItems
End Function
Declare the variables CurrentTotal and TotalItems outside the function
so that their values are preserved between calls.
Static variable
• Variables declared using static keyword exist as long as the
application is running.
• The static variables are available in the entire application.
• The static variables can be declared using ‘static’ keyword.
Example:-
Function RunningAvg(ByVal newValue As Double) As Double
Static CurrentTotal As Double
Static TotalItems As Integer
CurrentTotal = CurrentTotal + newValue
TotalItems = TotalItems + 1
RunningAvg = CurrentTotal / TotalItems
End Function
The advantage of using static variables is to minimize the number of
total variables in the application.
Types of Variables (data types)
Visual Basic recognizes the following five categories of variables:
• Numeric
• String
• Character
• Boolean
• Date
• Object
Numeric variables
Numeric variables store number.
A variety of numeric data types,
• Integers (there are several integer data types)
• Decimals
• Single, or floating-point numbers with limited precision
• Double, or floating-point numbers with extreme precision
22
I MSc CS .Net Programming
Decimal, single, and double are the three basic data types for storing
floating-point numbers.
The integer data types store whole numbers.
Visual Basic Numeric Data Types
Data Type Memory Stores
Representation
Short (Int16) 2 bytes Integer values in the range
-2,768 to 32,767.
Integer (Int32) 4 bytes Integer values in the range
-2,147,483,648to 2,147,483,647.
23
I MSc CS .Net Programming
The second assignment creates an empty string, and the last one
creates a string to contain numeric digits, which are also characters.
The difference between these two variables
Dim a As Integer = 25000
Dim b As String = “25,000”
The variable b holds the characters “2”, “5”, “,”, “0”, “0”, and“0”, and a
holds a single numeric value. The variable a is used in numeric calculations
and the variable b in string operations.
Character Variable
Character variables store a single Unicode character in two bytes.
In effect, characters are unsigned short integers. We can use the
CChar() function to convert integers to characters, and the CInt() function to
convert characters to their equivalent integer values.
Use the Char keyword to declare a character variable,
Dim char1, char2 As Char
We can initialize a character variable by assigning either a character or
a string to it. In the latter case, only the first character of the string is
assigned to the variable.
The following statements will print the characters “a” and “A” to the
Output window:
Dim char1 As Char = “a”, char2 As Char = “ABC”
[Link](char1)
[Link](char2)
The integer values corresponding to the English characters are the ANSI
codes of the equivalent characters. The statement:
[Link](CInt(“a”)) will print the value 65.
Boolean Variables
The Boolean data type stores True/False values.
Boolean variables are integers that take the value either 1 (for True) or 0
(for False).
Actually, any non-zero value is considered true.
Boolean variables are declared as:
Dim failure As Boolean and they are initialized to False.
Boolean variables are used in testing conditions, such as the following:
If failure Then MsgBox(“Couldn’t complete the operation”)
24
I MSc CS .Net Programming
They are also combined with the logical operators AND, OR, NOT, and
XOR.
The NOT operator toggles the value of a Boolean variable.
The following statement is a toggle:
running = Not running
Example:-
Dim running As Boolean
If running = True Then
running = False
Else
running = True
End If
Date Variables
Date and time values are stored internally in a special format, but don’t
need to know the exact format.
They are double-precision numbers:
Integer part represents the date.
Fractional part represents the time.
A variable declared as Date can store both date and time values with a
statement like the following:
Dim ddate As Date
The following are all valid assignments:
ddate = #01/01/2004#
ddate = #8/27/2001 6:29:11 PM#
ddate = “July 2, 2002”
ddate = Now()
The Now() function returns the current date and time.
Object variables
Object variables can store any type of data.
Variants are variables without a fixed data type
Variants are the opposite of strictly typed variables: they can store all
types of values, from a single character to an object.
Variants were the most flexible data type because they could
accommodate all other types.
A variable declared as Object declare the variable with the Object data
type:
Dim myVar As Object
25
I MSc CS .Net Programming
26
I MSc CS .Net Programming
27
I MSc CS .Net Programming
Constants are preferred for two reasons:-
Constants don’t change value: Once a constant has been declared,
can’t change its value in subsequent statements, so can be sure that the
value specified in the constant’s declaration will take effect in the entire
program.
Constants are processed faster than variables. When the program is
running, the compiler substitute’s constant names with their values, and the
program executes faster.
Rules for naming a constant:-
• The first letter must be an alphabet.
• Underscore is allowed but special characters are not allowed.
• Whitespaces and keywords are not allowed.
• The max length can be upto 255 characters.
Arrays
Contents
• Definition
• Declaring Arrays
• Initializing Arrays
• Array Limits
• Dynamic Arrays
• Multidimensional Arrays
Definition
A standard structure for storing data in any programming language is
the array.
Array is a set of indexed data of same data type. Each element in the
array has a unique number is called subscript number or Index.
An array has a name, and the values stored in it can be accessed and
identified by an index.
Types of Arrays
*One dimensional Array or List
* Multidimensional Array
Declaring arrays
Arrays must be declared with the Dim (or Public, or Private) statement
followed by the name of the array and the index of the last element in the
array in parentheses.
28
I MSc CS .Net Programming
Syntax:-
Dim arrayname [(subscript)] [As Datatype]
Example,
Dim Salary (15) As Integer
Salary is the name of an array that holds 16 values (salaries of the 16
employees), with indices ranging from 0 to 15.
Salary(0) is the first person’s salary, Salary(1) the second person’s
salary, and so on.
Initializing array
We can initialize variables in the same line where we declare them.
Dim arrayname() As type = {entry0, entry1, … entryN}
Example that initializes an array of strings:
Dim name() As String = {“John”, “Peter ”}
This statement is equivalent to the following statements,
Dim name(1) As String
name(0) = “John”
name(1) = “Peter”
Array limits
The first element of an array has index 0. The number that appears in
parentheses in the Dim statement is one less than the array’s total capacity
and is the array’s upper limit (or upper bound).
The index of the last element of an array (its upper bound) is given by
the function UBound(), which accepts as argument the array’s name.
Dim myArray(19) As Integer
Its upper bound is 19, and its capacity is 20 elements.
Fixed array
In fixed array, the memory allocation is done at the declaration and
stays the same for the whole time the program runs.
The advantage of fixed array is no risk of “Running out of memory”.
Example
Dim a(10)
Dim a(20) As Integer
29
I MSc CS .Net Programming
Dynamic array
Dynamic array is used to change the size of the array in runtime.
The size of a dynamic array can vary during the course of the Program.
Declare the array as usual with the Dim statement (or Public or Private)
but without specifying its dimensions to create a dynamic array
Dim DynArray() As Integer
Later in the program, use the ReDim statement to redimension (resize)
the array,
Syntax: ReDim DynArray(UserCount)
The ReDim statement can appear only in a procedure. Unlike the Dim
statement, ReDim is executable—it forces the application to carry out an
action at runtime. Dim statements aren’t executable, and they can appear
outside procedures.
Example1
Dim A As Integer
ReDim A (10)
Example2
Private a() As Integer
Private sub command1_click()
Dim n As Integer
n = Inputbox(“Numbers”)
ReDim a(n) As Integer
A dynamic array also can be resized to multiple dimensions. Declare it
with the Dim statement outside any procedure as follows:
Dim Matrix() As Double
And then use the ReDim statement in a procedure to declare a three-
dimensional array:
ReDim Matrix(9, 9, 9)
Advantage
Dynamic array is the flexible to resize the array.
Preserve Keyword
Whenever the ReDim statement is executed, all the values currently
stored in the array are lost.
Visual Basic resets the values of the elements as if they were just
declared. (It resets numeric elements to zero and String elements to empty
strings.)
30
I MSc CS .Net Programming
The Preserve keyword is used to preserve (reset the data) the data in an
existing array.
Syntax:-
ReDim [Preserve] varname(index) [As data type]
Example: ReDim Preserve a(10) As Integer
Local Array
The array which is declared inside a procedure is local to that array.
A local fixed array can be declared using Dim statement as follows,
Example,
Private sub command1_click
Dim a(10) As Integer
End sub
A local dynamic array can be declared using Dim statement as follows,
Example,
Private sub command1_click
Dim a() As Integer
n = (Int(Inputbox(“Elements”))
ReDim a(n) As Interger
End sub
Static array
The static array can declared using keyword ‘Static’.
The contents of the static array remain the same in all procedure or
functions.
Static arrays are fixed arrays.
Example
Private Function fartocel () As single
Static n(10) As Integer
End sub
Multidimensional array
An array with more than one subscript number or index is called
multidimensional array.
A two-dimensional array has two indices. The first identifies the row
and the second identifies the column.
Example
Dim A(3,3) As Integer
31
I MSc CS .Net Programming
Benefit of multidimensional array is easier to manage.
VB allows up to 60 dimensions with Dim statement and 8 dimensions
with ReDim statement.
Declaration of Multidimensional array:-
The Dim statement declares and allocates storage space for
multidimensional array.
Syntax:-
Dim varname(subscript or range) [As Datatype]
Examples
Dim a(2,2) As Integer
Dim a(1 to 2, 1 to 2) As Integer
If the array has more than one dimension, [Link] property can
used to find out the number of dimensions.
Example:-
Dim Salary (1, 99) As Object
To find out the number of dimensions, use the statement:
[Link]
When using the Length property to find out the number of elements in a
multidimensional array,
To find out the number of elements in a specific dimension use the
GetLength method, passing as argument a specific dimension.
The following expression will return the number of elements in the first
dimension of the array:
[Link]([Link](0))
Flow-Control Statements
Contents
Test Structures or conditional branching
• If…Then
• If…Then…Else
• If …Then…ElseIf
• Nested If
• Select Case
Loop Structures
• For…Next
• Do…Loop
• While…EndWhile
Jump Statements
• Goto
• Exit
32
I MSc CS .Net Programming
Test Structures
An application needs a built-in capability to test conditions and take a
different course of action depending on the outcome of the test. Visual Basic
provides five such decision structures:
• If…Then
• If…Then…Else
• If …Then…ElseIf
• Nested If
• Select Case
If…Then
If…Then statement tests the specified condition; if it’s True, the
program executes the statement(s) that follow.
If structure can have a single-line or a multiple-line syntax.
Single Line Syntax
Use the single-line syntax to execute one statement conditionally,
as follows:
If condition Then statement
Example
If Month(expDate) > 12 Then expYear = expYear + 1: expMonth = 1
Multiple Line Syntax
Execute multiple statements by separating them with colons:
Syntax:-
If condition Then statement: statement: statement
we can break this statement into multiple lines by using End If,
Example
If [Link] > 12 Then
expYear = expYear + 1
expMonth
End If
If…Then…Else
This statement provides two blocks such as, true block and false
block.
If…Then…Else statement, which executes one block of statements if the
condition is True and another block of statements if the condition is False.
33
I MSc CS .Net Programming
Syntax
If condition Then
statementblock1
Else
statementblock2
End If
Visual Basic evaluates the condition; if it’s True, VB executes the first
block of statements and then jumps to the statement following the End If
statement. If the condition is False, Visual Basic ignores the first block of
statements and executes the block following the Else keyword.
Example
If n>0 Then
Result = “positive”
Else
Result = “Negative”
End If
If…Then…ElseIf
This statement allows checking more than two conditions. This is also
known as Elseif Ladder.
Syntax:- If condition1 Then
statementblock1
ElseIf condition2 Then
statementblock2
ElseIf condition3 Then
statementblock3
Else
statementblock4
End If
Example:-
Private sub command1_click()
Dim a, b, c
a = val (text1)
b = val (text2)
c = val (text3)
If a > b AND a > C Then
34
I MSc CS .Net Programming
text4 = “A is Greater” &a
ElseIf b > c AND b > a Then
text4 = “B is Greater” &b
Else
text4 = “C is Greater” &c
End If
End sub
Nested If
A If lock is placed inside of another if block is known as nested if.
Syntax:-
If condition1 Then
If condition2 Then
Statements
Else
Statements
End if
Else
Statements
End if
Example:-
Private sub Command1_click()
Dim m1, m2, m3
Dim tot, avg
tot = val(txtm1) + val(txtm2) + val(txtm3)
avg = tot/5
txttot = tot
txtavg = avg
if txtm1>39 AND txtm2>39 AND txtm3>39 Then
txtres = “Pass”
If avg > 75 Then
txtclass = “Distintction”
elseif avg>60 Then
txtclass = “First class”
elseif avg>50 Then
txtclass = “Second class”
elseif avg>40 Then
txtclass = “Third class”
Else
txtclass = “Not Eligible”
End if
End if
End sub
35
I MSc CS .Net Programming
Select case
This statement allows checking more than one condition.
Select case is similar to If then Elseif...Ladder.
The advantage of the Select Case statement over multiple
If…Then…Else/ElseIf statements is that it makes the code easier to read and
maintain.
The Select Case structure tests a single expression, which is evaluated
once at the top of the structure. The result of the test is then compared with
several values, and if it matches one of them, the corresponding block of
statements is executed.
Syntax:-
Select Case expression
Case value1
statementblock1
Case value2
statementblock2
.
.
.
Case Else
statementblockN
End Select
Example
Dim message As String
Select Case [Link]
Case [Link]
message = “Have a nice week”
Case [Link]
message = “Have a nice weekend”
Case Else
Message = “Welcome back!”
End Select
MsgBox(message)
If more than one Case value matches the expression, only the statement
block associated with the first matching Case executes.
36
I MSc CS .Net Programming
Loop Structures
Loop structures allow to execute one or more lines of code repetitively.
Many tasks consist of trivial operations that must be repeated again and
again.
Visual Basic supports the following loop structures:
• For…Next
• Do…Loop
• While…End While
Repeating an operation a specified number of times is called loop.
Types of Loops
Determinate loop
Non Determinate loop
For…Next
For…Next loop repeating an operation fixed number of times is called as
determinate loops.
For…Next loop uses a variable (it’s called the loop’s counter) that
increases or decreases in value during each repetition of the loop.
syntax:
For counter = start To end [Step increment]
statements
Next [counter]
The keywords in the square brackets are optional. The arguments
counter, start, end, and increment are all numeric.
Steps in for loop
1. Sets counter equal to start
2. Tests if counter is greater than end. If so, it exits the loop.
3. Executes the statements in the block
4. Increments counter by the amount specified with the increment argument.
If the increment argument isn’t specified, counter is incremented by 1.
5. Repeats the statements
Example:-
For I = 1 to 10
Savings = savings + 1000
Next I
37
I MSc CS .Net Programming
Nested For loop
A for loop can be placed inside of another for loop is called Nested for loop.
Syntax:-
For counter1 = start To end [Step increment]
For counter2 = start To end [Step increment]
statements
Next [counter2]
Next [counter1]
Example : for j = 1 to 12
for i = 2
Print i * j
Next i
Next j
Indeterminate loop
This loop executes a block of code an indeterminate number of times.
Types:
Do While…loop
Do Until…loop
While…EndWhile
Do While…loop
Do While…loop first checks the condition, if it is true then it executes the
code block otherwise come out of loop.
Syntax:-
Do While(condition)
statement block
loop
Example:-
Do while(n=10)
sum = sum +n
n=n+2
loop
Do Until…loop
Do Until…loop first checks the condition, if it is false then it executes the
code block otherwise comes out of loop.
38
I MSc CS .Net Programming
Syntax:-
Do Until(condition)
statement block
loop
Example:-
position = 1
Do Until position = 0
position = InStr(position + 1, MyText, “ “)
words = words + 1
Loop
While…End While
The While…End While loop executes a block of statements as long
as a condition is True.
Syntax:
While condition
Statement-block
End While
If condition is True, all statements are executed and, when the End
While statement is reached, control is returned to the While statement, which
evaluates condition again. If condition is still True, the process is repeated. If
condition is False, the program resumes with the statement following End
While.
Example:-
Dim number, total As Double
number = 0
While number => 0
total = total + number
number = InputBox(“Please enter another value”)
End While
Jump Statements
The jump statements allow transferring the control to elsewhere in
the program unconditionally.
• Goto
• Exit
39
I MSc CS .Net Programming
Goto :-
The goto uses label to jump from one place to another.
Syntax:-
Goto block1
----------
---------
block1
---------
Exit
The Exit statement allows to exit directly from a block of statements
in a control structure, from a loop, or even from a procedure.
Syntax:-
If this code is part of a subroutine procedure, use the Exit Sub statement
and Exit statements for loops are Exit For, Exit While, and Exit Do.
Example
For i = 0 To UBound(n)
If n(i) < 0 Then Exit For
n(i) = [Link](n(i))
Next
40
I MSc CS .Net Programming
UNIT -II
Procedures
The code which is made up of small segments called procedures, and
work on one procedure at a time. Or
A larger program can be breaking into smaller logical components to
make simple and understandable. These components are called procedures.
Two types of procedures: subroutines and functions
Modular Coding
The idea of breaking a large application into smaller, more manageable
sections. Few tasks, programming can be managed as a whole.
The event handlers are just one example of breaking a large application
into smaller tasks.
Example:-
Retrieve(productID)
Sum1 = SumQtyPrice()
Qty1 = SumQuantities()
RetrieveInvoice(productID)
Sum2 = SumQtyPrice()
Net = (Sum2 – Sum1) / Qty1
The task is broken into smaller units, and each unit is implemented by
a function or subroutine.
The name of the procedure indicates the operation it performs.
Retrieve() subroutine retrieves quantities and purchase prices of a
specific product—the productID argument—from a database.
SumQtyPrice() function multiplies the quantities by prices at which they
were sold and sums the results to get the total value paid for the purchase of a
specific product. This result is stored in the Sum1 variable.
SumQuantities() function sums the unit quantities into the Qty1
variable.
RetrieveInvoice() subroutine gets similar data from the invoices in the
database, so that the SumQtyPrice() function can calculate the total income
generated by the same product. The value returned by the SumQtyPrice()
function is stored in the Sum2 variable.
41
I MSc CS .Net Programming
44
I MSc CS .Net Programming
Arguments
An argument is a value which pass to the procedure and functions on
which the procedure usually acts.
Example
The function Min() accepts two numbers and returns the smaller one:
Function Min(ByVal a As Single, ByVal b As Single) As Single
Min = If(a < b, a, b)
End Function
Argument Passing Mechani[Link]
• Passing arguments by value
• Passing arguments by reference
• Passing Objects as Arguments
Passing Arguments by Value:-
We can call a function or procedure by supplying the value of variable.
The actual parameter should be enclosed within the parenthesis to pass
a value.
ByVal keyword in front of the argument’s name is used to specify the
arguments that will be passed by value.
If we omit the ByVal keyword, the editor will insert it automatically,
because it’s the default option.
Syntax:-
Functionname (parameter1, parameter2…)
Procedurename (parameter1, parameter2…)
Benefit of passing arguments by value is,
• The argument values are isolated from the procedure,
• Only the code segment in which they are declared can change their
values.
• If we pass an argument by value then the original variable retains its
value after the procedure or functions completes.
This is the default argument-passing mechanism in [Link].
Example:-
1. a =19
call sum(a) ‘ Call by value’
2. Function Degrees(ByVal Celsius as Single) As Single
Degrees = (9 / 5) * Celsius + 32
End Function
45
I MSc CS .Net Programming
Call the function as follows:
CTemp = InputBox(“Enter temperature in degrees Celsius”)
MsgBox([Link] & “ degrees Celsius are “ & Degrees((CTemp))
& _ “ degrees Fahrenheit”)
If the value entered in the InputBox is 32, the following message is
displayed:
32 degrees Celsius are 89.6 degrees Fahrenheit
Passing arguments by reference:-
To pass reference to the actual parameter, they should be mentioned
without brackets or parenthesis while calling the procedure or function.
Passing arguments by reference gives the procedure access to the actual
variable.
The calling procedure passes the address of the variable in memory so
that the procedure can change its value permanently.
ByRef keyword is used to pass arguments by reference only if the
procedure has reason to change its value.
Example:-
Function Add(ByRef num1 As Integer, ByRef num2 As Integer) As
Integer
Add = num1 + num2
num1 = 0
num2 = 0
End Function
This simple function adds two numbers and then sets them to zero.
Next, place a Command button on the form and enter the following code
in the button’s Click event:
Dim A As Integer, B As Integer
A = 10
B=2
Dim Sum As Integer
Sum = Add(A, B)
[Link](A)
[Link](B)
[Link](Sum)
This code displays the following results in the Output window:
0
0
12
46
I MSc CS .Net Programming
The changes made to the function’s arguments take effect even after the
function has ended.
The values of the variables A and B have changed value permanently.
Change the definition of the function by inserting the keyword ByVal
before the names of the arguments, as follows:
Function Add(ByVal num1 As Integer, ByVal num2 As Integer)
As Integer
With this change, Visual Basic passes copies of the arguments to the
function. The rest of the program remains the same. Run the application, click
the button, and the following values display in the Output window:
10
2
12
Passing Objects as Arguments:-
When we pass objects as arguments, they’re passed by reference, even if
we specified the ByVal keyword.
The procedure can access and modify the members of the object passed
as argument, and the new value will be visible in the procedure that made the
call.
Private Sub Button1_Click(ByVal sender As [Link], _
ByVal e As [Link]) Handles [Link]
Dim aList As New ArrayList()
PopulateList(aList)
[Link](aList(0).ToString)
[Link](aList(1).ToString)
[Link](aList(2).ToString)
End Sub
Sub PopulateList(ByVal list As ArrayList)
[Link](“1”)
[Link](“2”)
[Link](“3”)
End Sub
The object is an ArrayList, which is an enhanced form of an array.
Add method adds new items to the ArrayList, and can access
individual items with an index value, similar to an array’s elements.
47
I MSc CS .Net Programming
The Click event handler of a Button control creates a new instance of
the ArrayList object and calls the PopulateList() subroutine to populate the
list.
Event-Handler Arguments:-
Event handlers are implemented as subroutines.
Event handlers never return a result, so they’re implemented as
subroutines.
Two arguments that are common to all event handlers, which pass
information about the object and the action that invoked the event.
The subroutines that handle events accept two arguments:
sender and e
The declaration of the Click event handler for a button:
Private Sub Button1_Click(ByVal sender As [Link], _
ByVal e As [Link]) Handles [Link]
The sender argument conveys information about the object that initiated
the event; we use this argument in our code to find out the type of the object
that raised the event.
The following two statements in a button’s Click event handler will print
the values shown in bold on the Output window:
[Link]([Link])
[Link], Text: Button1
[Link]([Link])
[Link]
The e argument is an object that exposes some properties, which vary
depending on the type of the event and the control that raised the event.
Structures
SYNOPSIS
• Introduction
• Structures Vs. Classes
• Declaration
• Object Creation
• Structures & Fields
• Structure & Methods
• Structures & Constructors
48
I MSc CS .Net Programming
Introduction
• Structures are complex data types that encapsulate small pieces of
tightly related data items.
• Structures can contain data members as well as member methods to
work with data inside a structure.
• A structure in [Link] is simply a composite data type consisting of
number elements of other types.
• A [Link] structure is a value type and the instances or objects of a
structure are created in stack.
• The structure in [Link] can contain fields, methods, constants,
constructors, properties, indexers, operators and even other structure
types.
Structures Vs Classes
Structures Classes
[Link] type 1. Reference type
2. Supports data members, code 2. Supports data members, code
members (methods) and events. members (methods) and events.
3. Cannot inherit 3. Supports inheritance.
4. Preferable when we perform large 4. Preferable when we need to
number of operations on each initialize one or more members upon
instance. creation.
5. Cannot control initialization using 5. Can have parameterized
structure variable constructors
6. Less flexible, limited event handling 6. More flexible, unlimited event
support handling support
Declaration
Structures are declared using Structure ... End Structure statements.
Between these two statements, there must be at least one member declared.
This member can be of any data type, non-shared and non-event.
Structure Declaration:-
The keyword struct can be used to declare a structure.
General form of a structure declaration in [Link]:-
<modifiers> struct <struct_name>
Data members
….
End Structure
49
I MSc CS .Net Programming
Where the modifier can be private, public, internal or public. The struct
is the required keyword.
Example 1
Private Structure Product
Public PID as Integer
Public PName as String // Declare data members
Private UnitPrice as Single
Public Function GetPrice() as Single // Declare code members
GetPrice = UnitPrice
End Function
End Structure
In the above example, the Product structure is declared as Private. That
means we cannot access it from the object of the class where defined it. The
data member UnitPrice is declared as private can't access it outside the
structure.
Note that there is a function GetPrice defined within the Structure.
Using this code member, one can get UnitPrice of a product.
Example2
Structure MyStruct
Public x As Integer
Public y As Integer
End Structure MyStruct
Object Creation
The objects of a structure can be created by using the new operator as
follows.
Dim ms As New MyStruct()
The individual members of a structure can be accessed by using the dot
(.) operator as showing below.
ms.x = 10
ms.y = 20
The strcut object can also be created without using the new operator.
Dim ms As MyStruct
But in this case all fields of the struct will remain unassigned and the
object can't be used until all of the fields are initialized.
50
I MSc CS .Net Programming
Structures & Fields
A structure in [Link] can contain fields. These fields can be declared
as private, public, internal. Inside a structure, we can only declare a field. We
can't initialize a field inside a structure. However we can use constructor to
initialize the structure fields.
Structure MyStruct
Private x As Integer = 20 // Invalid declaration
Private y As Integer = 20
End Structure 'MyStruct
A valid [Link] structure is showing below.
Imports System
Structure MyStruct
Public x As Integer
Public y As Integer
End Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms As New MyStruct
ms.x = 10
ms.y = 20
Dim sum As Integer = ms.x + ms.y
[Link]("The sum is {0}", sum)
End Sub 'Main
End Class 'MyClient
Structure & Methods
A [Link] structure can also contain methods. The methods can be
either static or non-static. But static methods can access only other static
members and they can't invoke by using an object of the structure. They can
invoke only by using the struct name.
Imports System
Structure MyStruct
Private Shared x As Integer = 25
Private Shared y As Integer = 50
Public Sub SetXY(ByVal i As Integer, ByVal j As Integer)
x=i
51
I MSc CS .Net Programming
y=j
End Sub 'SetXY
Public Shared Sub ShowSum()
Dim sum As Integer = x + y
[Link]("The sum is {0}", sum)
End Sub 'ShowSum
End Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms As New MyStruct
[Link](100, 200)
[Link]()
End Sub 'Main
End Class 'MyClient
Collections
The .NET Framework provides certain classes to address the issues of
data storage outside databases known as collections.
Visual [Link] Collections are data structures that hold data in
different ways for flexible operations. The important data structures in the
collections are,
• Array list
• Hash Table
• Sorted List
• Dictionary
• Stack
• Queue
Advanced Array
There are more types of collections besides arrays, and they’re all hosted
in the [Link] class, an assembly exposing many classes that
implement collections, like the ArrayList and the HashTable collections.
[Link] supports arrays through the Array class is called Advanced
Array.
The System. Array class is not inheritable, which means we can’t create
custom arrays; the classes under System. Collections are inheritable.
The most important feature of the Array class is that [Link] arrays can
be sorted and searched.
52
I MSc CS .Net Programming
Sorting Array
An array is sorted by calling its Sort method or using own custom
sorting routines. If the array is sorted, we can call the Binary Search method
to locate an element.
The simplest form of the Sort method accepts a single argument, which
is the name of the array to be sorted:
[Link](arrayName)
This method sorts the elements of the array according to the type of its
elements.
The Sort method is a reference method. It requires that supply the name
of the array to be sorted as an argument.
We can also sort a section of the array with the following form of the
Sort method:
[Link](arrayName, startIndex, endIndex)
Where startIndex and endIndex are the indices that delimit the section
of the array to be sorted.
A variation of the Sort method, sorts the elements of an array according
to the values of the elements in another array.
syntax:
[Link](array1, array2)
array1 is the array with the keys, and array2 is the array with the actual
elements to be sorted.
The SortArrayByLength application is used to sort an array based on the
length of its elements.
Syntax:-
[Link](StringsLen, Strings)
Program for Sorting an Array According to the Length of Its Elements
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
[Link])
Dim Str(3) As String
Dim StrLen(3) As Integer
Str(0) = “Visual Basic”
Str(1) = “C++”
Str(2) = “C#”
Str(3) = “HTML”
53
I MSc CS .Net Programming
Dim i As Integer
For i = 0 To UBound(Str)
StrLen(i) = len(Str(i))
Next
[Link]()
[Link](“Original Array”)
[Link](“******************”)
Dim str1 As Integer
For str1 = 0 To UBound(Str)
[Link](Str(str1) & “ “ & StrLen(str1).ToString)
Next
[Link](“*************************”)
[Link](“Array Sorted According to String Length “)
[Link](“*************************”)
[Link](StrLen, Str)
For str1 = 0 To UBound(Str)
[Link](Str(str1) & “ “ & StrLen(str1).ToString)
Next
[Link](“*************************”)
End sub
Output
Original Array
*******************
Visual Basic 12
C++ 3
C# 2
HTML 4
*********************
Array Sorted According to String Length
*********************************************
C# 2
C++ 3
HTML 4
Visual Basic 12
*************************
54
I MSc CS .Net Programming
Searching Arrays
Searching Array is the process of locating element of array.
Arrays can be searched in two ways:
∗ with the BinarySearch method, which works on sorted arrays and
is extremely fast;
∗ with the IndexOf (and LastIndexOf) methods, which work
regardless of the order of the elements.
All three methods search for an instance of an item and return its index.
The IndexOf and LastIndexOf methods are similar to the methods by the
same name of the String class. They return the index of the first (or last)
instance of an object in the array.
IndexOf Method:-
The simplest form of the IndexOf method is:
itemIndex = [Link](array, object)
where array is the name of the array to be searched and object is the item
which want to search.
The LastIndexOf method’s syntax is identical, but the LastIndexOf
method starts searching from the end of the array.
Another form of the IndexOf and LastIndexOf methods allows to begin
the search at a specific index:
itemIndex = [Link](array, object, startIndex)
This form of the method starts searching in the segment of the array
from startIndex to the end of the array.
Finally, we can specify the range of indices where the search will take
place with the following form of the method:
itemIndex = [Link](array, object, startIndex,
endIndex)
Binary Search:-
BinarySearch method is ued to search large arrays more efficiently if the
array is sorted.
Simplest form of the BinarySearch method is
[Link](array, object)
Where array is the name of the array and object the item we’re searching
for.
55
I MSc CS .Net Programming
Specify the two indices to search a section of the array that delimit the
section of the array:
[Link](array, startIndex, selLength, object)
Benefits of Array Method:-
• Faster
• Easier to understand
• Efficient
Other Array Operations
The Array class exposes additional methods are
• Reverse method
• Copy Method
Reverse method
Reverse method reverses the order of the elements in an array.
Syntax of the Reverse method is,
[Link](array)
Example:-
Dim Names(99) As String
{
statements to populate array Names
}
Dim ReverseNames() As String
ReverseNames = [Link](Names)
Copy Method:-
The Copy and CopyTo methods copy the elements of an array (or
segment of an array) to another array. The Copy method copies a range of
elements from one array to another,
Syntax:-
[Link](sourceArray, destinationArray, count)
sourceArray and destinationArray are the names of the two arrays, and
count is the number of elements to be copied.
The copying process starts with the first element of the source array and
ends after the first count elements have been copied.
Both the Copy and CopyTo methods work with one-dimensional arrays
only.
56
I MSc CS .Net Programming
Array list
∗ The Array List collection allows maintaining multiple elements, similar
to an array.
∗ The Array List collection allows the insertion of elements anywhere in
the collection, as well as the removal of any element.
∗ It’s a dynamic structure that can also grow automatically as when add
elements.
∗ Like an array, the Array List's elements can be sorted and searched.
∗ In effect, the Array List is a more “convenient” array, a dynamic array
Creating an Array List:-
First we must create an instance of the Array List class with the New
keyword to use an Array List in code. Need not to specify any dimensions
When declare an Array List.
Statement to create Array list:-
Dim aList As New ArrayList
The aList variable represents an Array List that can hold only 16
elements (the default size). It is possible to set the initial capacity of the
ArrayList by setting its Capacity property.
Capacity property:-
The Capacity property is the number of elements the ArrayList
can hold. It’s like declaring an array for 100 elements, but using only 4 of
them. There are 96 more elements to be used.
The ArrayList’s capacity can be increased, or reduced, at any time,
just by setting the Capacity property.
The following statement sets the capacity of the ArrayList to 1,000
elements:
[Link] = 1000
The aList variable is now ready to hold a large number of items.
The exact number of items currently in the ArrayList is given by
the Count property.
Important functions in ArrayList
∗ Add - Add an Item in an ArrayList
∗ Insert - Insert an Item in a specified position in an ArrayList
∗ Remove - Remove an Item from ArrayList
∗ RemoveAt - remove an item from a specified position
∗ Sort - Sort Items in an ArrayList
57
I MSc CS .Net Programming
Adding an Items:-
The Add method is used to add a new item to an ArrayList.
Syntax:-
[Link](Item)
Where aList is a properly declared Array List and Item is the item
which wants to add to the Array List collection.
The Add method appends the specified item to the collection and
returns the index of the new item.
Example:-
Dim capital As New ArrayList()
capital. Add(“Chennai")
We can also add multiple items with a single call to the AddRange
method. This method appends a collection of items to the Array List.
The items could come from an array, or another Array List. The
following statement appends the elements of an array to the aList collection,
Dim colors() As Color = {[Link], [Link], [Link]}
[Link](colors)
Insert an item:-
Insert method is used to insert an item at a specific location.
The Insert method accepts as argument the location at which the new item
will be inserted and an object to insert in the Array List.
Syntax:-
[Link](index, object)
The Insert method doesn’t return a value to the location of the new item
is already known.
To insert a range of items anywhere in the ArrayList, use the
InsertRange method.
Syntax : [Link](index, objects)
Remove an item:-
The Remove method used to remove an item.
Syntax:-
[Link](object)
The object argument is the value to be removed, and not an index value.
The Array List allows removing items only by value. If the collection
contains multiple instances of the same item, only the first instance of the
object will be removed.
58
I MSc CS .Net Programming
Example:-
Dim R1 As New Rectangle(10, 10, 100, 100)
Dim R2 As Rectangle
[Link](R1)
[Link](R2)
R2 = New Rectangle(10, 10, 100, 100)
[Link](R2)
We can also remove items by specifying their order in the list with the
RemoveAt method. This method accepts as argument the location of the
item to remove, which must be less than the number of items currently in
the list.
Syntax:-
[Link](index)
Example:-
[Link](2)
The RemoveRange method can be used to remove more than one
consecutive item.
Syntax:-
[Link](startIndex, count)
Sorting an item:-
To sort the ArrayList, use the Sort method, which has three overloaded
forms:
[Link]()
[Link](comparer)
[Link](startIndex, endIndex, comparer)
The first form of the Sort method sorts the ArrayList alphabetically or
numerically, depending on the data type of the objects stored in it.
The other two forms of the Sort method use a custom function for
comparing items.
Program to add, insert, remove and sort an item in arraylist
Public Class Form1
Private Sub Button1_Click(ByVal sender As [Link],
ByVal e As [Link]) Handles [Link]
Dim i As Integer
Dim ItemList As New ArrayList()
[Link]("Item4")
[Link]("Item5")
59
I MSc CS .Net Programming
[Link]("Item2")
[Link]("Item1")
[Link]("Item3")
MsgBox("Shows Added Items")
For i = 0 To [Link] - 1
MsgBox([Link](i))
Next
[Link](3, "Item6")
[Link]()
[Link]("Item1")
[Link](3)
MsgBox("Shows final Items the ArrayList")
For i = 0 To [Link] - 1
MsgBox([Link](i))
Next
End Sub
End Class
Advantages of Array list:-
• Most flexible data structure
• Array List contains a simple list of values
• We can easily add , insert , delete , sort with Array List
• It is very flexible because we can add without any size information
• It grow dynamically
Hash Table
Hash Table stores a Key Value pair type collection of data. We can
retrieve items from hash Table to provide the key. Both key and value are
Objects.
The Hash Table collection is similar to the Array List, but it allows
accessing the items by a key. Each item has a value and a key.
The value is the same value which store in an array, but the key is a
meaningful entity for accessing the items in the collection.
The Hash Table exposes most of the properties and methods of the Array
List ie, The Count property returns the number of items in the collection as
usual, but the Hash Table collection doesn’t expose a Capacity property
because it uses fairly complicated logic to maintain the list of items, and it
adjusts its capacity automatically.
Add an item to Hash Table:-
Add method can be used to add an item to the Hash Table. Syntax:-
[Link](key, value)
value is the item want to add, and key is a value we supply, which
represents the item.
60
I MSc CS .Net Programming
Example:-
Dim Temperatures As New HashTable
[Link](“Houston”, 81)
The keys must be unique. If we attempt to use an existing key, an
argument exception will be raised.
The ContainsKey and ContainsValue methods to find out whether a
specific value or key is already in the collection.
ContainsKey : Check if a specified key exist or not
Synatx : [Link](key)
Key : The Key value for search in HahTable
ContainsValue : Check the specified Value exist in HashTable
Synatx : [Link](Value)
Remove an item from Hash Table:-
The Remove method, which accepts as argument the key of the item to
be removed from hash table.
Syntax:-
[Link](key)
CopyTo Method:-
The CopyTo method is used to extract items from a HashTable. This
method copies the items to a one-dimensional array.
Syntax
newArray = [Link](arrayName)
Sorted List
The Sorted List collection is a peculiar combination of the Array and
Hash Table classes.
It maintains a list of items, which can be accessed either with an index
or with a key.
The collection is always sorted according to the keys. The items of a
Sorted List are ordered according to the values of their keys, and there’s no
method for sorting the collection according to the values stored in it.
The Sorted List collection supports the Capacity and Count properties.
Statement to create a new Sorted List collection:-
Dim sList As New SortedList
Add an item to Sorted List:-
Add method is used to add an item to a Sorted List collection.
Syntax:-
[Link](key, item)
Where key is the key of the new item and item is the item to be added.
Both arguments are objects.
61
I MSc CS .Net Programming
The Add method is the only way to add items to a Sorted List collection.
All items are inserted into the collection according to their keys, and each
item’s key must be unique. Attempting to add a duplicate key will throw an
exception.
The Sorted List class also exposes the Contains Key and Contains Value
properties, which allow finding out whether a key or item exists in the list
already.
Example:-
If Not [Link](myKey) Then
[Link](myKey, myItem)
End If
To replace an existing item, use the SetByIndex method, which replaces
the value at a specific index.
Syntax :-
[Link](index, item)
Where the first argument is the index at which the value will be inserted
and item is the new item to be inserted in the collection.
Remove an item from sorted list:-
To remove items from the collection, use the Remove and RemoveAt
methods.
The Remove method accepts a key as argument and removes the item
that corresponds to that key.
The RemoveAt method accepts an index as argument and removes the
item at the specified index.
Clear method is used to remove all the items from a SortedList
collection.
TrimToSize method is called to restore its capacity to the default size
after clearing the collection.
Example Program
Public Sub Button1_Click(ByVal sender As [Link], ByVal e As
[Link])
Dim sList As New [Link]()
‘ Populate sortedlist
[Link](16, “item 3”)
[Link](10, “item 9”)
62
I MSc CS .Net Programming
[Link](15, “item 4”)
[Link](17, “item 2”)
[Link](11, “item 8”)
[Link](14, “item 5”)
[Link](18, “item 1”)
[Link](12, “item 7”)
[Link](19, “item 0”)
[Link](13, “item 6”)
Dim SLEnum As IDictionaryEnumerator
SLEnum = [Link]()
‘ Print all key-value pairs
While [Link]
[Link](“Key = “ & [Link] & “, Value= “ &
[Link])
End While
End Sub
Output
Key = 10, Value= item 9
Key = 11, Value= item 8
Key = 12, Value= item 7
Key = 13, Value= item 6
Key = 14, Value= item 5
Key = 15, Value= item 4
Key = 16, Value= item 3
Key = 17, Value= item 2
Key = 18, Value= item 1
Key = 19, Value= item 0
Creating Custom Classes
Introduction
A class is a program that doesn’t run on its own; it must be used by
another application.
The class is invoked by creating a variable of the same type as the class.
Then, exploit the functionality exposed by the class by calling the members of
the class through this variable.
The methods and properties of the class, as well as its events,
constitute the class’s interface.
The application uses the class’s interface to interact with the class.
63
I MSc CS .Net Programming
Example:-
When declare an array, invoke the [Link] class, which contains
all the code for manipulating arrays.
Even when we declare a simple integer variable, its need to invoking a
class, the [Link] class. This class contains the code that implements
the various properties (such as MinValue and MaxValue) and methods (such
as ToString) of the Integer data type.
Good Uses for Classes
• Wrapping up the representation and set of operations to perform on a
database table, for example adding, editing, deleting, and retrieving
data.
• Wrapping up the set of operations and data for dealing with text files
such as reading, writing, and indexing the lines of text within the file.
• Wrapping up all global variables in a program into properties within a
class.
Building the Minimal Class
A Class may reside in the same file as a Form, but it’s customary to
implement custom classes in a separate module, a Class module can also
create a Class project, which contains just a class.
Create a Windows application, add the class to it, and then test it by
adding the appropriate code to the form.
Start a new project and name it Simple Class then create a new class by
adding a Class item to project.
Right-click the project’s name in the Solution Explorer window and
select Add ➢Add Class from the context menu.
In the dialog box that pops up, select the Class icon and enter a name
for the class.
64
I MSc CS .Net Programming
Open the class by double-clicking its icon in the Project Explorer
window, then lines in the code window can appear as follows:
Public Class Minimal
End Class
Once class is created then add a button to the test form, and insert the
following code in its Click event handler:
Dim obj1 As Minimal()
Creating Properties
It is necessary to add a few properties and methods to perform simple
text-manipulation tasks.
The two properties are called property1 (a String) and property2 (a
Double).
We can simply declare them as public variables to expose these two
members as properties, to make it available to code outside the class.
The following line exposes the two properties of the class:
Public property1 As String, property2 As Double
The two methods are the ReverseString and NegateNumber methods.
The first method reverses the order of the characters in property1 and returns
the new string. The NegateNumber method returns the negative of property2.
Example to add a Few Members to the Minimal Class
Public Class Minimal
Public property1 As String, property2 As Double
Public Function ReverseString() As String
Return (StrReverse(property1))
End Function
Public Function NegateNumber() As Double
Return (-property2)
End Function
End Class
New Keyword
The New keyword tells VB to create a new instance of the Minimal class.
Initialize the object variable with the New keyword on a separate line:
obj = New Minimal()
If we omit the New keyword, a “Null Reference” exception will be thrown
when the code attempts to use the variable. This means that the variable is
Null—it hasn’t been initialized yet.
65
I MSc CS .Net Programming
Property Procedures
The property1 and property2 properties will accept any value, as long as
the type is correct and the value of the numeric property is within the
acceptable range.
We should be able to invoke some code to validate the values assigned
to the property. To implement the properties with code is called Property
procedures.
Properties are implemented with a special type of procedure that
contains a Get and Set section.
The Set section of the procedure is invoked when the application
attempts to set the property’s value, and the Get section is invoked when the
application requests the property’s value.
Usually, the value passed to the property is validated in the Set section
and, if valid, stored to a local variable. The same local variable’s value is
returned to the application when it requests the property’s value, from the
property’s Get section.
Implementing Properties with Property Procedures
Private tAge As Integer
Property Age() As Integer
Get
Age = tAge
End Get
Set (ByVal Value As Integer)
If Value < 0 Or Value >= 125 Then
MsgBox(“Age must be positive and less than 125”)
Else
tAge = Value
End If
End Set
End Property
tAge is the local variable where the age is stored. When the following line
is executed in the application, the Set section of the Property procedure is
invoked:
[Link] = 39
66
I MSc CS .Net Programming
Since the value is valid, it’s stored in the tAge local variable. when the
following one is executed,
[Link]([Link])
The Get section of the Property procedure is invoked, and the value 39 is
returned to the application.
Customizing Default Members(Creation of Method)
The class is exposed a few members (the default members) before adding
any code during the creation of Minimal class.
Members(Methods):-
ToString method : which returns the name of the class
Equals method : which compares two objects for reference equality
Custom implementation for these members:-
Custom ToString method must be implemented as a public function,
and it must override the default implementation.
Public Overrides Function ToString() As String
Return “The infamous Minimal class”
End Function
The Overrides keyword tells the compiler that this implementation
overwrites the default implementation of the class.
Example:-
Dim obj1 As New Minimal()
[Link] = #1/1/1963#
Dim obj2 As New Minimal()
[Link] = #12/31/1950#
[Link]([Link])
[Link]([Link])
The Equals method exposed by most of the built-in objects can compare
values, not references. Two Rectangle objects equal if their dimensions and
origins are the same.
Example:-
Dim R1 As New Rectangle(0, 0, 30, 60)
Dim R2 As New Rectangle
R2.X = 0
R2.Y = 0
[Link] = 30
[Link] = 60
If [Link](R2) Then
MsgBox(“The Two rectangles are equal”)
End If
67
I MSc CS .Net Programming
Working with Forms
Contents
Appearance of Forms
Loading and Showing Forms
Designing Menus
Building Dynamic Forms at Runtime
Introduction
In Visual Basic, the form is the container for all the controls that
make up the user interface.
When a Visual Basic application is executing, each window it
displays on the desktop is a form.
Forms are the only objects that can have menus.
The form is the top-level object in a Visual Basic application, and
every application starts with the form.
The terms form and window describe the same entity. A window is
what the user sees on the desktop when the application is running. A form
is the same entity at design time.
Forms have built-in functionality that is always available without any
programming effort.
Features of Forms in [Link]
Design forms that can be easily resized.
AutoScroll property, ie. Scrolling forms are also new to [Link].
A new special control was added, whose purpose is to act as a pane
separator on forms: the Splitter control.
[Link] you can create instances of new controls from within code and
position them on the form.
Appearance of Forms
Applications are made up of one or more forms and the forms are what
users see.
Forms are designed by adding various controls from toolbox.
The main characteristic of a form is the title bar on which the form’s
caption is displayed.
We should craft our forms carefully, make them functional, and keep
them simple and intuitive.
68
I MSc CS .Net Programming
Clicking the icon on the left end of the title bar in form opens the
Control menu, which contains the commands.
Commands of the Control Menu
Restore
Move
Size
Minimize
Maximize
Close
2. Properties of the Form Control:-
The dialog boxes that display critical information or prompt to select the
file to be opened are also forms.
We can duplicate the look of any window or dialog box through the
following properties of the Form object.
Accept Button and Cancel Button:
These two properties specify the default Accept and Cancel buttons. The
Accept button is the one that’s automatically activated when we press Enter,
and is usually the button with the OK caption.
The Cancel button is the one that’s automatically activated when hit the
Esc key and is usually the button with the Cancel caption.
To specify the Accept and Cancel buttons on a form, locate the Accept
Button and Cancel-Button properties of the form and select the
corresponding controls from a drop-down list, which contains the names of all
the buttons on the form.
69
I MSc CS .Net Programming
AutoScale:
This property is a True/False value that determines whether the
controls place on the form are automatically scaled to the height of the current
font.
When we place a TextBox control on the form, for example, the
AutoScale property is True, the control will be enough to display a single line
of text in the current font. The default value is True.
AutoScroll:
The AutoScroll property is a True/False value that indicates whether
scroll bars will be automatically attached to the form .
This property is new to [Link] and will help to large forms without
having to worry about the resolution of the monitor on which they’ll be
displayed.
70
I MSc CS .Net Programming
Form Border Style Enumeration
None - Borderless window that can’t be resized; this setting should be
avoided.
Sizable (default)- Resizable window that’s used for displaying regular
forms.
Fixed3D -Window with a visible border, “raised” relative to the main
area. Can’t be resized.
Fixed Dialog - A fixed window, used to create dialog boxes.
Fixed Single - A fixed window with a single line border.
Fixed Tool Window - A fixed window with a Close button only.
Sizable Tool Window - Same as the Fixed Tool Window but resizable. Its
caption font is smaller than the usual.
Control Box
This property is also True by default. Set it to False to hide the
icon and disable the Control menu.
Although the Control menu is rarely used, When the Control Box
property is False, the three buttons on the title bar are also disabled.
MinimizeBox, MaximizeBox
These two properties are True by default. Set them to False to hide
the corresponding buttons on the title bar.
Minimum Size, Maximum Size
These two properties read or set the minimum and maximum size
of a form.
Size Grip Style
This property gets or sets the style of sizing handle to display in
the bottom-right corner of the form.
Size Grip Style Enumeration
Auto (default)- The Size Grip is displayed as needed.
Show - The Size Grip is displayed at all times.
Hide - The Size Grip is not displayed, but the form can still be resized
with the mouse.
Start Position
This property determines the initial position of the form when it’s
first displayed.
71
I MSc CS .Net Programming
Form Start Position Enumeration
Center Parent -The form is centred in the area of its parent form.
Center Screen - The form is centred on the monitor.
Manual - The location and size of the form will determine its starting
position.
3. Placing Controls on Forms:-
The second step in designing application’s interface is the design of the
forms.
Designing a form means placing Windows controls on it, setting their
properties, and then writing code to handle the events of interest.
Visual [Link] is a rapid application development (RAD)
environment. This doesn’t mean that to develop Applications rapidly. It
means that can rapidly prototype an application and show something to
the customer.
Select controls in the Toolbox and then draw, on the form to place
controls on form.
Double-click the control’s icon to place an instance of the control on the
form.
All controls have a default size, and can resize the control on the form
with the mouse.
Set the control’s properties in the Properties window.
Each control’s dimensions can also be set in the Properties window,
through the Width and Height properties
4. Setting the Tab Order
Another important issue in form design is the tab order of the controls
on the form.
Pressing the Tab key at runtime takes to the next control on the form.
The order of the controls isn’t determined by the form; specify the order
during the design the application, with the help of the Tab Order
property.
Each control has its own Tab Order setting, which is an integer value.
When the Tab key is pressed, the focus is moved to the control whose
tab order immediately follows the tab order of the current control.
The Tab Order of the various controls on the form need not be
consecutive.
72
I MSc CS .Net Programming
Set their Tab Order property in the Properties window to specify the tab
order of the various controls or select the Tab Order command from the
View menu.
The tab order of each control will be displayed on the corresponding
control.
Setting the Tab Order of the controls on the main form
The default tab order is the same as the order in which we place the controls on
the form.
5. Form’s Events
The Form object triggers several events, the most important of them
being,
Activate
Deactivate
Closing
Resize
Paint
Activate and Deactivate:-
When more than one form is displayed, the user can switch from one to
the other with the mouse or by pressing Alt+Tab.
Each time a form is activated, the Activate event takes place. Likewise,
when a form is activated, the previously active form receives the
Deactivate event.
Closing Event
This event is fired when the user closes the form by clicking its Close
button. If the application must terminate because Window is shutting
down.
73
I MSc CS .Net Programming
Resize Event
The Resize event is fired every time the user resizes the form with the
mouse. Resize event’s handler to resize the controls and possibly
rearrange them on the form.
Paint Event
This event takes place every time the form must be refreshed. When you
switch to another form that partially or totally overlaps the current form
and then switch back to the first form
The Paint event will be fired to notify application that it must redraw the
form.
In this event’s handler, we insert the code that draws on the form.
Loading and Showing Forms
Multi-form applications are to load and manipulate forms from within
other forms’ code.
First create a variable that references the second form to access a form
from within another form.
Let’s application has two forms, named Form1 and Form2, and that
Form1 is the project’s start up form. To show Form2 when an action takes
place on Form1, first declare a variable that references Form2:
Dim frm As New Form2
This declaration must appear in Form1 and must be placed
outside any procedure.
Then, to invoke Form2 from within Form1, execute the following statement:
[Link]
Designing Menus
Menus are one of the most common and characteristic elements of the
Windows user interface.
Menus were used to display methodically organized choices and guide the
user through an application.
Menu Editor
Menus can be attached only to forms, and they’re implemented through
the Main Menu control. The items that make up the menu are Menu Item
objects.
The IDE provides a visual tool for designing menus, and then can
program their Click event handlers.
74
I MSc CS .Net Programming
76
I MSc CS .Net Programming
UNIT - III
Basic Windows Controls
Controls are the basic building blocks of the Windows user interface.
Basic Window controls are,
TextBox
ListBox
CheckedListBox
ComboBox
ScrollBar
TrackBar
TextBox Control:-
The TextBox control is the primary mechanism for displaying and
entering text.
It is one of the most common elements of the Windows user interface.
The TextBox control is a small text editor that provides all the basic
text-editing facilities such as,
Inserting text
Selecting text
Scrolling text
Exchanging text
The text box is an extremely versatile data-entry tool that can be used
for entering a single line of text.
The scroll bars in some text boxes are part of the control.
We can specify which scroll bars (vertical and/or horizontal) will appear
on the control, and the appropriate scroll bars are attached to the control
automatically whenever the control’s contents exceed the visible area of the
control.
77
I MSc CS .Net Programming
Basic Properties:-
Basic properties that determine the appearance and functionality of the
TextBox control, these can be set through the Properties window.
Properties that allows manipulating the control’s contents.
TextAlign property: which sets (or returns) the alignment of the text on the
control and can be Left, Right, or Center.
Font property: can set the font in which the text will be displayed.
BackColor property: which set the control’s background color .
BackImage property: used to display a background image.
MultiLine property determines whether the TextBox control will hold a single
line or multiple lines of text. By default, the control holds a single line of text.
To change this behavior, set the MultiLine property to True.
ScrollBars property controls the attachment of scroll bars to the TextBox
control if the text exceeds the control’s dimensions.
Single-line text boxes can’t have a scroll bar attached, even if the text
exceeds the width of the control.
Multiline text boxes can have a horizontal or a vertical scroll bar, or
both.
Scroll bars can appear in multiline text boxes
WordWrap property determines whether the text is wrapped automatically
when it reaches the right edge of the control. The default value of this property
is true.
AcceptsReturn, AcceptsTab These two properties specify how the TextBox
control reacts to the Return (Enter) and Tab keys.
The Enter key activates the default button on the form; default button is
usually an OK button that can be activated with the Enter key.
Press the Tab button repeatedly to move the focus to one of the buttons.
MaxLength property determines the number of characters the TextBox control
will accept. Its default value is 32,767.
Text-Manipulation Properties:-
Text property, which holds the control’s text.
Text property to extract the text entered by the user or to replace the
existing text by assigning a new value to the property.
The Text property is a string and can be used as argument with the
usual string-manipulation functions.
78
I MSc CS .Net Programming
The following expression returns the number of characters in the
TextBox1 control:
Dim strLen As Integer
strLen = [Link]
Call the Len () function, which does the same:
strLen = Len([Link])
We can set its Text property to a blank string to clear the control,
[Link] = “”
or call the control’s Clear method:
[Link]
IndexOf method of the String class will locate a string within the
control’s text.
The following statement returns the location of the first occurrence of
the string “Visual” in the text:
Dim location As Integer
location = [Link](“Visual”) We can also use
the InStr() function,
location = Instr([Link], “Visual”)
To store the control’s contents in a file, use a statement such as
[Link]([Link])
Similarly,we can read the contents of a text file into a TextBox control
with a statement such as
[Link] = [Link]
where StrReader and StrWriter are two properly declared StreamReader
and StreamWriter object variables.
Replace method is used to replace a string with another within the line.
Split method to split the line into smaller components (like words), and
any other method exposed by the String class.
The following statement appends a string to the existing text on the
control:
[Link] = [Link] & newString
READONLY, LOCKED:-
ReadOnly propertity used to prevent users from editing the text.
When ReadOnly is set to True, put text on the control from within code
and users can view it but they can’t edit.
79
I MSc CS .Net Programming
Set the Locked property to True to prevent the editing of the TextBox
control from others.
PasswordChar:-
This property turns the characters typed into any character which we
specify. If we don’t want to display the actual characters typed by the user
(when entering a password, for instance), use this property to define the
character to appear in place of each character the user types.
Set this value to an asterisk (*), for example, the user sees an asterisk in
the place of every character typed. This property doesn’t affect the control’s
Text property, which contains the actual characters.
Text-Selection Properties:-
The TextBox control provides three properties for manipulating the text
selected by the user:
SelectedText
SelectionStart
SelectionLength
SelectedText:-
This property returns the selected text, enabling to manipulate the
current selection from within code.
For example
We can replace the selection by assigning a new value to the
SelectedText property.
To convert the selected text to uppercase, use the ToUpper method of
the String class:
[Link] = [Link]
To delete the current selection, assign an empty string to the
SelectedText property:
[Link] = “”
SelectionStart:-
The SelectionStart property returns or sets the position of the first
character of the selected text in the control’s text.
SelectionLength:-
The SelectionLength property returns or sets the length of the selected
text.
80
I MSc CS .Net Programming
Dim seekString As String
Dim textStart As Integer
seekString = “Visual”
textStart = [Link](seekString)
If textStart > 0 Then
[Link] = selStart – 1
[Link] = [Link]
End If
Text-Selection Methods:-
The TextBox control exposes two methods for selecting text. we can
select some text with the Select method, whose syntax is shown next:
[Link](start, length)
The Select method is new to [Link] and is equivalent to setting the
SelectionStart and SelectionLength properties.
If the TextBox control contains the string “ABCDEFGHI,” then the
following statement will select the range “DEFG”:
[Link](3, 4)
ListBox, CheckedListBox, and ComboBox Controls:-
The ListBox, CheckedListBox, and ComboBox controls present
lists of choices, from which the user can select one or more.
ListBox control occupies a user-specified amount of space on the
form and is populated with a list of items.
If the list of items is longer than can fit on the control, a vertical
scroll bar appears automatically.
The items must be inserted in the ListBox control through the
code or via the Properties window.
81
I MSc CS .Net Programming
The ComboBox control also contains multiple items but typically
occupies less space on the screen.
The ComboBox control is an expandable ListBox control: the user can
expand it to make a selection and collapse it after the selection is made.
The real advantage to the ComboBox control, is that the user can enter
new information in the ComboBox, rather than being forced to select from the
items listed.
Basic Properties
The ListBox and ComboBox controls provide a few common properties
that determine the basic functionality of the control and are usually set at
design time;
IntegralHeight
This property is a Boolean value (True/False) that indicates whether the
control’s height will be adjusted to avoid the partial display of the last item.
Items
The Items property is a collection that holds the items on the control.
Locate the Items property in the Properties window to load a number of items
to a ListBox control at design time.
MultiColumn
A ListBox control can display its items in multiple columns, if we set its
MultiColumn property to True.
SelectionMode
This property determines how the user can select the list’s items and
must be set at design time.
Sorted
If we want the items to be always sorted, set the control’s Sorted
property to True.
Text
The Text property returns the selected text on the control.
ScrollBar and TrackBar Controls
The ScrollBar and TrackBar controls let the user specify a magnitude by
scrolling a selector between its minimum and maximum values.
In some situations, the user doesn’t know in advance the exact value of
the quantity to specify, so application must provide a more flexible mechanism
for specifying a value, along with some type of visual feedback.
The vertical scroll bar that lets a user move up and down a long
document is a typical example of the use of a ScrollBar control.
82
I MSc CS .Net Programming
The scroll bar is a prime mechanism for repositioning the view in a long
document or in a large picture that won’t fit entirely in its window.
The user uses the scroll bar to navigate through the document.
The TrackBar control is similar to the ScrollBar control, but it doesn’t
cover a continuous range of values. The TrackBar control has a fixed number
of tick marks.
ScrollBar Control
The ScrollBar control is a long stripe with an indicator that lets the user
selects a value between the two ends of the control, and it can be positioned
either vertically or horizontally.
Use the Orientation property to make the control vertical or horizontal.
The left (or bottom) end of the control corresponds to its minimum
value; the other end is the control’s maximum value. The current value of the
control is determined by the position of the indicator, which can be scrolled
between the minimum and maximum values.
The basic properties of the ScrollBar control, are properly named
Minimum, Maximum, and Value.
83
I MSc CS .Net Programming
More Windows Controls
Common Dialog Controls
All Windows applications use some standard dialog boxes for common
operations.
These dialog boxes are built into the Framework system, and any
application can use them.
The common dialog controls are invisible at runtime, and they’re not
placed on forms.
Simply add them to the project by double-clicking their icons on the
Toolbox.
When a common dialog control is added to a project, a new icon appears
in the components tray of the form, just below the Form Designer.
Common dialog controls are available on the Toolbox
• OpenFileDialog: Lets users select a file to open. It also allows the
selection of multiple files, for applications that must process many files
at once.
• SaveFileDialog: Lets users select or specify a filename in which the
current document will be saved.
• ColorDialog: Lets users select a color from a list of predefined colors, or
specify custom colors.
• FontDialog: Lets users select a typeface and style to be applied to the
current text selection.
• PrintDialog: Lets users select and set up a printer.
Using the Common Dialog Controls
First add an instance of the appropriate control to project to display a
common dialog from within application.
Then, set basic properties of the control through the Properties window.
Most applications set the control’s properties from within the code to
display a common dialog box from within code, simply call the control’s
ShowDialog method, which is common for all controls.
call the ShowDialog method, the corresponding dialog box appears on-
screen and the execution of the program is suspended until the box is closed.
Example:-
If [Link] = [Link] Then
fileName = [Link]
End If
The ShowDialog method is common to all controls.
84
I MSc CS .Net Programming
Color Dialog Box
• Color dialog box is one of the simplest dialog boxes. It has a single
property, Color, which returns the color selected by the user or sets the
initially selected color when the user opens the dialog box.
• Before opening the Color common dialog with the ShowDialog method,
can set various properties.
RichTextBox Control
The RichTextBox control is the core of a full-blown word processor. It
provides all the functionality of a TextBox control;
In addition, it gives the capability to mix different fonts, sizes, and
attributes; and it gives precise control over the margins of the text.
86
I MSc CS .Net Programming
We can even place images in text on a RichTextBox control.
The fundamental property of the RichTextBox control is its RTF property.
Similar to the Text property of the TextBox control, this property is the text
displayed on the control.
Text property, which returns (or sets) the text of the control but doesn’t
contain formatting information, the RTF property returns the text along with
any formatting information.
RichTextBox control to specify the text’s formatting, including paragraph
indentation, font, and font size or style.
RTF stands for Rich Text Format, which is a standard for storing
formatting information along with the text.
The beauty of the RichTextBox control for programmers is that
they don’t need to supply the formatting codes.
RichTextBox’s Properties
The names of the RichTextBox control’s properties for manipulating
selected text mostly start with Selected or Selection.
The most commonly used properties related to the selected text are,
SelectedText: The selected text
SelectedRTF : The RTF code of the selected text
SelectionStart: The position of the selected text’s first character
SelectionLength: The length of the selected text
SelectionFont: The font of the selected text
SelectionColor: The color of the selected text
RightMargin: The distance of the text’s right margin from the left edge of the
control, which is in effect the length of each text line.
SelectionBullet: Whether the selected text is bulleted.
BulletIndent: The amount of bullet indent for the selected text.
SelectionIndent: SelectionRightIndent, SelectionHangingIndent.
SelectedText:-
The SelectedText property represents the selected text. To assign the
selected text to a variable, use the following statement:
SText=[Link]
RichTextbox1 is the name of the control.
SelectionStart, SelectionLength:-
87
I MSc CS .Net Programming
Two additional properties, SelectionStart and Selection Length are used
to simplify the manipulation and formatting of the text on the control report
the position of the first selected character in the text and the length of the
selection.
[Link] = 0
[Link] = Len ([Link])
SelectionAlignment:-
Use this property to read or change the alignment of one or more
paragraphs.
This property value is one of the members of the HorizontalAlignment
enumeration: Left, Right, and Center.
[Link] = Left([Link])
SelectionIndent, SelectionRightIndent, SelectionHangingIndent:-
These properties allow to change the margins of individual paragraphs.
Selection Indent property sets (or returns) the amount of the text’s
indentation from the left edge of the control.
SelectionRightIndent property sets (or returns) the amount of the
text’s indentation from the right edge of the control.
SelectionHangingIndent property is the distance between the left edge
of the first line and the left edge.
SelectionBullet, BulletIndent:-
These properties are used to create a list of bulleted items. If we set the
SelectionBullet property to True, the selected paragraphs are formatted with a
bullet style.
To change a list of bulleted items back to normal text, make the same
property False.
To set the amount of the indentation, use the BulletIndent property,
whose syntax is
[Link] = value
Methods
The first two methods of the RichTextBox control are
SaveFile and LoadFile
SaveFile saves the contents of the control to a disk file.
LoadFile loads the control from a disk file.
88
I MSc CS .Net Programming
SaveFile
The syntax of the SaveFile method is
[Link](path, filetype)
where path is the path of the file in which the current document will be
saved. By default, the SaveFile method saves the document in RTF format and
uses the RTF extension.
LoadFile
The LoadFile method loads a text or RTF file to the control. Its syntax is
identical to the syntax of the SaveFile method:
[Link](path, filetype)
The filetype argument is optional and can have one of the values of the
RichTextBoxStreamType enumeration.
Select, SelectAll:-
The Select method selects a section of the text on the control, similar to
setting the SelectionStart and SelectionLength properties.
The Select method accepts two arguments, which are the location of the
first character to be selected and the length of the selection:
[Link](start, length)
The SelectAll method accepts no arguments and selects all the text on
the control.
Advanced Editing Features
The RichTextBox control provides all the text-editing features such as,
Undo and Redo
Cut, copy and Paste
Find
CanUndo, CanRedo
These two properties are Boolean values can read to find out whether an
operation can be undone or redone.
The following statements disable the Undo command if there’s no action
to be undone at the time, where EditUndo is the name of the Undo command
on the Edit menu:
If [Link] Then
[Link] = True
Else
[Link] = False
End If
89
I MSc CS .Net Programming
Cut, Copy and Paste:-
The methods Copy, Cut, and Paste perform the corresponding
operations.
The Cut and Copy methods are straightforward and require no
arguments.
The Paste method accepts a single argument, which is the format of the
data to be pasted.
If [Link]([Link]) Then
[Link]([Link])
End If
Searching in a RichTextBox Control
The Find method locates a string in the control’s text.
[Link](string)
[Link](string, start, searchMode)
[Link](string, start, end, searchMode)
Error Handling and Debugging
The complex nature of software development leads to errors in
programming.
When writing Visual Basic .NET code, some of the tools that can use to
locate these errors and the coding structures used to prevent these errors
when users run the program.
Contents
• Types of Errors
• Exceptions and Structured Exception Handling
Types of Errors
The errors caused by a computer program can be categorized into three
major groups:
• Design-time error
• Runtime error
• Logic error
The design-time error is the easiest to find and fix. A design-time error
occurs when write a piece of code that does not conform to the rules of the
language in which we’re writing.
They are easy to find because Visual Studio .NET tells not only where
they are, but also what part of the line it doesn’t understand.
90
I MSc CS .Net Programming
Runtime errors are harder to locate, because VS doesn’t give any help
in finding the error until it occurs in program. These errors occur when
program attempts something illegal, like accessing data that doesn’t exist or a
resource to which it doesn’t have the proper permissions.
The logic error is often the most insidious type to locate, because it may
not manifest itself as a problem in the program at all.
A program with a logic error simply means that the output or operation
of program is not exactly as we intended it. It could be as simple as an
incorrect calculation.
Design-Time Errors:-
Also called syntax errors.
Design-time errors occur when the Visual Basic .NET interpreter cannot
recognize one or more lines of code that have written.
Some design-time errors are simply typographical errors, where we
have mistyped a keyword. Others are the result of missing items: undeclared
or untyped variables, classes not yet imported, incorrect parameter lists in a
function or method call, or referencing members of a class that do not exist.
A program with as few as one design-time error cannot be compiled and
run so it must locate and correct the error before continuing.
Fortunately, design-time errors are the easiest to detect and correct,
because [Link] shows the exact location of these errors and gives good
information about what part of the code it can’t understand.
Example:
Note the three blue squiggly lines under various parts of this brief code (under
two instances of the letter i and under the term lbNumbers). Each one of those
squiggly lines represents a design-time error.
To determine what the errors are, locate the Task List window in the IDE
and bring it forward. The Task List displays the errors
91
I MSc CS .Net Programming
.
Runtime Errors:-
Runtime errors are much more insidious to find and fix than design-
time errors.
Runtime errors are problems encountered by program while it’s
running. Runtime errors can take on dozens of different shapes and forms.
Here are some examples:
Attempting to open a file that doesn’t exist
Trying to log in to a server with an incorrect username or password
Trying to access a folder for which have insufficient rights
Requesting data from a database table that has been renamed
Opening a file on a server that is down for maintenance
Accessing an Internet URL that no longer exists
Allocating a resource without the necessary available RAM
Dividing a number by zero
Users entering character data where a number is expected
Runtime errors can be many degrees harder to diagnose and fix
compared to design-time errors.
Logic Errors:-
Logic errors also occur at runtime, and because of this, they are
often difficult to track down.
A logic error occurs when a program does not do what the
developer intended it to do.
Private Sub Button1_Click (ByVal sender As [Link], _
ByVal e As [Link]) Handles [Link]
Dim i As Integer
i=1
Do While i > 0
i += 1
Loop
End Sub
92
I MSc CS .Net Programming
Here we have an integer variable set to 1 and incremented by one in a
loop. Each time the loop iterates, the number gets bigger. The loop will
continue to iterate as long as the variable is greater than 0.
The problem is that the value of the variable will always be greater than
0, so the loop will never terminate. This is called an infinite loop.
Exceptions and Structured Exception Handling
A runtime error in [Link] generates an exception. An exception is a
response to the error condition that the program just generated. Example of an
exception message:
93
I MSc CS .Net Programming
Basic syntax of structured error handling:
Try
'Code that may raise an error.
Catch
'Code to handle the error.
Finally
'Code to do any final clean up.
End Try
The Try and End Try statements are required.
The Catch and Finally statements are not required, though must
include at least one of them in code.
We can also specify multiple Catch statements so that each Catch block
handles a specific error.
Catch an Exception:-
Start Visual Studio .NET.
Create a new Console Application project in Visual Basic .NET
Sub Main procedure, add the following code:
Dim a As Integer = 0
Dim b As Integer = 0
Dim c As Integer = 0
Try
a=b\c
Catch exc As Exception
[Link]("A run-time error occurred")
Finally
[Link]()
End Try
On the Debug menu, click Start to run the application.
The code tries to divide a number by zero. This is an illegal operation
that causes a divide by zero exception. Fortunately, the Catch block catches
this error, and the Console window displays the following error message:
A run-time error has occurred.
Catch Multiple Exceptions:-
This section demonstrates how to use multiple Catch statements to
handle different error
94
I MSc CS .Net Programming
In the Sub Main procedure,
Dim a As Integer = 2147483647
Dim b As Integer = 0
Dim c As Integer = 0
Try
a += 1
Catch exc As DivideByZeroException
[Link]("Error: Divide by zero")
Catch exc As OverflowException
[Link]("Error: Overflow")
Finally
[Link]()
End Try
Throw an Exception:-
Structured exception handling uses the Catch statement to catch an
exception.
Structured exception handling also provides a way to throw an
exception.
For example, it is useful to throw an exception when we perform data
validation inside a Property Set procedure because may want to throw an
error if a business rule is violated.
Create a new Console Application project in Visual Basic .NET
On the Project menu, click Add Class.
In the Add New Item window, type [Link] in the Name text box,
and then click OK.
Add the following code inside the Public Class clsPerson...End
Class statements:
Private mintAge As Integer
Public Property Age() As Integer
Get
Age = mintAge
End Get
Set(ByVal Value As Integer)
If Value >= 0 Then
mintAge = Value
95
I MSc CS .Net Programming
Else
Throw New ArgumentException ("Age cannot be negative")
End If
End Set
End Property
This code creates an Age property. Because a person cannot have a
negative age, an error is raised if the user of the class tries to set Age to a
number that is less than zero.
In the Sub Main procedure of [Link], add the following code:
Dim p As New clsPerson()
Try
[Link] = -1
Catch exc As Exception
[Link]([Link])
Finally
[Link]()
End Try
On the Debug menu, click Start to run the application. The Console
window displays the following error message:
Age cannot be negative.
Try…Finally
The Try…Finally blocks are usually used in order to ensure that
allocated resources are being cleaned up. These blocks allow catching and
handling errors, as well as execute a section of the code regardless of whether
there is an error. The basic format of the block is listed below:
'Resource allocation code
Try
'Use the resource
Finally
'Clean the resource up
End Catch
Protected Sub ReadFromATextFile(cFilename as string)
Dim s As StreamReader
Dim cLine As String
Dim bDone As Boolean = False
96
I MSc CS .Net Programming
[Link]()
s = New Streamreader(cFilename)
Try
While Not bDone
cLine = [Link]()
If cLine Is Nothing Then
bDone = True
Else
Call [Link](cLine)
End If
End While
Catch oEX as Exception
Call MsgBox(“some error occurred”)
Finally
[Link]()
End Try
End Sub
Accessing Database
Building Database Applications with [Link]
[Link] is a model used by .NET applications to communicate with a
database for retrieving, accessing and updating data.
[Link] is a part of .NET framework architecture.
[Link] is the name for the data access layer provided by the .NET
framework class library (FCL). Conceptually, [Link] can be divided into two
distinct parts:
• Data access mechanism
• Data storage system
All of the principle classes, interfaces, and types used in [Link] are
defined under the [Link] second-level namespace.
These classes include DataColumn, DataRelation, DataRow, DataSet,
DataView and DataTable.
97
I MSc CS .Net Programming
Architecture of [Link]:-
98
I MSc CS .Net Programming
Open() Method: It opens a database connection with the property
settings specified by the connection string.
Close() Method: It closes the connection to the database.
Various parameter of the connection string,
Provider: set the name of provider for connection
Initial Catalog: Used to specify the name of database
Datasource: Used to specify name of server
UserID : Specify server login account
Password: specify password for server login account
Example:
//Create an object of the sqlConnection class
SqlConnection connection = new SqlConnection()
//Create a connection string to the HR database
[Link] = “Data Source = SQLSERVER01; Initial
Catalog = HR; User ID = sa; password = niit#123”;
Creating a Command Object:
After a connection has been established, execute commands and
return the result from data source using command object.
We can execute Sql statements or stored procedures through
command object.
Example:- //Sqlcommand cmd=new Sqlcommand(“select * from
salary”,conn);
Opening the Connection Object:-
After defining connection string, we need to open the connection by
using Open() method.
// Open the connection
[Link]()
Executing SQL Statements in the Command Object:-
To execute the query passed in the command object, call its methods.
// Create an object of the sqlDataReader class
sqlDataReader myReader = [Link]
Closing the connection object:-
After executing the commands we should close the connection.
//close the connection
[Link]()
99
I MSc CS .Net Programming
Creating a DataSet:-
Exploration of database programming by creating a Datasets.
Steps to create a new database application:
1. Start a new project as usual.
2. When the project’s form appears, open the Server Explorer and
expand one of the databases.
3. Select the database and expand its icon to see the objects of the
database.
4. In the Tables section, select the Customers table, drag it with
the mouse, and drop it on the form.
VB will add two new objects in the Components
Connection and DataAdapter.
We must first establish a connection to the database to get the data into
a DataSet.
The Connection object allows specifying the database which want to
work, and it’s one of the simpler objects of [Link].
OleDbDataAdapter class to obtain rows from the Access database and
to insert the rows into a DataSet object.
If we’re working with an Access database, follow the same steps, but the
objects will have different names.
The Connection object’s default name will be OleDbConnection, and the
DataAdapter object’s default name will be OleDbDataAdapter. The SQL
statements that move data in and out of an Access database may use a
slightly different syntax, but they’re equally simple statements.
Select the DataAdapter object on the designer and locate the Generate
Dataset link at the bottom of the Properties window. Alternatively, we can
open the Data menu and select the Generate Dataset command. (The Data
menu isn’t available unless the form is visible.)
Generate Dataset dialog box:-
100
I MSc CS .Net Programming
This dialog box proposes to create a new DataSet object, named
DataSet1, that will contain the table Customers. DataSet may contain multiple
tables that’s why option to select the table(s) which want to add to the
DataSet. Click OK to create the new DataSet object.
Open the Data menu and select Preview Data. Alternatively,
right-click the DataAdapter’s icon in the Components tray and select
Preview Data.
Data Adapter Preview dialog box:-
DataGrid Control
One of the most common tasks in programming database
applications is to present data to the users. We have created the DataSet that
will hold data, so we can now design an interface to present the data residing
in the DataSet to the user.
Data can be displayed by establishing the connection to the
database and binding the data using DataGridView.
101
I MSc CS .Net Programming
Steps for creating Database Application in [Link]
1. Design Window Form
2. Create a database
3. Create a connection to the database by using [Link]
4. Execute the window form and verify the output
Step1: Designing window form
Window application is created using following steps,
• 1. Start Microsoft Visual Studio .NET.
• 2. On the File menu, point to New, and then click Project.
• 3. Under Project Types, click Visual Basic Projects.
• 4. Under Templates, click Windows Application, and then click OK.
By default, Form1 is created.
Step2: Create a database
To create a database in Access and then create a table in the
database, follow these steps:
• 1. Start Access.
• 2. On the File menu, click New.
• 3. Click Blank database on the task pane.
• 4. In the File name box, type dbname, and then click Create.
• 5. Right-click Create table in Design view, and then click Open.
• 6. In the Fielding the data
• 7. In the Data Type list, click Type of data
• 8. Type several more records in the table, and then close table
• 9. Close the dbname database.
Step3: Create a connection to the database
Open a connection to the Access database,
• 1. On the View menu, click Server Explorer.
• 2. In Server Explorer, right-click Data Connections, and then click Add
Connection.
• 3. In the Data Link Properties dialog box, click the Provider tab.
• 4. In the OLE DB Provider(s) list, click Microsoft Jet 4.0 OLE DB
Provider, and then click Next.
• 5. Click the Connection tab, and then click the ellipses button (...).
• 6. Locate the Access database [Link] file that created by following
the corresponding path on computer.
• 7. Select the [Link] file, and then click Open.
• 8. In the Data Link Properties dialog box, click OK.
102
I MSc CS .Net Programming
Retrieve data from the Access database by using the OleDbDataAdapter
class,
• 1. On the toolbox, click the Data tab.
• 2. Drag an OleDbDataAdapter control to Form1.
• 3. In the Data Adapter Configuration Wizard, click Next three times.
• 4. In the Generate the SQL statements panel, type the following
Microsoft SQL Server statement, and then click Next:
Select * from dbname
• 5. In the View Wizard Results panel, click Finish.
• 6. Right-click OleDbDataAdapter1, and then click Generate Dataset.
• 7. In the Generate Dataset dialog box, click OK.
• 8. Add the following code to the Form1_Load event handler:
'Fill retrieves rows from the data source by using the SELECT
statement
[Link](DataSet11)
Display records that are retrieved from the Access database
1. Add a DataGrid control to Form1.
By default, DataGrid1 is created.
2. Right-click DataGrid1, and then click Properties.
3. In the Properties dialog box, set the DataSource property to
DataSet11 and set the DataMember property to dbname.
ADO Recordset
Using ADO recordset in managed code using [Link] data
providers is simple.
Visual studio .NET provides to add reference to the COM libraries.
The first step to add a reference to the ADO library. Add reference
to the ADO library by using Project->Add Reference menu item and then select
COM tab
103
I MSc CS .Net Programming
104
I MSc CS .Net Programming
Data Provider:-
A data provider is used for connecting to a database, retrieving data,
storing the data in a dataset, reading the retrieved data and updating the
database.
Four main types of data providers are,
.NET Framework data provider for SQL Server:
It is used to work specifically with Microsoft SQL Server.
.NET Framework data provider for OLE DB:
This type of provider uses native OLE DB through Component Object
Model (COM) interoperability to enable data access.
.NET Framework data provider for ODBC:
This provider uses the ODBC driver manager through COM
interoperability to enable data access.
.NET Framework data provider for Oracle:
It enables data access to Oracle data sources through the Oracle client
connectivity software.
Key Components of data provider are:-
Connection:
The component is used to establish (open) a connection with a data
source such as database.
Database connection is represented in the Connection object, which
includesConnectionString and ConnectionTimeout.
Connection object helps in accessing and manipulating a database.
Database transactions are also dependent upon the Connection object.
Commonly used connections in the [Link]
• SqlConnection
• OleDbConnection
• OdbcConnection
Command:
The Command object is used to perform action on the data source.
Command object can execute stored procedures and T-SQL commands.
This component is used to retrieve, insert, delete, or modify data in data
source.
105
I MSc CS .Net Programming
Datareader:
This component is used to retrieve data from a data source quickly in a
read-only and forward only mode.
DataAdapter:
This component is used to transfer data to and from a database .
A data adapter retrieves data from a database into a dataset.
DataAdapter object works in connected model. DataAdapter performs
five following steps:
• Create/open the connection
• Fetch the data as per command specified
• Generate XML file of data
• Fill data into DataSet
• Close connection
Command Builder:
It is used to save changes made in-memory cache of data on backend.
The work of Command Builder is to generate Command as per changes in
DataRows.
Command Builder generates command on basis of row state. There are
five row states:
• Unchanged
• Added
• Deleted
• Modified
• Detached
Command Builder works on add, delete and modified row state only.
Detached is used when object is not created from row state.
Transaction:
The Transaction object is used to execute backend transaction.
Transactions are used to ensure that multiple changes to database rows
occur as a single unit of work.
The Connection class has a Begin Transaction method that can be used
to create a Transaction.
Parameters:
Parameter object is used to solve SQL Injection attack problem while
dealing with the user input parameters.
Parameter object allows passing parameters into a Command object the
Parameter class allows to quickly put parameters into a query without string
concatenation.
106
I MSc CS .Net Programming
Dataset:
The dataset is a memory based relational representation of data.
A dataset is a part of the disconnected environment.
A dataset is disconnected, cached set of records that are retrieved from a
database.
A dataset is a collection of one or more Data Table objects made up of
rows and columns of data as well as constraints and relation information
about data in the data table objects.
A dataset is present in the DataSet class in the [Link]
namespace.
Key Components of Dataset are,
DataTable Collection: It contains all the tables retrieved from data
source.
DataRelationCollection: It contains relationship and links between
tables in a dataset.
DataTable: It represents a table in the datatable collection of a dataset.
DataRowCollection: It contains all the rows in a datatable.
DataColumnCollection: It contains all the Columns in a datatable.
Features of [Link]:-
• Disconnected data architecture
• Data cached in datasets
• Scalability
• Data transfer in XML format
107
I MSc CS .Net Programming
UNIT – IV: [Link]
Introducing Visual Web Developer Tools
Rapid application development tool allows developer to build high-
quality applications more quickly.
These tools allow developer to create prototypes, develop reusable
software components and facilitate communication and file management.
There are many text and web page editors that can be used to create
Web applications.
Web applications are created using a basic text editor and then copy or
upload the application to a Web server using basic file transfer program (FTP).
[Link] is a compatible web editor such as Visual [Link] or
Visual Web Developer Express(VWD).
VWD was chosen as a platform because it contains the same basic
[Link] features as Visual Studio .NET.
EXPLORING VISUAL WEB EDITORS:-
VWD provides web developer and windows programmer a consistent
programming model using Visual Studio .NET.
A Start Page provides access to recently created applications and links
to the MSDN support site.
Click the application name on the Start Page to reopen application
quickly. If we closed the Start Page and want to reopen it, click View on menu
bar, select other windows and then click Start Page.
EXPORING THE INDIVIDUAL WINDOWS:-
Properties window
Main window
Solution window
Database Explorer window
Toolbox window
Task list window
Properties windows:-
Properties window is used to set properties for object, controls and
classes.
If we can click a control, the properties for that control are displayed in
the properties window.
Many properties can be set through the properties window during the
design of web pages.
108
I MSc CS .Net Programming
Main Window:-
Main window is used to view the project files.
If we open multiple documents in the main window at the same time, a
document tab appears in the main window to allow to switch between
documents easily.
Solution Explorer window:-
This window is used to display solution name and project name.
It also used to manage all of the files and resources within applications.
Database explorer window:-
This window is used to create and manage connections to databases
and to manage data object such as tables and stored procedures.
Toolbox window:-
Toolbox contains frequently used controls. These controls are organized
using tabs.
General and other tabs of Toolbox
Standard tab: Contains many of the [Link] controls that are used
within [Link] pages.
Data tab: Provides access to data controls used to display data and data
source controls.
Validation tab: Provides access to controls used to validate webpage
forms.
Navigation tab: Provides access to controls used to create site map,
menus and tree views.
Login tab: Provides access to controls that used to create a login,
password recovery and change password form.
Web parts tab: Provide access to create and manage a new way of
organizing web pages using web parts and web zones.
HTML tab: Provides access to the traditional HTML tags. ie. Basic
formatting and anchor tag is not included here.
General tab: This tab is used to store user created controls and
snippets of code which want to reuse.
Task list window:-
This window allows to manage a list of user tasks comments within
applications.
109
I MSc CS .Net Programming
Additional properties:-
It allows customizing the layout of user environment.
Auto Hide Property:-
This property is new feature that allows to store the window on the
desktop as a tab.
Dockable Property:-
It allows window to be moved to other location on desktop and to be
placed on top of one another.
Floating Property:-
This property allows selecting the window and dragging and dropping it
to any location on the desktop.
CREATING A NEW WEB APPLICATION
To create a new web application,
1. Start web editor application
2. Click the File on menu bar and click New web site to create a new
project. The new website window opens. [Link] web site is selected by
default is used to create a blank [Link] Web site.
3. Click browse button which opens the Choose Location window.
4. Navigate through file system to locate and click
5. Click Create New Folder icon type WebSite1 then press Enter if need to
create new folder to store web application.
6. Click open, which closes the Choose Location Window.
7. Click Ok to create web application and close new web site window.
8. Click File on menu bar then click Close Project to close the web
application.
9. Click File on menu bar then click Exit to exit.
Introduction to [Link] server programming
Programming that makes Client applications to communicate with
server application in a network is referred to as client-server programming.
Technology created by Microsoft called Active Server Page .NET
([Link]) is used to create client-server applications.
Because these client-server applications communicate primarily through
the Internet, they simply called as web applications.
Client-Server applications:-
Web applications need to become more dynamic because the Internet
expanded from government and universities to business and individuals.
Dynamic web applications enable the user to interact with the
application in ways that change the appearance or content of webpage.
110
I MSc CS .Net Programming
Unfortunately, we cannot create dynamic web applications using HTML
alone. It need to use many different technologies such as client/server-side
scripting and server-side programming with HTML to create dynamic Web
applications.
Major limitations of client-side scripting are browser dependency and
security because client-side scripts are executed via browsers.
Server-side programs allow creating dynamic Web applications that can
process a form or manage a database.
we can create a secure Web site with server based applications because
the programs run on the Web server.
Processing [Link] Applications
A basic Web page created with [Link] is referred to as a Web form.
Web forms allow quickly developing and processing forms on Web pages
and develop cross-browser Web applications.
Web forms are web pages identified with the file extension .aspx.
When we build the application, any server programming code is
compiled on the server.
The following figure depicts how [Link] Web pages are processed on
the Web server.
Processing an [Link] application
The developer creates the web page(1) which is stored on the web server,
Programming code can be precompiled into the assembly(2).
The assembly contains a language and computer independent
representation of code called the Microsoft Intermediate Language (MSIL).
When the visitor first requests a page (3), the [Link] engine
dynamically compiles the assembly (4) and on subsequent request the page is
translated into computer specific instructions (5) with the output sent back to
the browser.
111
I MSc CS .Net Programming
Each application directory in web application is compiled into a single
file called an assembly.
Server Control:-
Toolbox is used to group the controls logically into tabs according to
their common functions.
[Link] provides a way to use server controls.
Server controls are objects on the web server built from classes that
were installed when installed the .NET Framework.
These server controls such as HTML controls and [Link] controls can
be used only within [Link] pages.
An object is a set of related methods and properties.
Properties are used to set the value of a variable defined within object.
It is difficult for server to retain the value and properties of the HTML
tags with HTML alone. So with server control the state of the server controls
can be maintained using [Link].
Server controls on the Standard tab in Toolbox:-
Pointer Hyperlink Table
Label Dropdownlist RadioButton
Textbox ListBox BulletedList
Button CheckBox Hiddenfield
LinkButton Image
ImageButton ImageMap
These server controls generate the necessary HTML tag, JavaScript and
Dynamic HTML (DHTML) which are supported by the client.
DHTML allows interacting with user when they complete a form or click
a hyperlink.
HTML Tags and HTML Controls
HTML controls are similar to HTML tags, expect that they are
programmable by the server.
In a traditional HTML page the developer creates a text box by writing
<input id=“Text1” type=“text”>.
HTML tags are sent unaltered to the browser. Only need to add
runat=“server” to the tag to transform the HTML tag into an HTML control.
Ex: <input id=“Text1” type=“text” runat=“server”/>
112
I MSc CS .Net Programming
When the value of the runat property is set to server, the control is
processed by the server.
We can create server-side programs that interact with the control before
rendered as a plain HTML tag and sent to the browser by transforming HTML
tags to HTML controls.
When we refer to the HTML control in code, we need to set the runat
property. If we have not set the runat property, the compiler displays an error
message that the control is not declared.
Runat property is not able to set by using the property window. Instead
runat proerty is set by using source code or in Design view right click the tag
and then click Run As Server Control.
All HTML control inherit from the same class in the .NET Framework
named [Link](called the HTML control class) which is
located in the [Link] namespace in [Link].
Web Controls:-
Web controls allow rendering HTML output and providing more
flexibility than HTML controls.
Web controls will create the HTML tags that are sent to the browser.
Web controls are usually identified with the prefix asp: followed by the
name of the control.
Ex: the code to create a button control is
<asp:Button ID =“Button1” runat=“server” Text=“Show the msg”/>.
Web controls have differnet properties than HTML control conterparts.
Web control can interact with client-side events such as the user
clicking a button. When the event occurs, the web control can trigger a script
to run on the server.
A web form inherits from the web Control class which is found in the
[Link] namespace.
Web controls similar to HTML Controls, but they support additional
properties, methods and events.
Creating webpage using a web Editor
Web Form is created in Web Editor, there are several options can be
configured.
Usually Web forms are created by inserting web controls, preview the
page in a browser and validate the HTML output.
113
I MSc CS .Net Programming
Steps to create a simple web form:-
1. Click File on the menu bar and click New File. The Add New Item
window opens. The Add New Item window displays templates.
2. Click Web Form in the Add New Item window.
3. In the Name textbox, highlight the existing content, type [Link]
and then click Add. The Web Form is added to the project and opens in the
main window in source code view.
[Link] the code
5. Click File on the menu bar and then click Save All
6. Click File on the menu bar and then click View in Browser.
7. Right click the page in the browser and click View Source.
8. Select all of the text in Source Code view. In notepad click Edit on the
menu bar and click Select All. Then click Edit on the menu bar click Copy.
9. Open a browser window, type [Link] in the address
text box, and press Enter. The Markup Validation Service Web page opens.
10. Scroll down to validate by Direct Input text box, right-click inside
the text box and click Paste then click Check button. The page is validated:
If the page valid then it displays “This page is Valid XHTML 1.0
Transitional!” else number of errors is displayed along with information about
error.
11. Close the browser and all opened files in Web editor.
Variables and Constants in a Web Form
Contents
• Basics of variable
• Declaration of variable
• Types of variable
• Naming variable
• Assigning values to Variables
• Declaring Constants
Basics of variable:-
Variables store data that can be retrieved at later.
For Example,
A variable might store a value that is to be used during a calculation.
Variable is a quantity that can be changed during execution time.
114
I MSc CS .Net Programming
Declaration of variable:-
A variable declaration consists of three parts,
» Declaration keyword
» Variable name
» Data type
Declaration keyword define what parts of the web application will have
access to the variable.
Variable name refers to the name of the variable.
The data type identifies what kind of data the variable can store.
When we declare a variable, the computer reserves the memory required
to store the variable.
Declaring variable is the process of reserving the memory space for the
variable before it is used in the program.
Types of variable:-
Local variables are defined within a procedure and can be used only by
the procedure in which they were declared.
Local variables are more readable, easier to maintain and require less
memory resources than module-level variables.
Module-level variables are defined in the class but outside of
procedures, and can be used by any of the procedure within the page.
Module-level variables are not available to other web Forms or other
classes within the application.
If Dim is used and the context is not specified, then the variable is
public by default.
The scope identifies what context of the application can access the variable.
Dim: Its use will mean the variable is public.
Public: This is used to declare a variable global or public.
Friend: This defines variables that are used only within the current web
application.
Protected: This defines variables that can be used only by the
procedure.
Examples:-
Dim qty, price As Integer
Dim strname, stremail As String
115
I MSc CS .Net Programming
Naming Variable:-
Rules to naming variable,
• Cannot use any of the commands or keywords as variable name.
• Variable names must begin with a letter.
• Cannot use a period or space within a variable name.
• Avoid using any special characters in a variable name except underscore
Assigning Values to Variables:-
We can store values in variables using assignment operator,
which is the equal sign (=).
Enter the name of the variable on the left side of the assignment
operator and enter the value on the right side of the assignment operator to
assign a value to variable.
Example:-
Dim name As String = “John”
(or)
Dim name As String
[Link] = “John”
Declaring Constants:-
Constants are used when we want to assign a value that does not
change.
The Const keyword is used to declare a constant.
The naming rules for variables are also applied to constants.
The name constants are usually all uppercase and need to assign the
value to the constant when it deaclared.
Ex: Const TAXRATE As Integer = 6
Working with Web Objects to Store Data
HTTP is one of the protocols used to send and retrieve data over the
Internet.
Data is transmitted in the header with each request from the browser
and response from the Web server.
The header is the portion of a data packet that describe how and where
to send the file.
The header includes the date and time, type of request, page requested
and HTTP version.
The user agent can be used to identify the client software.
116
I MSc CS .Net Programming
Web objects are,
Request Object
Response Object and
Session Object
Using the Request Object to Retrieve Data from Header:-
HTTP collects information and stores the values as a collection of server
variable.
The Request object of the page class allows to retrieve any data sent by
the browser, including the names and values of the form field and server
variable.
Server variables can be retrieved by using an HTTPRequest object with
[Link](“VARIABLE_NAME”). The server variable name is
always in uppercase.
The [Link] class is mapped directly to the request
property of the Page object. So instead of using server variable to retrieve the
header data use [Link] Name or [Link] Name.
The browser property of the page class can directly access the browser
application’s name and version without the user agent.
Example:-
Dim Mb as String = [Link] & “<br/>” & _
[Link] &”<br/>”& _
[Link] &”<br/>”& _
[Link]
Retrieving Data from a Form with Request Object:-
The form field names and values can be accessed from the header, the
Request object of the page class allows to access the values.
The Request object contains a Form collection and QueryString
collection that allows to retrieve form data from the header.
Enter [Link](“CompanyName”) to retrieve the value of a field
named CompanyName if the value of the form method identified in the HTML
Form element is Post.
If the value of the form method identified in the HTML Form element is
Get, then the form results are HTML encoded and appended with a question
mark to the URL requested as a single string called QueryString.
117
I MSc CS .Net Programming
The value of the CompanyName form field is retrieved and assigned to a
Label control using code as below,
[Link] = [Link](“CompanyName”)
Accessing Form Field Data:-
If processing server controls on the Web page, we can access the
value properties of the form field directly from web page code.
Use the name of the object and the property that stores its value
to retrieve the value of form field.
[Link]
We can assign a value to the form field such as
[Link] = “ABC Ltd”
Working with the Response Object:-
Page class also contains a Response object which is used to send
information to the browser.
The Response object is mapped to the [Link] class.
All data sent to browser is sent via HttpResponse class or via
Response object.
Response object has several methods to send content to the
browser such as,
• WriteFile method
• Write method
The WriteFile method allows to send the entire contents of a text file to
the Webpage.
The Write method allows to send a string to the browser.
Example
The code to write string to the webpage
[Link](“[Link]<br/>”)
We can use a variable to store the string,
Dim strmsg as String = “Welcome<br/>”
[Link](strmsg)
The Response object allows to redirect the browser to another
page using code as below,
[Link](“[Link]
Another method used to change to a new page is [Link]
118
I MSc CS .Net Programming
Example:-
[Link](“[Link]”,true)
Session Objects:-
User information can be tracked across user sessions and across the
entire application.
This information is retrieved from the properties of the Session object
such as SessionID, which is a unique identifier that identifies each session.
We can’t change the value of the SessionID property.
A special session cookie is used to maintain the session information.
When the session ends, the cookie is discarded.
If the user opens a new session, a new SessionID is issued. So a
SessionID can be used to track a user across a single session but not across
multiple sessions.
Code will retrieve the SessionID and the number of session variables
and extend the timeout to 30 minutes:
Session(“Session ID”) = [Link]
Session(“Number”) = [Link]
[Link] = “30”
The Session object is used to maintain session state across a single
user’s session.
Session variables are stored in the server’s memory and accessed only
within the session that declared and assigned the session variable.
When the session ends the session variables are released from memory.
The application variables are released from memory only when the web
application is stopped.
The following code store form field data, server variables and session data.
Session(“Member ID” = [Link]
Session(“Date of visit”)=[Link]
Session(“URL requested” = [Link].
Saving Data using Session Object:-
We can save state information in session variables and save a value in a
variable named Publisher in ViewState with:
ViewState(“Publisher”) = “ Course Tech”
119
I MSc CS .Net Programming
Request Object is used to retrieve information about the client and
server and session object to store data and to modify the timeout property and
ViewState content.
Clear the controls button will remove the session objects and changes in
the ViewState.
1. In the Solution Explorer window, right-click the *.aspx page and click
view code.
[Link] the Save All button
3. In the Solution Explorer window, right-click the *.aspx page and click
view in Browser.
[Link] Session variables in button then click Clear the Controls button.
[Link] the MemberID and Password textboxes, type admin and password
and click Event handler button.
6. In the MemberID and Password textboxes, type admin and password
and click _ViewState button. Click Clear the control button.
7. Close each of the open pages.
Designing .Net Web Applications
Web applications are different than Windows application because web
applications are used in a browser or an Internet-enabled device.
[Link] is used as the programming language for both types of
applications.
[Link] is the technology used to develop dynamic web applications
within the .NET Framework.
.NET framework consists of a CLR and a hierarchical set of base class
libraries.
Web Application Architecture:-
Programmers were trained to take advantage (hardware efficiency)
of a tiered hierarchical framework when designing the architecture for Web
applications.
One example of a tiered application would be to store the data on
a data server on a separate physical computer.
The application can still be designed with a tiered framework
where the presentation, business and data layers are separated.
120
I MSc CS .Net Programming
The Web Forms are used to display the data in a web page; the user
interface is the presentation layer of the application.
Assemblies contain the compiled code and can be stored on application
servers or with the individual applications.
Data can be stored in a variety of structures such as, text file, XML
document, database, or data server. This tier is also called the Data Access
Layer(DAL),
The Presentation tier contains the user interface
Middle tier is useful to create the business components to isolate the
programming logic.
The data tier consists of one or more data server such as SQL server.
Organization of classes in the .NET Framework:-
The base class libraries are groups of commonly used built-in classes
stored in executable files.
These classes can be accessed from any .NET applications. They contain
fundamental code structures and methods that allow to communicate with the
operating system software and other application.
The base class libraries are organized into hierarchical logical groupings
of code called namespaces.
The system namespace is at the top of the namespace hierarchy and
all built-in classes inherit from it.
121
I MSc CS .Net Programming
Programming with Visual Basic .NET
Decision control structures, Functions and procedures were used
to control the execution order of program.
These programming methods are stored in classes that can be
reused throughout web application.
Contents:-
• Creating a class in [Link]
• Using Procedure
• Creating a property method
• How web application interact with [Link]. Graphical
Class
• Using [Link]. Graphical Class
• Dynamically creating Server Controls
• Dynamically creating a Hyperlink Control
Creating a class in [Link]
[Link] application stores programming statements in classes.
In object-oriented programming, we create custom objects based on the
object definition, and then access the procedures and properties of the object
across multiple web pages.
The creation of an object consists of two separate tasks,
• Class definition: Class is not accessed directly; it is the code that will
be used to create the procedures and properties of the object. Once class
is defined, many objects are created based on the class definition.
• Instantiation: The class is the template for new object. When we create
an object that means really creating an instance of the class.
Instantiation is the process of declaring and initializing an object from a
class.
We can restrict which applications can have access to the class
using these additional keywords,
• Public: Can interact with other objects outside of the base class
• Private: can only be called within base class
• Protected: Can be called within base class and within subclass.
• Friend: Can be called anywhere from within same application
Code to create a class definition named Mycls in a web application
named GreenRiver web.
122
I MSc CS .Net Programming
Public Class Mycls
Private CompName As String =“GreenRiver”
If we want to use a class that is located in different file, it needs to
import a class into the web page and then create new objects using the class.
Ex:
Imports Mycls()
Here, use keyword Dim to declare a variable in which to store the object,
and New keyword to identify that this is an object based on class definition.
Ex:
Dim a As new GreenRiver [Link]()
After the object is created, it can access all of the variables, properties,
functions and procedures defined within Mycls.
Using a Procedure:-
Procedures are used to contain one or more programming statements.
Some programming statements are action statements.
Procedures are executed only when they are called by another procedure
or when event occurs.
The order in which procedures are declared does not affect the order of
their execution.
Procedures are always executed in the order in which they are called,
not the order in which they are created.
Two types of procedures,
Subprocedures(subroutines)
Functions
Creating subprocedures:-
A sub procedure is a procedure that can be called from other locations.
Each sub procedure can be reused without having to rewrite entire sections
of code.
Sub procedures do not return values and cannot be used in an
expression value.
Variables declared within procedure are local and available only to the
sub procedure.
When we create the sub procedure, declare it public or private.
The keyword public is used to explicitly declare the sub procedure
available to all other procedures in the application.
123
I MSc CS .Net Programming
While private sub procedures are only available to other sub procedures
in the context in which they declared.
Sub procedures are declared using the keyword Sub, and use End Sub
statement to stop the sub procedure.
Syntax:-
Sub subprocedurename (parameter1 As type1, parameter2 As type2)
Statements
End Sub
Example:
Sub Emp(EName As String, Eno As Integer)
Statements
End Sub
The sub procedures are executed in the order they are called by
specifying the name of the sub procedure or using the keyword Call and
passing any parameter required.
[call] Emp(“Joe”, 304)
Creating Event Procedures:-
An event procedure is a type of sub procedure that is attached to an
object with events.
Event procedure is not executed until triggered an event. The event
procedure is the code that will execute when the event handler occurs such as
button click.
The event procedure is not called but rather is triggered.
Event procedure name is based on the name of the object and event
name. An underscore (_) is used to separate the object name and event name.
Ex: btnExit_Click
When an event such as button click occurs in the browser, the client
side script passes the name of event procedure and parameter to the server.
The Sender As Object parameter identifies the object in the page that
initiated the event.
The EventArg represented as an e, is the parameter that was send with
the object.
Syntax:-
Sub ObjectName_event(Sender As Object, e As EventArgs)
statements
End Sub
124
I MSc CS .Net Programming
Example:-
Sub btnExit_Click(Sender As Object, e As EventArgs)
End
End Sub
Creating Functions:-
A function is a block of code that is grouped into named unit. There are
hundreds of built-in functions available within the .NET framework including
mathematical, date and time, string and formatting functions.
The function declaration is identified by a unique name and declares as
public, private, protected or friend before the Function keyword.
The End Function statement is used to identify the end of the function.
Function returns the value by using Return statement.
Ex:-
Public Function Getdiscount( cstate As String) As Integer
Dim Discount As Integer
if cstate=“TN” then
Discount =10
else
Discount = 5
End if
Return Discount
End Function
Creating a property Method:-
A property method sets the value of a variable defined within an object
and is often used to expose private variables that are defined within the class.
Some properties are assigned to the object by default within the object
definition.
If an object does not assign a value to a property and a new object is
created without assigning a value to the property, the property is assigned the
default value “undefined”.
We need to use the property method to use an instance variable from a
different class and also to make the instance variable available to code outside
of the class.
The following Code shows a property is defined within a class,
Public Readonly Property StoreName( ) As String
Get
Return StoreName
End Get
End Property
125
I MSc CS .Net Programming
Using a Property to Retrieve and Set the value of a variable:-
The property method retrieves the value of the internal instance variable
named StoreName.
Property method store the value of the variable, the internal variable is
not exposed outside of the class.
Property method is used to retrieve and set the value of the variables.
Ex:-
Public Class sample
Private StoreName As String = “ Green River”
Public Property NewStoreName( ) As String
Get
Return StoreName
End Get
Set (ByVal NewValue As String)
NewStoreName = NewValue
End Set
End Property
End Class
Using the Object Browser to view classes, properties and Methods:-
The Object Browser can be used to display the classes, properties, and
methods built into the namespaces within the .NET Framework.
Web Applications using the [Link] Class:-
Windows programmers are used to working with the
[Link] class, which is referred to as the GDI+ or simply
the Graphics class.
We can create visual objects such as lines and shapes such as rectangle
and ellipse, paint the background, and build custom objects with the Graphics
class.
The application drawing objects are first created in memory bitmap
using Bitmap class.
Then it needs to define a graphic object using the From File method of
the [Link] which acts drawing board.
Many Classes that used to display content in the graphic:-
DrawString class is used to draw text to the bitmap.
FillRectangle method is used to create rectangles and squares.
126
I MSc CS .Net Programming
FillPolygon method is used to create polygon shapes such as triangles,
trapezoids.
Point class is used to create and connect individual points within the
polygon.
FillEllipse method can be used to create circles and ovals.
Font class can be used to set the font type and size for a text message.
Brushes enumerator is used to change the color of the brushes.
Pen class is used to draw different styles of pens using the LineCap and
LineStyle properties.
LineCap property indicates how to start and end the line.
DashStyle properties is used to alter the line style can be Solid, Dash,
Dot, DashDot or custom.
SmoothingMode property can be set which will smooth any curves.
DrawString class actually draws the graphic into the bitmap.
Dispose method closes the image and releases the memory.
Dynamically Creating Server Controls:-
Placeholder control is used as a container to store dynamically added
server controls.
This control does not produce any visible output without the use of
other control.
The placeholder control is created with the code,
<asp:PlaceHolder ID=“PlaceHolder ID” runat =“server”>
</asp:PlaceHolder>
Panel control can contain other controls and creates a DIV tag to
enclose the content.
Literal control is used to write content directly to the page.
Hyperlink control is used to create an anchor tag that can link to
another page or target by using the ImageURL property
Dynamically creating a hyperlink control:-
Create a Hyperlink control dynamically and add it to the Placeholder
control. The literal control is used to send HTML line break tags to the
browser.
Placeholder control is created within a Panel control.
127
I MSc CS .Net Programming
Code for dynamically creating Hyperlink control.
Dim a As new hyperlink
[Link](a)
[Link]=“click”
[Link] = “images/[Link]”
Advanced Web Controls
Advanced web controls are used to create XML-based rotating banner
ads, display an interactive calendar and upload files from a web page.
Advanced web controls are,
ADROTATOR CONTROL
CALENDAR CONTROL
FILEUPLOAD CONTROL
ADROTATOR CONTROL
AdRotator control allows to display a banner ad on a web page. When we
refresh the page, the banner ad is changed to another image.
The AdRotator control is created from the
[Link] namespace.
The advertisement file is an XML document that stores the ad
information. This file is also known as the rotation file because it includes
the information about the rotating ads.
The banner ad is a hyperlinked image.
Role of the Advertisement File:-
The information used to create the banner ad is an external file called
advertisement file. This is an example of an XML document.
The advertisement file contains information that creates the HTML
image tag, which inserts the image in the web page and also contains
information that creates the hyperlink using an anchor tag.
When we click the banner ad, redirected to the URL defined within
hyperlink.
Image source and URL for the hyperlink are defined within the
advertisement file. Each time the page is displayed, AdRotator class retrieves a
different image and hyperlink from the advertisement file.
The first line of advertisement file indicates the version of the XML
document.
Ex: <?xml version =“1.0” encoding =“utf-4” ?>
128
I MSc CS .Net Programming
The rest of the file is contained within a root node named
Advertisements. In XML document, all tags must be nested within root node.
The root tag in an XML document is also known as root node which
contained within the Advertisement node are one or more Ad elements.
The Ad elements contain the individual properties for the ad.
Each ad contains several properties that used to create the image and
hyperlink tags within web page.
• ImageUrl element identifies the absolute or relative location of the
[Link] images in the JPEG, GIF, PNG formats are currently
supported on most browsers.
• NavigateUrl element identifies the URL to which the browser will be
directed when user clicks on the image.
NavigateUrl is used to create the href property in the hyperlink and is
also known as terget page or destination page.
• AlternateText element identifies the text that is displayed when the
user places the mouse icon over the image.
• Height and Weight property allows defining the ad dimension the
advertisement file is an XML file so the elements and properties within
file are case sensitive.
Properties with no corresponding HTML Function:-
There are two properties that do not have a corresponding HTML
function.
Impressions element is used to indicate the frequency with which the
banner ad is displayed.
AdRotator class selects a banner ad from the XML file based upon the
Impression property.
Keyword element is used in the advertisement file to indicate one or
more words that categorize the banner ads. The AdRotator class uses
the keyword to group the banner ads.
Sample code to display two banner ads,
<?xml version=“1.0” encoding=“sam” ?>
<Advertisements>
<Ad>
<ImageUrl>[Link]</ImageUrl>
<NavigateUrl>[Link]
129
I MSc CS .Net Programming
<AlternateText> Course </AlternateText>
<Impressions>60</Impressions>
<Keyword>Books</keyword>
</Ad>
<Ad>
<ImageUrl>[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText> Microsoft </AlternateText>
<Impressions>40</Impressions>
<Keyword>Software</keyword>
</Ad>
</Advertisements>
Properties of the AdRotator Control
o Height and Width property define the height and width of the
image that will be displayed.
o Style property is used to configure the styles for the AdRotator
control such as BorderColor, BorderWidth, BorderStyle, Visible,
TabIndex and Absolute positioning.
o Target property is used to open the new URL in a different
window.
o KeywordFilter property retrieves only those banner ads from
XML document whose keyword matches exactly.
o ToolTip property is used to provide more information about the
banner ad.
o DataMember and DataSource properties are used to identify
which data table to map to the AdRotator control.
Inserting the AdRotator Control into a Web Page:-
• Insert the banner ad control which is called AdRotator control to insert
the banner ad in the Web Page.
• This control is identified with the prefix asp and a colon because this is
a web control.
• In the AdRotator control, we must set the runat property to server to
indicate that the control is a server control and also must configure the
AdvertisementFile property to point the location of the advertisement
file.
130
I MSc CS .Net Programming
• We can insert the AdRotator control manually by entering code or drag
and drop the AdRotator control from the toolbox. If we use latter, we
need to configure the properties for the AdRotator control using property
window.
CALENDAR CONTROL
Calendar control is used to insert and configure an interactive calendar
within the web page.
Calendar control is useful for allowing a user to select dates for plane, hotel
and conference reservations.
Calendar control can also be used to display event data such as location and
time of event and to help project managers to keep track of the project
timelines.
This control is created by calendar class.
Thecalendarclassis [Link].
The calendar displays a single calendar month. By default the current
month of web server is the month that is displayed.
• We can configure the appearance of the calendar by setting the
properties of the calendar control.
• In Visual [Link], we can directly insert the calendar control in the
HTML code or drag and drop the control from the web forms tab in the
tool box.
• The name of the control includes the prefix asp followed by the word
calendar.
• The runat property must be assigned to server and assign a value to the
ID property.
Ex:
<asp:Calendar id =“mycal” runat =“server” />
Properties, Methods and Events:-
The calendar controls supports several style properties that can
configure when the control is inserted.
The property of the control is also changed dynamically in the code.
Most of the style properties can modify the background color, text color,
font face, size and style, alignment, width, height and border style etc.
We can also assign a style using a class defined in the CSS(Cascading
Style Sheet)Class property.
131
I MSc CS .Net Programming
Various Calendar control style properties:-
o DayHeaderStyle: sets the style for the days of the week.
o DayStyle: sets the style for individual dates.
o NextPrevStyle: sets the style for navigation control in the
heading.
o OtherMonthDayStyle: Sets the style for dates that are not in the
current month.
o SelectedDayStyle: sets the style for the dates that are selected.
o Titlestyle: sets the style for the title in the heading.
o TodayDayStyle: sets the style for the current date.
o WeekendDayStyle: sets the style for weekend dates.
132
I MSc CS .Net Programming
UNIT – V
C# PROGRAMMING
Evolutions of C# and .NET
Machine Language:-
In the 1940s, programmers toggle switches on the front of computer to
enter programs and data into memory. That is how programming began. When
they moved to punching binary codes 0s and 1s on cards reading cards into
memory. It could not better and coding was very tedious and prone to error.
Assembly Language:-
In the 1950s, assembly languages replaced the binary notation by using
mnemonic symbols to represent the instructions for computer.
Assembly language was designed to make the programmer’s job easier
using mnemonic symbols.
But, In Assembly Language statements to perform same task is differed
from computer to computer.
Assembly language still considered as low-level programming language.
These instructions are not easy to read and understand. They are not close to
English Language.
High-level Programming Languages:-
High-level languages came into existence in the late 1950s with
FORTRAN(Formula Translator) and later COBOL (Common Business Oriented
Language).
These languages were considered as High-level because they were
designed to be accessible to humans and easy to read, write and understand
and close to English.
Over the years more than 2000 high-level languages have came into
existence some of them only still widely BCPL and B in 1973.
Dennis Ritchie is credited with developing the C programming language;
Bjarne Stroustrup at Bell Labs is considered as father of C++ for his work in
early 1980s.
C++ includes features that enabled programmers to perform Object-
Oriented Programming. C++ is used heavily in the computer industry today.
Visual Basic Introduced in 1991, derived from the
BASIC(Beginners All Purpose Symbolic Code) programming language which
developed in 1960s.
133
I MSc CS .Net Programming
The earlier version of Visual Basic did not facilitate development using
an object-oriented approach but it facilitate easy creation of window-based
graphical user interfaces(GUI) for this VB has been used for great deal of
application development.
Java was introduced in 1995 and was originally called Oak. It was
designed for intelligent consumer-electronic devices and it heavily used for
Web applications because of nature of byte code which enable Machine
independent language this facilitates development of code that runs on many
types of computer.
C# is a new Computer programming language developed by Microsoft
Corporation.
C# is a fully object oriented language and is the first Component
oriented language.
It has been designed to support the key features of .NET Framework.
It is a simple, efficient, productive and type-safe language derived from
the popular C and C++ language.
It has the rapid graphical user interface(GUI) features of previous
version of VB, the added power of C++ and object oriented class libraries
similar to Java.
C# can be used to develop any type of software components including,
Mobile applications
Dynamic Web pages
Database access components
Window desktop applications
Web services and
Console-based applications.
C# is designed for building robust, reliable and durable components to
handle real-world applications.
Major highlights of C#
It is a brand new language derived from C/C++ family
It simplifies and modernizes C++
It is the only component oriented language available today
It is the only language designed for the .NET framework
It combines the best features of many commonly used language: the
productivity of VB, the power of C++ and the elegance of Java
It has consistent syntax
It embodies today’s concern for simplicity, productivity and robustness
Major parts of .NET framework are actually coded in C#
134
I MSc CS .Net Programming
.NET
.NET is an environment in which programs designed and run to be a
new programming paradigm.
It provides a Platform for developing and running code that is easy to
use.
Microsoft stated that the vision for .NET was to provide a new
programming platform and a set of development tools with intent to be able to
build distributed component based applications.
In February 2002 Microsoft finally released the first version of Visual
Studio, the IDE for developing C# applications.
[Link], Visual C++.NET, Visual J#.NET, [Link] and C# .NET all use
this same development environment.
Visual Studio is tools for typing program statement, compiling,
executing and debugging applications.
Features of .NET:-
Multilanguage independent: .NET supports development using a
number of programming languages: VB, C#, J#, C++. All the code from
each of the languages can compile to the common Microsoft
Intermediate Language (IL).
New Framework base classes: The .NET Framework has a class library,
which provides a very large collection of over 2500 reusable types
(classes) available to any .NET language.
Dynamic Web pages and Services: .NET was written the Internet in
mind. Thus, deploying applications over intranet or internet using a new
technology [Link].
Scalable component development: Segments of codes are extended ,
stored independently, combined and reused in many applications.
Robust: Build applications those are strong.
Why C#
C# was the language created for .NET and was designed from scratch to
work with .NET.
A large number of classes were included as part of .NET. These classes
or templates were designed for reuse by any of the .NET supported languages.
They reduce amount of programming that need to be done. These classes are
called .NET Framework classes. Most of the .NET Framework classes were
written using C# programming language.
135
I MSc CS .Net Programming
C# offers an exciting vehicle to incorporate and use emerging web
standards such as HTML, XML and SOAP.
C# was designed with the Internet in mind.
C and C++ has been the two popular and most widely used languages in
the software industry for the past two decades. They provide programmers
with a tremendous amount of power and control for developing scientific,
commercial and business applications.
These languages suffer from problems are,
High complexity of language
Long cycle-time
They are not suitable for working with new web technologies
They have poor type-safety
They do not support versioning
Low productivity
Poor Interoperability
They are weak in consistency
Poor support for component programming
Visual Basic, a language promoted by Microsoft for overcoming these
problems also could not meet some of the requirements of WWW, because VB
is not truly an object oriented programming language.
Java, a language derived from C/C++ family, is a true object-oriented
language has been widely used for web applications. Unfortunately, Java has
not retained some powerful C++ features such as Operator Overloading. It also
lacks interoperability.
So Microsoft attempted to transform Java and make it a language of
choices for their proposed new generation .NET platform.
Therefore, Microsoft decided to design a new language, that the result is
C# a simple, modern object-oriented language directly address the needs of
component based software development.
C# provides an easy way to create graphical user interfaces through
using Visual Studio IDE and .NET Framework.
All of the looping and selection programming constructs are included
from C and C++.
C# enables developers to make their packages available over the Internet
using many common features found only in Java.
136
I MSc CS .Net Programming
Elements of a C# program
The Program statements make up of the smallest functional programs that
can be developed using C#, they include all the major components found in
most programs.
Comments
Using Directives
Namespace
Class definition
Main Method
Method Body
Braces
Output Line
Comments:-
Comments play a very important role in the maintenance of programs.
They are used to enhance readability and understanding of code.
Comments are also used to document the purpose of different sections
of code.
Comments place anywhere in the program.
C# permits two types of comments, namely
» Single-line comments
» Multi-line comments
Single line comments:-
It begin with a double slash (//) symbol and terminate at the end of the
line. Everything after the // on a line is considered as comments.
Ex: using System // System is a namespace
Multi line comments:-
This comment starts with the /* characters and terminates with */ and
mainly used for longer comments.
Ex: /* using
system
namespace */
Using Directive:-
This directive is used to avoid prefixing of [Link] to the method
WriteLine().
System is a namespace and Console is a class. The using directive can
be applied only to namespaces and cannot be applied to classes.
137
I MSc CS .Net Programming
For example
using System; // legal
Class Sample
{
Public static void Main()
{
[Link](“Hello”);
}
}
using [Link]// illegal
We can overcome this problem by using aliases for namespace
classes. It takes the form:
using alias-name = class-name;
Example:-
using A = [Link] // A is alias for [Link]
class Sample
{
Public static void Main()
{
[Link](“Hello”);
}
}
By typing the using-namespace-directive, all the types contained in the
given namespace are imported.
Namespaces:-
System is a namespace (scope) in which the Console class is located.
A class in a namespace cab be accessed using the dot(.) operator.
C# supports a feature known as using directive that can be used to
import the namespace System into the program.
Once namespace is imported, we can use the elements of that
namespace without using the namespace as prefix.
Example
using System; // importing namespace
138
I MSc CS .Net Programming
Class Definition:-
Class is declared using follwing form,
class class-name
class HelloWorld // declaration of class
C# is object-oriented language, everything in C# is designed around a
class, which is the building block of an object oriented program.
C# doesn’t allow anything to be defined outside of a class, everything
must be placed inside a class.
Class is a keyword and declares that a new class definition follows,
HelloWorld is a identifier that specifies the name of the class to be defined.
Class definition must be enclosed within curly braces. Within braces we
can define class members.
Class member may be.
» Data member, which contains value associated with the state of class.
» Member method, which perform some behavior of the class.
Main() Methd:-
Main() method play a important role in C# and this is the “entry point”
for all application.
Main method is where the program begins execution and it can be
placed anywhere inside the class definition.
This line contains a number of keywords: public, static and void
Purpose of keywords:
public: The keyword public is an access modifier.
static: The keyword static declares the Main method is a global one and
can be called without creating an instance of the class.
void : It states the Main method does not return any value.
Method Body:-
The body of Main ( ) method consists of statements of program.
Example: {
[Link](“Welcome To C#”);
}
Braces:-
C# is a block structured language ie code blocks are always enclosed by
braces{}. Therefore every class definition in C# begins with an opening brace ‘{‘
and ends with a closing brace ‘}’.
139
I MSc CS .Net Programming
Output Line:-
The only executable statement in the program is
[Link](“ C# is sharper than C++”);
The WriteLine method is a static method of the Console class which
located in the namespace System.
This line print the string : C# is sharper than C++
Arrays and Collections
Contents
• Array Basics
• One-dimensional Arrays
• Creating an Array
• Array Declaration
• Creating memory locations
• Initialization of Array
• Two-dimensional Array
• Multidimensional Array
• Array class
• Arraylist class
Array Basics:-
An array is a group of contiguous or related data items that share a
common name.
For Example,
marks[10] represents 10 marks of student.
The individual values(variables) in array are called Array elements and
array can be of any variable type.
An array is a data structure that may contain any number of variable.
Elements of array are accessed through an index or subscript.
The index references the location of the variable relative to
the first element in the array. The elements in the array are also called
subscripted or indexed variables.
One-dimensional Array:-
An array with only one subscript is called one-dimensional array.
For example,
if we want to represent a set of five numbers like 34,10,23,20,50
by an array variable number declare as follows
int [ ] number = new int[5]
140
I MSc CS .Net Programming
The values to the array elements can be assigned as follows:
number[0] = 34
number[1] = 10
number[2] = 23
number[3] = 20
number[4] = 50
Creating an array:-
Like variables, arrays must be declared and created in the
computer memory before they are used.
Creation of array involves three steps:
1. Declaring the array
2. Creating memory location
3. Putting values into the memory locations.
Declaration of Arrays:-
Arrays in C# are declared as follows:
Syntax: type[ ] arrayname;
Examples:
int [ ] counter; // declare int array reference
float [ ] avg; //declare float array reference
int [ ] x,y;//declare two int array reference
Remember, do not enter the size of the arrays in the declaration.
Creation of Arrays:-
After declaring an array, we need to create it in the memory.
C# allows to create arrays using new operator,
Syntax: arrayname = new type [size];
Examples:
number = new int[5];
avg = new float[10];
The variables number refers to an array of five integers and avg
refers to an array of ten floating-point values.
It is also possible to combine the two steps, declaration and
creation into one,
int [ ] number new int[5];
Initialization of Arrays:-
The final step is to put values into the array created. This process is
known as initialization. This is done using the array subscripts,
Syntax: arrayname[subscript] = value;
141
I MSc CS .Net Programming
Examples:-
number[0] = 56;
number[1] = 30;
int [ ] number = { 3, 5,2,6,7 };
It is also possible to assign an array object to another.
int [ ] a = { 1,4,6};
int [ ] b;
b = a;
Program for sorting a list of numbers
using System;
class sorting
{
public static void Main( )
{
int [ ] n = { 50, 40, 80, 65, 70 };
int n1 = [Link];
[Link](“Given list: “);
for (int i = 0; i<n1; i++)
{
[Link](“ “ + n[i]);
}
[Link](“\n”);
for (int i = 0; i<n1 ; i++)
{
for(int j= i+1; j<n1; j++)
{
if(n[i]<n[j])
{
int t = n[i];
n[i] = [j];
n[j] = t;
}
}
}
[Link](“Sorted list: “);
for(int i=0; i<n1; i++)
{
[Link](“ “ + n[i]);
}
[Link](“ “);
}
}
142
I MSc CS .Net Programming
Two-dimensional Array:-
An array with two dimensions is called two-dimensional array.
Two kinds of two-dimensional array can be created using C#,
• Rectangular Array
• Jagged Array
Rectangular Array:-
Rectangular 2-D array is usually visualized as a table divided into rows
and columns. Data is stored in individual cells.
Format for creating 2-D array,
type[ , ] identifier = new type [integral value, integral value];
All data values placed in a two-dimensional array must be of the same
base type.
Two integral values are required for a two-dimensional array. These
values specify the number of rows and columns for allocating storage to be
referenced by the identifier name.
Example:-
int[ , ] a;
a=new int[3,4];
or
int[,]a=new int[3,4];
This creates a table that can store twelve integer values.
Jagged Array(or)variable-size array:-
C# treats multidimensional arrays as ‘arrays of arrays’. One row might
have five columns; another row 50 columns.
Example:-
int [ ] [ ] x = new int [3] [ ];
x[0] = new int [2];
x[1] = new int [4];
x[2] = new int [3];
Multidimensional Array:-
An array with more than two index.
Format for creating a 3-D array is:
type[ , , ] identifier = new type[ integral value, integral value,
integral value];
143
I MSc CS .Net Programming
Example:-
int[ , ,]c = new int [4, 7, 3];
Program for counting calories:
using;
namespace caloriecounter
{
class caloriecounter
{
static void Main( )
{
int [ , ,] cal ={ { { 120, 110, 100 }
{ 300, 200, 100}
{ 150, 220, 180}
{ 110, 250, 101}
{ 300, 200, 100}
{140, 230, 150}
{160, 210, 105} },
{ { 170, 100, 190 }
{ 310, 220, 120}
{ 120, 220, 180}
{ 110, 250, 101}
{ 330, 250, 100}
{160, 250, 150}
{160, 240, 105} },
{ { 100, 140, 180 }
{ 350, 200, 100}
{ 150, 220, 180}
{ 130, 250, 101}
{ 400, 210, 100}
{150, 200, 150}
{100, 250, 100} },
{ { 420, 110, 200 }
{ 500, 200, 110}
{ 100, 200, 150}
{ 140, 150, 150}
{ 100, 210, 140}
{150, 200, 150}
{160, 200, 140} } }
Accumulatecalorie(cal);
displaytot(cal);
}
public static void Accumulatecalorie(int [ , , ]cal
{
for(int wk =0; wk<[Link](0);wk++)
for(int da=0;da<[Link](1);da++)
144
I MSc CS .Net Programming
for(int m1=0;m1<[Link](2);m1++)
cal[wk, da,3]+=cal[wk,da, m1];
}
public static void displaytot(int[ , ,]cal)
{
string [ ]dayName = {“Sun”, “Mon”, “Tue”,
“Wed”, “Thr”, “Fri”,
“Sat”);
[Link](“Week#\tDat#\tTotalcalories”);
for(int wk=0;wk<[Link](0);wk++)
for(int da=0;da<[Link](1);da++)
[Link](“{0}\t{1}\t{2}”, wk+1, dayName[da],
cal[wk, da, 3]);
}
}
}
Output:-
Week# Day# TotalCalories
1 Sun 340
1 Mon 600
1 Tue 550
1 Wed 460
1 Thr 600
1 Fri 520
1 Sat 475
2 Sun 460
2 Mon 650
2 Tue 520
2 Wed 461
2 Thr 680
2 Fri 560
2 Sat 505
3 Sun 320
3 Mon 650
3 Tue 550
3 Wed 481
3 Thr 710
3 Fri 500
3 Sat 450
4 Sun 730
4 Mon 810
4 Tue 450
4 Wed 441
4 Thr 450
4 Fri 500
4 Sat 500
145
I MSc CS .Net Programming
Array Class:-
In C#, Every array we create is automatically derived from the
[Link] class.
Array class defines a number of methods and properties that can
be used to manipulate arrays more efficiently.
Some commonly used methods of [Link] class
Clear( ) –Sets the range of elements to empty values
CopyTo( ) – Copies elements from the source array into the
destination array
GetLength( ) – Gives number of elements in a given
dimension of array
GetValue( ) – Gets the value for a given index in the array.
Length – Gives the length of array
SetValue( ) – Sets the value for a given index in the array
Reserve( ) – Reserves the contents of one-dimensional array
Sort( ) – Sorts the elements in a one-dimensional array
Sorting and reversing an array:-
using System;
class SR
{
public static void Main( )
{
int [ ]x = {30,10,80,90,20};
[Link](“Array before Sorting”);
foreach(int i in x)
[Link](“ “ + i);
[Link]();
[Link](x);
[Link](“ Array after Sorting”);
foreach(int i in x)
[Link](“ “+i);
[Link]( );
[Link](x);
[Link](“ Array after Sorting”);
foreach(int i in x)
[Link](“ “+i);
}
}
146
I MSc CS .Net Programming
Arraylist class:-
[Link] namespace defines a class known as ArrayList that
can store a dynamically sized array of objects.
The ArrayList class includes a number of methods to support operations
such as Sorting, removing and enumerating its contents.
It also supports a Count property that gives the number of objects in an
array list and Capacity property is used to modify or read the capacity of
array.
ArrayList is very similar to an array except that it has the ability to
grow dynamically.
Creating an arraylist:-
ArrayList cities = new ArrayList (30);
It creates cities with a capacity to store thirty objects. If we do not
specify the size, it defaults to sixteen that is,
ArrayList cities = new ArrayList ( );
Important ArrayList Methods and properties:-
Add( ) – Adds an object to a list
Clear( ) – Removes all the elements from the list
Contains( ) – Determines if an element is in the list
CopyTo( ) – Copies a list to another
Insert( ) – Inserts an elements into list
Remove( ) – Removes the first occurrence of an element
RemoveAt( ) – Removes the elements at the specified place
RemoveRange( ) – Removes the range of elements
Sort( ) – Sort the element
Example program:-
using System;
using [Link];
class city
{
public static void Main( )
{
ArrayList n = new ArrayList( );
[Link](“Chennai”);
[Link](“Bombay”);
147
I MSc CS .Net Programming
[Link](“Delhi”);
[Link](“Trichy”);
[Link](“Capacity:”+[Link]);
[Link](“Elements:”+[Link]);
[Link]();
for(int i=0;i<[Link];i++)
{
[Link](n[i]);
}
[Link]();
[Link](2);
For(int i=0;i<[Link];i++)
{
[Link](n[i]);
}
}
}
Programming Based On Events
DELEGATES
In object-oriented programming, it is the usual practice for one object to
send messages to other objects. However, in real-life applications, it is quite
common for an object to report back to the object that was responsible for
sending a message. The methods used to call back messages are known as
callback method.
C# implements the callback technique in a much safer and object
oriented manner using a kind of object called delegate object.
Delegates form the foundation for events in C#.
Delegates are special type of object that contains the details of a method
rather than data.
Delegates in C# are used for two purposes:
Callback
Event handling
The dictionary meaning of delegate is “a person acting for another
person”. In C#, delegates mean method acting for another method.
148
I MSc CS .Net Programming
In C#, delegate is a class type object and is used to invoke a method
that has been encapsulated into it at the time of its creation.
Creating and using delegates involve four steps:-
* Delegate declaration
* Delegate method definition
* Delegate instantiation
* Delegate invocation
A delegate declaration defines a class using the class System. Delegate
as a base class.
The delegate instance holds the reference to delegate methods.
Delegate Declaration:-
A delegate declaration is a type declaration.
General Form:
Modifier delegate return-type delegate-name (parameter);
Delegate is the keyword that signifies that the declaration represents a
class type derived from System. Delegate.
The return-type indicates return type of the delegate.
Parameter identifies the signature of the delegate.
The delegate-name is any valid identifier.
The modifier controls the accessibility of the delegate. It is optional.
Delegate may take any of the following modifier,
New
public
protected
internal
private
The new modifier only permitted on delegates declared within another
type.
Example:-
delegate void Simpledelegate( );
public delegate int campareitems(int x, int y);
private delegate string getString( );
Delegate Methods:-
The methods whose references are encapsulated into a delegate instance
are known as delegate methods.
149
I MSc CS .Net Programming
One feature of delegates is that they are type-safe to ensure the
matching of signatures of delegate methods.
» What type of object the method is being called
» Whether the method is a static or an instance method.
For example, the delegate
delegate string GetString( )
can be made to refer to the method ToString using int object N.
GetString s1 = new GetString ([Link]);
The delegate
delegate void Delegate1( );
can encapsulate references to the following methods,
public void F1( ) // instance method
{
[Link](“F1”);
}
static public void F2( ) // static method
{
[Link](“F2”);
}
Similarly, the delegate
delegate double Mathop(double x, double y);
Can refer to any of the following methods,
public static double Multiply(double a, double b)
{
return (a*b);
}
public double Divide(double a, double b)
{
return (a/b);
}
The signature and return type of methods match the signature and
return type of the delegate.
Delegate Instantiation:-
C# provides a special syntax for instantiating their instances. A
delegate-creation-expression is used to create new instance of a delegate.
new delegate-type(expression)
150
I MSc CS .Net Programming
The delegate-type is name of delegate declared earlier whose object is to
created.
The expression must be a method name or valid delegate-type.
if it is a method name its signature and return type must be same as
those of the delegate.
if no matching exists, or more than one matching method exists an error
occurs.
The matching method may be either an instance or static method.
if it is an instance method, we need to specify the instance as well as the
name of the method.
if it is a static one, then it is enough to specify the class name and the
method name.
Example:-
delegate int ProductDelegate(int x , int y);
class delegate
{
static float Product(float a, float b) // signature does not match
{
return ( a*b);
}
static int Product(int a, int b) // signature matches
{
return ( a*b);
}
ProductDelegate p = new ProductDelegate(Product)
The delegate p is initialized with the reference to the second Product
method because that method exactly matches the signature and return type of
ProductDelegate.
Delegate Invocation:-
When a delegate is invoked, it in turn invokes the method whose
reference has been encapsulated into the delegate.
General Form:-
delegate_object(parameter list)
If the invocation invokes a method that returns void, the result is
nothing. So it cannot be used as an operand.
delegate1(x,y); // void delegate
151
I MSc CS .Net Programming
If the method returns a value, then it can be used as an operand of an
operator. We assign the return value to an appropriate variable for further
processing.
Ex: double result = delegate2(2.44, 4.6);
Using delegates:- Program for creating and implementing a delegate
using System;
delegate int Arithop(int x, int y); // delegate declaration
class mathop
{
public static int Add(int a, int b) // defintion of delegate
{ // method
return (a+b);
}
public static int Sub(int a, int b)
{
return (a-b);
}
}
Class Delegatetest
{
public static void Main( )
{ // delegate instances
Arithop op1 = new Arithop([Link]);
Arithop op2 = new Arithop([Link]);
// invoking delegates
int res1=op1(200,300);
int res2 = op2(200,100);
[Link](“Result1=“ +res1);
[Link](“Result2=“ +res2);
}
}
Event Handling in C#:-
An event is a delegate type class member that is used by object or class
to provide a notification to other objects that event has occurred.
The client object can act on an event by adding an event handler to the
event.
Events are declared using the simple event declaration format as
follows,
modifier event type event-name;
152
I MSc CS .Net Programming
The type of event declaration must be a delegate type and the delegate
must be accessible as the event itself.
event is a keyword that signifies that the event-name is an event.
Example of event declaration
public event Eventhandler Click;
public event Ratechange Rate;
Eventhandler and Ratechange are delegates and Click and Rate are
events.
Since events are based on delegates, we must first declare a delegate
and then declare an instance of the delegate using keyword event.
Implementing an event handler:-
using System;
public delegate void Edelegate(string str);
class Eventclass
{
public event Edelegate Status;
public void TriggerEvent( )
{
if(Status!=null)
Status (“ Event Triggered”);
}
}
event is a keyword that signifies that the event-name is an event.
Example of event declaration
public event Eventhandler Click;
public event Ratechange Rate;
Eventhandler and Ratechange are delegates and Click and Rate
are events.
Since events are based on delegates, we must first declare a
delegate and then declare an instance of the delegate using keyword event.
Implementing an event handler:-
using System;
public delegate void Edelegate(string str);
class Eventclass
{
153
I MSc CS .Net Programming
public event Edelegate Status;
public void TriggerEvent( )
{
if(Status!=null)
Status (“ Event Triggered”);
}
}
class EventTest
{
public static void Main( )
{
Eventclass ec = new Eventclass( );
EventTest et = new EventTest( );
[Link] +=new Edelegate([Link]);
[Link]( );
}
public void EventCatch(string str)
{
[Link](str);
}
}
154