Dot Net Complete Guide Bca
Dot Net Complete Guide Bca
Dot Net Complete Guide Bca
DOT NET
PROGRAMMING
(Compiled Notes)
Jeevan Poudel
BCA VIII, 2077
Purbanchal University, Nepal
Dot Net
Programming
(BCA453CO)
(Compiled Notes)
BCA-VIII
Jeevan Poudel
List of Figures ix
List of Tables xi
2 Language Basics 13
2.1 Variables and Data Types . . . . . . . . . . . . . . . . . . . . 13
2.1.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 String and String Builder . . . . . . . . . . . . . . . . . . . . 17
2.2.1 String . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.2 String Builder . . . . . . . . . . . . . . . . . . . . . . . 18
2.3 Boxing and Unboxing . . . . . . . . . . . . . . . . . . . . . . . 19
2.3.1 Boxing . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.3.2 UnBoxing . . . . . . . . . . . . . . . . . . . . . . . . . 20
v
vi
2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . 21
2.4.2 Relational Operators . . . . . . . . . . . . . . . . . . . 21
2.4.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . 22
2.4.4 Compound Assignment Operators . . . . . . . . . . . . 22
2.4.5 Ternary Operator . . . . . . . . . . . . . . . . . . . . . 23
2.5 Control statements . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.1 Conditional Statements . . . . . . . . . . . . . . . . . 24
2.5.2 C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.3 VB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.5.4 Iteration statements . . . . . . . . . . . . . . . . . . . 27
2.5.5 Jump statements . . . . . . . . . . . . . . . . . . . . . 28
2.6 Arrays and Strings . . . . . . . . . . . . . . . . . . . . . . . . 29
2.6.1 Array Declaration . . . . . . . . . . . . . . . . . . . . 29
2.6.2 Array Initialization . . . . . . . . . . . . . . . . . . . . 30
2.7 Procedure and Functions . . . . . . . . . . . . . . . . . . . . . 33
2.7.1 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.7.2 Function . . . . . . . . . . . . . . . . . . . . . . . . . . 35
References 155
LIST OF FIGURES
ix
LIST OF TABLES
xi
CHAPTER
1
2CHAPTER 1. OVERVIEW OF VB . NET AND C# . NET LANGUAGE
Language
WinForms, ASP.NET, ADO.NET
Library
Framework Class Library
CLR
Common Language Runtime
The . Net Framework Architecture is the programming model for the . Net
platform. It provides a managed execution environment, simplified develop-
ment and deployment and integration with a wide variety of programming
languages. The . Net Framework class library (FCL) is a comprehensive,
object-oriented collection of reusable types that you can use to develop appli-
cations. The common language runtime (CLR) is the core runtime engine for
executing applications in the . Net Framework. The CLR is fully protected
1.1. INTRODUCTION TO . NET FRAMEWORK 3
from the outside environment and highly optimized within, taking advantage
of the services that the CLR provides such as security, performance, deploy-
ment facilities, and memory management , including garbage collection.
1.1.1.3 Languages
The types of applications that can be built in the .Net framework is classified
broadly into the following categories
• ADO.Net – This technology is used to develop applications to interact
with Databases such as Oracle or Microsoft SQL Server: This is used
for developing Forms-based applications, which would run on an end
user machine. Notepad is an example of a client-based application.
• ASP.Net: This is used for developing web-based applications, which are
made to run on any browser.
• ADO.Net: This technology is used to develop applications to interact
with Databases such as Oracle or Microsoft SQL Server.
1
A namespace is a logical separation of methods.
4CHAPTER 1. OVERVIEW OF VB . NET AND C# . NET LANGUAGE
• During the compile time, the compiler convert the source code into
MSIL.
Managed Code
Managed Code in Microsoft . Net Framework, is the code that has executed
by the Common Language Runtime (CLR) environment. On the other hand
Unmanaged Code is directly executed by the computer’s CPU. Data types,
error-handling mechanisms, creation and destruction rules, and design guide-
lines vary between managed and unmanaged object models.
The benefits of Managed Code include programmers convenience and en-
hanced security. Managed code is designed to be more reliable and robust
than unmanaged code, examples are Garbage Collection, Type Safety etc.
The Managed Code running in a CLR cannot be accessed outside the run-
time environment as well as cannot call directly from outside the runtime
environment. This makes the programs more isolated and at the same time
computers are more secure. Unmanaged Code can bypass the . Net Frame-
work and make direct calls to the OS. Calling unmanaged code presents a
major security risk.
6CHAPTER 1. OVERVIEW OF VB . NET AND C# . NET LANGUAGE
The Managed Code running under a CLR cannot be accessed outside the
runtime environment as well as cannot call directly from outside the runtime
environment. It refers to a contract of cooperation between natively execut-
ing code and the runtime. It offers services like garbage collection, run-time
type checking, reference checking etc. By using managed code we can avoid
many typical programming mistakes that lead to security holes and unstable
applications, also, many unproductive programming tasks are automatically
taken care of, such as type safety checking, memory management, destruction
of unused objects etc.
Framework, including VB. Net, C#, J#, etc. Since Visual C++ can be com-
piled to either managed or unmanaged code it is possible to mix the two in
the same application.
Interoperability
Language interoperability is the ability of code to interact with code that
is written using a different programming language. It can help maximize
code reuse and, therefore, improve the efficiency of the development process.
The . NET components can communicate with the existing COM components
without migrating to those components into . NET. That means, this feature
is a great help to reduce the migration cost and time.
Portability
Applications built on the . Net framework can be made to work on any
Windows platform. And now in recent times, Microsoft is also envisioning to
make Microsoft products work on other platforms, such as iOS and Linux.
Security
The . NET Framework has a good security mechanism. The inbuilt security
mechanism helps in both validation and verification of applications. Every
application can explicitly define their security mechanism. Each security
mechanism is used to grant the user access to the code or to the running
program.
Language Independence
The . Net Framework is language independent. It is possible to use . Net
from many programming languages because they have all agreed on some
8CHAPTER 1. OVERVIEW OF VB . NET AND C# . NET LANGUAGE
Type safety
Type-Safety is enforced by the CLR and the Language Compiler — in accor-
dance to the CTS directives of the . Net Framework. Type-safe code cannot
perform an operation on an object that is invalid for that object. This pre-
vents ill-defined casts, wrong method invocations, and memory size issues
when accessing an object. For example, if you have declared a variable as an
integer, it cannot be assigned any value which is not an integer (by implicit
conversion, or explicit conversion).
Memory Management
The Common Language runtime does all the work or memory management.
The . Net framework has all the capability to see those resources, which
are not used by a running program. It would then release those resources
accordingly. This is done via a program called the “Garbage Collector”,
which runs as part of the . Net framework.
The garbage collector runs at regular intervals and keeps on checking
which system resources are not utilized, and frees them accordingly.
C# Features
• Simple
C# is a simple language in the sense that it provides structured ap-
proach (to break the problem into parts), rich set of library functions,
data types etc.
• Object-Oriented
C# is object-oriented programming language. OOPs makes develop-
ment and maintenance easier where as in Procedure-oriented program-
ming language it is not easy to manage if code grows as project size
grow.
• Type Safe
C# type safe code can only access the memory location that it has
permission to execute. Therefore it improves a security of the program.
• Interoperability
Interoperability process enables the C# programs to do almost anything
that a native C++ application can do.
• Rich Library
C# provides a lot of inbuilt functions that makes the development fast.
Featues of VB . Net
VB . NET comes loaded with numerous features that have made it a popular
programming language amongst programmers worldwide. These features
include the following
Class
Class is a collection of objects of similar type. Objects are variables of the
type class. Once a class has been defined, we can create any number of
objects belonging to that class. Classes are user define data types.
Dynamic Binding
Refers to linking of function call with function definition is called binding
and when it is take place at run time called dynamic binding.
Message Passing
The process by which one object can interact with other object is called
message passing.
12
CHAPTER 1. OVERVIEW OF VB . NET AND C# . NET LANGUAGE
Inheritance
It is the process by which object of a class acquire the properties or features
of objects of another class. The concept of inheritance provide the idea of
re-usability means we can add additional features to an existing class without
modifying it. This is possible by deriving a new class from the existing one.
The new class will have the combined features of both the classes.
Polymorphism
An operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. Its types:
LANGUAGE BASICS
13
14 CHAPTER 2. LANGUAGE BASICS
C# also allows defining other value types of variable such as enum and
reference types of variables such as class.
Variable Declaration in C#
Syntax for variable definition in C# is:
<data_type > <variable_list >;
Here, data_type must be a valid C# data type including char, int, float,
double, or any user-defined data type, and variable_list may consist of
one or more identifier names separated by commas.
Some valid variable definitions are shown here:
int i, j, k;
char c, ch;
float f, salary ;
double d;
Some valid variable declarations along with their definition are shown
here:
' VB
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1 , count2 As Integer
Dim status As Boolean
Dim exitButton As New System . Windows . Forms . Button
Dim lastTime , nextTime As Date
Variable Initialization
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is:
variable_name = value ;
2.1. VARIABLES AND DATA TYPES 15
' VB
DIM <variable_name > As <data_type > = value
' VB
Dim semesterID As Integer = 8
Dim teacherName As String = " Madan Uprety "
• A variable name can start with alphabet and underscore only. It can’t
start with a digit.
• A variable name must not be any reserved word or keyword e.g. char,
float etc.
Object Type In C#, all types, predefined and user-defined, reference types
and value types, inherit directly or indirectly from Object. So basically it is
the base class for all the data types. Before assigning values, it needs type
conversion. When a variable of a value type is converted to object, it’s called
boxing. When a variable of type object is converted to a value type, it’s
called unboxing. Its type name is System.Object.
Dynamic Type You can store any type of value in the dynamic data type
variable. Type checking for these types of variables takes place at run-time.
1 // Syntax
2 dynamic <variable_name > = value ;
3
4 // Example
5 dynamic d = 69;
Dynamic types are similar to object types except that type checking for
object type variables takes place at compile time, whereas that for the dy-
namic type variables takes place at run time.
2.2. STRING AND STRING BUILDER 17
Pointer Type
Pointer type variables store the memory address of another type. To get the
pointer details we have a two symbols: ampersand (&) and asterisk (*).
• ampersand (&): It is Known as Address Operator. It is used to deter-
mine the address of a variable.
• asterisk (*): It also known as Indirection Operator. It is used to access
the value of an address.
// Syntax
type* identifier ;
// Example
int* p1 , p; // Valid syntax
int *p1 , *p; // Invalid
The String class is defined in the .NET base class library. In other words
a String object is a sequential collection of System.Char objects which repre-
sents a string. The maximum size of String object in memory is 2GB or about
18 CHAPTER 2. LANGUAGE BASICS
In the above code, string color will alter 3 times, each time the code
perform a string operation (+=). That mean 3 new string created in the
memory. When you perform repeated operation to a string, the overhead
associated with creating a new String object can be costly.
1 // StringBuilder Example
2
3 StringBuilder sb = new StringBuilder ("");
4 sb. Append ("red");
5 sb. Append ("blue");
6 sb. Append (" green ");
7 string colors = sb. ToString ();
In the above code the StringBuilder object will alter 3 times, each time
the code attempt a StringBuilder operation without creating a new object.
2.3. BOXING AND UNBOXING 19
That means, using the StringBuilder class can boost performance when
concatenating many strings together in a loop.
But immutable objects have some advantages also, such as they can be
used across threads without fearing synchronization problems. On the other
hand, when initializing a StringBuilder, you are going down in performance.
Also many actions that you do with string can’t be done with StringBuilder
object.
String StringBuilder
2.3.1 Boxing
1 int Val = 1;
2 Object Obj = Val; // Boxing
The first line we created a Value Type Val and assigned a value to Val.
The second line, we created an instance of Object Obj and assign the value of
Val to Obj. From the above operation Object Obj = i we saw converting a
value of a Value Type into a value of a corresponding Reference Type. These
types of operation is called Boxing.
2.3.2 UnBoxing
1 int Val = 1;
2 Object Obj = Val; // Boxing
3 int i = (int)Obj; // Unboxing
The first two line shows how to Box a Value Type. The next line int
i = (int) Obj shows extracts the Value Type from the Object. That is
converting a value of a Reference Type into a value of a Value Type. This
operation is called UnBoxing.
Boxing and UnBoxing are computationally expensive processes. When a
value type is boxed, an entirely new object must be allocated and constructed,
also the cast required for UnBoxing is also expensive computationally.
Boxing Unboxing
2.4 Operators
An operator is a symbol that tells the compiler to perform specific mathe-
matical or logical manipulations. C# has rich set of built-in operators and
provides the following type of operators.
logical, and bitwise operators. Table 2.5 shows list of compound assignment
operators.
= x=6 x=6
+= x += 4 x=x+4
-= x -= 6 x=x-6
*= x *= 9 x=x*9
/= x /= 7 x=x/7
%= x%=2 x=x%2
// Example
int number = 18;
string result ;
control flow is provided to us by the use of control statements. These are the
special keywords in the C# language that allow the programmer to set up
things like branching, looping, and even entire jumps to new points in the
program during execution. Control statements:
• Selection Statements: This consists of if, else, switch, and case
branching
2.5.2 C#
if statement
The if statement selects a branch for execution based on the value of a
Boolean expression.
// C#
// Syntax : if statement
if ( condition ) {
// Statement (s)
} else {
// Statement (s)
}
switch statement
Switch statement can be used to branch the execution of a program to a
set of statements that are inside of a case label, which is created with the
2.5. CONTROL STATEMENTS 25
keyword case. The C# switch statement does this by matching the value
inside the switch against the values that you specify in each case label.
• Restricted to integers, characters, strings, and enums
• Case labels are constants
• Default label is optional
case value2 :
// statements
break ;
.
.
case valueN :
// statements
break ;
default :
// default statement
}
2.5.3 VB
If ... Then Statement
Loops in VB
Do loop
It repeats the enclosed block of statements while a Boolean condition is True
or until the condition becomes True. It could be terminated at any time with
the Exit Do statement.
' Syntax : sDo loop
Do ( While | Until ) ( condition )
' statements
' Continue Do
' statements
' Exit Do
' statements
Loop
' -or -
Do
'statements
' Continue Do
' statements
' Exit Do
' statements
Loop ( While | Until ) ( condition )
2.5.4.4 while
The while loop executes a statement(s) while a condition evaluates to true.
// Syntax : while loop
while ( statement ) {
statement ;
}
break statement
The break statement is used to terminate the loop or statement in which it
present. After that, the control will pass to the statements that present after
2.6. ARRAYS AND STRINGS 29
the break statement, if available. If the break statement present in the nested
loop, then it terminates only those loops which contains break statement.
continue statement
This statement is used to skip over the execution part of the loop on a
certain condition. After that, it transfers the control to the beginning of the
loop. Basically, it skips its following statements and continues with the next
iteration of the loop.
goto statement
This statement is used to transfer control to the labeled statement in the
program. The label is the valid identifier and placed just before the statement
from where the control is transferred.
return statement
This statement terminates the execution of the method and returns the con-
trol to the calling method. It returns an optional value. If the type of method
is void, then the return statement can be excluded.
throw statement
This is used to create an object of any valid exception class with the help
of new keyword manually. The valid exception must be derived from the
Exception class.
Where,
30 CHAPTER 2. LANGUAGE BASICS
// Example
int [] totalCount ; // can store int values
string [] affectedCountries ; // can store string values
double [] economicLoss ; // can store double values
CoronaVirus [] covid19 ; // can store instances of CoronaVirus
class which is a custom class
Only Declaration of an array doesn’t allocate memory to the array. For that
array must be initialized.
Where,
• datatype: specifies the type of data being allocated
• size: specifies the number of elements in the array
• arrayName: is the name of array variable
• new: allocates memory to an array according to its size
Multidimensional Arrays
The multi-dimensional array contains more than one row to store the values.
It is also known as a Rectangular Array in C# because it’s each row length
is same. It can be a 2D-array or 3D-array or more. Nested loop is required
inorder to access multidimensional array.
// creates a two - dimensional array of
// four rows and three columns .
int[, ] arrayName = new int [4, 3];
Jagged Arrays
A jagged array is an array whose elements are themselves arrays, not all
necessarily of the same length. This is declared in the format
// jagged array declaration
datatype [][] arrayName
Example,
// Example
int [][] Jag = new int [3][];
Before you can use Jag, its elements must be initialized. You can
initialize the elements like this:
Jag [0] = new int [5]; // array of 5 integers
Jag [1] = new int [4]; // array of 4 integers
Jag [2] = new int [2]; // array of 2 integers
32 CHAPTER 2. LANGUAGE BASICS
The elements of Jag are arrays and thus are reference types, so they are
initialized to null. Individual array elements can be accessed like this:
Jag [0][1] = 77;
// Assign 77 to the second element ([1]) of the first array
([0])
Example
22 }
23
24 /* output :
25 11 21 56 78
26 42 61 37 41 59 63
27 */
Types of Procedures
Visual Basic uses several types of procedures:
Sub Procedures Perform actions but do not return a value to the calling
code.
Function Procedures Return a value to the calling code. They can per-
form other actions before returning.
Sub Procedure
A Sub procedure is a series of Visual Basic statements enclosed by the Sub and
End Sub statements. The Sub procedure performs a task and then returns
control to the calling code, but it does not return a value to the calling code.
We can define a Sub procedure in modules, classes, and structures. By
default, it is Public.
The term method describes a Sub or Function procedure that is accessed
from outside its defining module, class, or structure.
A Sub procedure can take arguments, such as constants, variables, or
expressions, which are passed to it by the calling code.
Syntax
Where,
• Modifiers: specify the access level of the procedure; possible values are
- Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
Example
Example shown in Listing 2.2 demonstrates a Sub procedure CalculatePay
that takes two parameters hours and wages and displays the total pay of an
employee.
1 Module mysub
2 Sub CalculatePay ( ByRef hours As Double , ByRef wage As Decimal
)
3 'local variable declaration
4 Dim pay As Double
5 pay = hours * wage
2.7. PROCEDURE AND FUNCTIONS 35
2.7.2 Function
A Function procedure is a series of Visual Basic statements enclosed by the
Function and End Function statements. The Function procedure performs
a task and then returns control to the calling code. When it returns control,
it also returns a value to the calling code.
We can define a Function procedure in a module, class, or structure. It
is Public by default.
A Function procedure can take arguments, such as constants, variables,
or expressions, which are passed to it by the calling code.
Syntax
Where,
• Modifiers: specify the access level of the function; possible values are:
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
• ReturnType: specifies the data type of the variable the function re-
turns.
36 CHAPTER 2. LANGUAGE BASICS
Example
Example shown in Listing 2.3 demonstrates the example of function in VB.
1 Module myfunctions
2 Function FindMax ( ByVal num1 As Integer , ByVal num2 As Integer
) As Integer
3 Dim result As Integer
4 If (num1 > num2) Then
5 result = num1
6 Else
7 result = num2
8 End If
9 FindMax = result
10 End Function
11 Sub Main ()
12 Dim a As Integer = 2076
13 Dim b As Integer = 2077
14 Dim res As Integer
15 res = FindMax (a, b)
16 Console . WriteLine ("Max value is : {0}", res)
17 Console . ReadLine ()
18 End Sub
19 End Module
DEVELOPING CONSOLE
APPLICATION
37
38 CHAPTER 3. DEVELOPING CONSOLE APPLICATION
Console applications have one main entry point (static main method) of
execution, which takes an optional array of parameters as its only argument
for command-line parameter representation.
The .NET Framework provides library classes to enable rapid console ap-
plication development with output display capability in different formats.
System.Console (a sealed class) is one of the main classes used in the devel-
opment of console applications.
Where,
OR
static void Main( string [] args)
The arguments of the Main method is a String array that represents the
command-line arguments. Usually you determine whether arguments exist
by testing the Length property.
if (args. Length == 0) {
System . Console . WriteLine ("No arguments found !!");
return 1;
}
c:\windows\microsoft.net\framework\v4.7.0\csc.exe hello.cs
9
10 // Calculate the factorial iteratively rather than
recursively .
11 long tempResult = 1;
12 for (int i = 1; i <= n; i++) {
13 tempResult *= i;
14 }
15 return tempResult ;
16 }
17 }
18
19 class MainClass {
20 static int Main( string [] args) {
21 // Test if input arguments were supplied .
22 if (args. Length == 0) {
23 Console . WriteLine (" Please enter a numeric argument .");
24 Console . WriteLine ("Usage : Factorial <num >");
25 return 1;
26 }
27
28 /* Try to convert the input arguments to numbers . This will
throw an exception if the argument is not a number .
29 num = int.Parse (args [0]); */
30 int num;
31 bool test = int. TryParse (args [0] , out num);
32 if (! test) {
33 Console . WriteLine (" Please enter a numeric argument .");
34 Console . WriteLine ("Usage : Factorial <num >");
35 return 1;
36 }
37
38 // Calculate factorial .
39 long result = Functions . Factorial (num);
40
41 // Print result .
42 if ( result == -1)
43 Console . WriteLine ("Input must be >= 0 and <= 20.");
44 else
45 Console . WriteLine ("The Factorial of {num} is { result }."
num , result );
46
47 return 0;
48 }
49 }
ESSENTIALS OF
OBJECT–ORIENTED
PROGRAMMING
Class Creation
C#
43
CHAPTER 4. ESSENTIALS OF OBJECT–ORIENTED
44 PROGRAMMING
3 // fields
4 }
VB
We can create a class using the Class keyword, followed by the class name.
And the body of the class ended with the statement End Class.
1 [ Access_Specifier ] [ Shadows ] [ MustInherit | NotInheritable ] [
Partial ] Class ClassName
2 ' Data Members
3 ' Methods
4 ' Statements
5 End Class
Where,
4.1.2 Object
Objects are the basic run-time units of a class. Once a class is defined, we
can create any number of objects related to the class to access the defined
properties and methods.
Synatx:
4.1. OBJECT AND CLASS DEFINITION WORKING 45
States
States are the conditions in which objects exist. An object’s state is defined
by its attributes. An object’s attributes are usually static, and the values of
the attributes are usually dynamic.
Behavior
The term behavior refers to how objects interact with each other, and it is
defined by the operations an object can perform.
Identity
Identity is an uniqueness of an object from other objects. No matter what its
attributes and operations are, an object is always uniquely itself. It retains
its identity regardless of changes to its state or behavior.
Together, state and behavior define the roles that an object may play.
And an object may play many roles during its lifetime.
For example, an object in the bank’s Employee class could be involved
with the payroll system, with the customer database, or with the command
hierarchy.
The functions you require an object to perform are its responsibilities.
And an object’s responsibilities are fulfilled by its roles — by its state and
behavior combined.
So, you can capture all the meaningful functionality of an object by spec-
ifying its state and behavior. Objects are characterized by a third feature in
addition to state and behavior — identity.
CHAPTER 4. ESSENTIALS OF OBJECT–ORIENTED
48 PROGRAMMING
Object Class
Important points
• Through encapsulation a class can hide the internal details of how
an object does something. Encapsulation solves the problem at the
implementation level.
to use a Client object, it can request the name and address for the bank
without needing to know the company and department details of the
Client object.
• With the help of encapsulation, a class can change the internal imple-
mentation without hurting the overall functionality of the system.
• To have a class better control over its fields (validating values etc).
27 set {
28 phone = value ;
29 }
30 }
31 }
32 static void Main () {
33
Using an interface
Now, based on the current location (for which we can have variables),
whenever we want to view the balance information of a specific account,
we can use the IAccount interface and we can see how AsianAccount,
CHAPTER 4. ESSENTIALS OF OBJECT–ORIENTED
52 PROGRAMMING
Syntax
Example
1 using System ;
2
3 namespace InheritanceApplication {
4 class Shape {
5 public void setWidth (int w) {
6 width = w;
7 }
8 public void setHeight (int h) {
9 height = h;
10 }
11 protected int width ;
12 protected int height ;
13 }
14
15 // Derived class
16 class Rectangle : Shape {
17 public int getArea () {
4.4. INHERITANCE AND POLYMORPHISM WITH INTERFACE 53
Interface
Interface is a blueprint of a class. It is like abstract class because all the
methods which are declared inside the interface are abstract methods. It
cannot have method body and cannot be instantiated.
It is used to achieve multiple inheritance which can’t be achieved by class.
It is used to achieve fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or
struct which implements the interface, must provide the implementation of
all the methods declared inside the interface.
Following example show the use of interface which has draw() method.
Its implementation is provided by two classes: Rectangle and Circle.
1 using System ;
2 public interface Drawable {
3 void draw ();
4 }
5 public class Rectangle : Drawable {
6 public void draw () {
7 Console . WriteLine (" drawing rectangle ...");
8 }
9 }
10 public class Circle : Drawable {
11 public void draw () {
12 Console . WriteLine (" drawing circle ...");
13 }
14 }
CHAPTER 4. ESSENTIALS OF OBJECT–ORIENTED
54 PROGRAMMING
Polymorphism
There are two types of polymorphism in:
• Runtime polymorphism
Runtime polymorphism in achieved by method overriding which is also
known as dynamic binding or late binding.
• Base classes may define and implement virtual methods, and derived
classes can override them, which means they provide their own def-
inition and implementation. At run-time, when client code calls the
method, the CLR looks up the run-time type of the object, and invokes
that override of the virtual method.
not know at compile time which specific types of shapes the user will create.
However, the application has to keep track of all the various types of shapes
that are created, and it has to update them in response to user mouse actions.
You can use polymorphism to solve this problem in two basic steps:
• Create a class hierarchy in which each specific shape class derives from
a common base class
First, create a base class called Shape, and derived classes such as Rect-
angle, Circle, and Triangle. Give the Shape class a virtual method called
Draw, and override it in each derived class to draw the particular shape that
the class represents. Create a List<Shape> object and add a Circle, Triangle
and Rectangle to it. To update the drawing surface, use a foreach loop to
iterate through the list and call the Draw method on each Shape object in
the list. Even though each object in the list has a declared type of Shape, it
is the run-time type (the overridden version of the method in each derived
class) that will be invoked.
1 using System ;
2 using System . Collections . Generic ;
3 public class Shape {
4 // A few example members
5 public int X {
6 get;
7 private set;
8 }
9 public int Y {
10 get;
11 private set;
12 }
13 public int Height {
14 get;
15 set;
16 }
17 public int Width {
18 get;
19 set;
20 }
21 // Virtual method
22 public virtual void Draw () {
23 Console . WriteLine (" Performing base class drawing tasks ");
24 }
25 }
CHAPTER 4. ESSENTIALS OF OBJECT–ORIENTED
56 PROGRAMMING
71 Drawing a circle
72 Performing base class drawing tasks
73 */
Benefits
• We are clearly able to group by the fact that they share common be-
havior.
• You need only single list to hold movable object, not multiple list of
each type of object.
1 Using System ;
2 using System . Collections . Generic ;
3 namespace InheritanceInterface {
4 interface IMovable {
5 void Move ();
6 }
7 class Human : IMovable {
8 public void Move () // code that defines how human moves
9 {
10 Console . WriteLine ("I am a Human , I move by Walking ");
11 }
12 }
13 class Fish: IMovable {
14 public void Move () // code that defines how fish moves
15 {
16 Console . WriteLine ("I am a Fish , I move by swimming ");
17 }
18 }
19 class Car: IMovable {
20 public void Move () // code that defines how car moves
21 {
22 Console . WriteLine ("I am Car , I move By wheel ");
23 }
24 }
25 class Program {
CHAPTER 4. ESSENTIALS OF OBJECT–ORIENTED
58 PROGRAMMING
5.1 Introduction
• Windows Forms is a Graphical User Interface (GUI) class library which
is bundled in . Net Framework.
59
60CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
• Can also be used to add descriptive text to a Form to provide the user
with helpful information.
Label control can also display an image using the Image property, or a
combination of the ImageIndex and ImageList properties.
label1 . Image = Image . FromFile ("C:\\ testimage .jpg");
The following C# source code shows how to set some properties of the
Label through coding.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 label1 .Text = "This is my first label ";
12 label1 . BorderStyle = BorderStyle . FixedSingle ;
13 label1 . TextAlign = ContentAlignment . MiddleCenter ;
14 }
15 }
16 }
When you want to change display text of the Button , you can change
the Text property of the button.
button1 .Text = " Click Here";
The following C# source code shows how to change the button Text prop-
erty while Form loading event and to display a message box when pressing a
Button Control.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 button1 .Text = " Click Here";
12 }
13 private void button1_Click ( object sender , EventArgs e) {
14 MessageBox .Show("BCA -VIII ::2077 ");
15 }
16 }
17 }
62CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
• This control has additional functionality that is not found in the stan-
dard Windows text box control, including multi-line editing and pass-
word character masking.
You can also collect the input value from a TextBox control to a variable
like this way.
string var;
From the following C# source code you can see some important property
settings to a TextBox control.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 textBox1 . Width = 250;
12 textBox1 . Height = 50;
13 textBox1 . Multiline = true;
14 textBox1 . BackColor = Color .Blue;
15 textBox1 . ForeColor = Color . White ;
16 textBox1 . BorderStyle = BorderStyle . Fixed3D ;
17 }
18 private void button1_Click ( object sender , EventArgs e) {
19 string val;
20 val = textBox1 .Text;
21 MessageBox .Show(val);
22 }
23 }
5.2. BASIC CONTROLS 63
24 }
• The user can type a value in the text field or click the button to display
a drop down list. You can add individual objects with the Add method.
• You can delete items with the Remove method or clear the entire list
with the Clear method.
DropDownStyle
The DropDownStyle property specifies whether the list is always displayed or
whether the list is displayed in a drop-down. The DropDownStyle property
also specifies whether the text portion can be edited.
comboBox1 . DropDownStyle = ComboBoxStyle . DropDown ;
64CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
ComboBox Example
The following C# source code add four districts to a combo box while load
event of a Windows Form and int Button click event it displays the selected
text in the Combo Box.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 comboBox1 . Items .Add(" Taplejung ");
12 comboBox1 . Items .Add(" Panchthar ");
13 comboBox1 . Items .Add("Ilam");
14 comboBox1 . Items .Add(" Jhapa ");
15 comboBox1 . SelectedIndex = comboBox1 . FindStringExact ("
Taplejung ");
16
17 }
18 private void button1_Click ( object sender , EventArgs e) {
19 string var;
20 var = comboBox1 .Text;
21 MessageBox .Show(var);
22 }
23 }
24 }
• Normal - Places the upper-left corner of the image at upper left in the
picture box
• MainMenu is the container for the Menu structure of the form and menus
are made of MenuItem objects that represent individual parts of a
menu.
• You can add menus to Windows Forms at design time by adding the
MainMenu component and then appending menu items to it using the
Menu Designer.
66CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
5.4.2 ToolStrip
• ToolStrip is the base class for MenuStrip, StatusStrip, and
ContextMenuStrip.
5.5.2 Panel
• Windows Forms Panel controls are used to provide an identifiable
grouping for other controls.
Panel GroupBox
It does not have the Text prop- It has the Text property
erty
68CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
Panel GroupBox
5.6 ListBox
the first item in the list is number of items in the list, and
selected, the SelectedIndex the value of the Count property
value is 0. is always one more than the
largest possible SelectedIndex
• When multiple items are se- value because SelectedIndex
lected, the SelectedIndex is zero-based.
value reflects the selected item
that appears first in the list. • To add or delete items in
a ListBox control, use the
• The SelectedItem property is Add, Insert, Clear or Remove
similar to SelectedIndex, but method.
returns the item itself, usually
a string value. • Alternatively, you can add
items to the list by using the
• The Count property reflects the Items property at design time.
If the Sorted property of the C# ListBox is set to true, the item is inserted
into the list alphabetically. Otherwise, the item is inserted at the end of the
ListBox.
Listbox Column
A multicolumn ListBox places items into as many columns as are needed
to make vertical scrolling unnecessary. The user can use the keyboard to
navigate to columns that are not currently visible. First of all, you have Gets
or sets a value indicating whether the ListBox supports multiple columns
70CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
Add items
You can add individual items to the list with the Add method. The
CheckedListBox object supports three states through the CheckState enu-
meration: Checked, Indeterminate, and Unchecked.
checkedListBox1 . Items .Add(" Sunday ", CheckState . Checked );
If you want to add objects to the list at run time, assign an array of
object references with the AddRange method. The list then displays the
default string value for each object.
string [] days = new [] { " Sunday ", " Monday ", " Tuesday " };
Parameters:
• index(Int32) - The index of the item to set the check state for.
• When a user clicks on a radio button, it becomes checked, and all other
radio buttons with same group become unchecked.
The radio button and the check box are used for different functions. Use
a radio button when you want the user to choose only one option. When you
want the user to choose all appropriate options, use a check box. Like check
boxes, radio buttons support a Checked property that indicates whether the
radio button is selected.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 radioButton1 . Checked = true;
72CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
12 }
13 private void button1_Click ( object sender , EventArgs e) {
14 if ( radioButton1 . Checked == true) {
15 MessageBox .Show("You 've selected Taplejung !! ");
16 return ;
17 } else if ( radioButton2 . Checked == true) {
18 MessageBox .Show("You 've selected Jhapa !! ");
19 return ;
20 } else {
21 MessageBox .Show("You 've selected Sunsari !! ");
22 return ;
23 }
24 }
25 }
26 }
5.7.2 CheckBox
• CheckBox allow the user to make multiple selections from a number of
options.
• You can click a check box to select it and click it again to deselect it.
Usually CheckBox comes with a caption, which you can set in the Text
property.
checkBox1 .Text = "Java";
You can use the CheckBox control ThreeState property to direct the
control to return the Checked, Unchecked, and Indeterminate values. You
need to set the check box ThreeState property to True to indicate that you
want it to support three states.
checkBox1 . ThreeState = true;
The radio button and the check box are used for different functions. Use
a radio button when you want the user to choose only one option. When
you want the user to choose all appropriate options, use a check box. The
following C# program shows how to find a checkbox is selected or not.
5.8. DATETIMEPICKER 73
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void button1_Click ( object sender , EventArgs e) {
11 string msg = "";
12
13 if ( checkBox1 . Checked == true) {
14 msg = "Java => SpringBoot ";
15 }
16
5.8 DateTimePicker
• The DateTimePicker control allows you to display and collect date
and time from the user with a specified format.
• The DateTimePicker control has two parts, a label that displays the
selected date and a popup calendar that allows users to select a new
date.
74CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
• The Value property contains the current date and time the control is
set to.
• You can use the Text property or the appropriate member of Value to
get the date and time value.
DateTime iDate ;
• The control can display one of several styles, depending on its property
values.
• The values can be displayed in four formats, which are set by the
Format property:
The following C# program shows how to set and get the value of a Date-
TimePicker1 control.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 dateTimePicker1 . Format = DateTimePickerFormat . Short ;
12 dateTimePicker1 . Value = DateTime . Today ;
13 }
14 private void button1_Click ( object sender , EventArgs e) {
15 DateTime iDate ;
16 iDate = dateTimePicker1 . Value ;
17 MessageBox .Show(" Selected date is " + iDate );
18 }
5.9. TABCONTROL 75
19 }
20 }
5.9 TabControl
• TabControl presents a tabbed layout in the user interface.
• You can use the tab control to produce the kind of multiple-page dialog
box that appears many places in the Windows operating system, such
as the Control Panel Display Properties.
• When a tab is clicked, it raises the Click event for that TabPage object.
5.10 RichTextBox
load text and embedded images text, Unicode plain text, and
from a file; and find specified Rich Text Format (RTF).
characters.
• The possible file formats are
• The RichTextBox control is listed in RichTextBoxStreamType.
typically used to provide text
• You can also use a
manipulation and display fea-
RichTextBox control for Web-
tures similar to word processing
style links by setting the
applications such as Microsoft
DetectUrls property to true
Word.
and writing code to handle the
• Like the TextBox control, the LinkClicked event.
RichTextBox control can dis- • You can prevent the user from
play scroll bars; but unlike the manipulating some or all of the
TextBox control, its default set- text in the control by setting
ting is to display both horizon- the SelectionProtected prop-
tal and vertical scroll bars as erty to true.
needed, and it has additional
scroll bar settings. • You can undo and redo
most edit operations in a
• The RichTextBox control has RichTextBox control by calling
numerous properties to format the Undo and Redo methods.
text.
• The CanRedo method enables
• To manipulate files, the you to determine whether the
LoadFile and SaveFile meth- last operation the user has un-
ods can display and write multi- done can be reapplied to the
ple file formats including plain control.
5.11 ProgressBar
• A progress bar is a control that an application can use to indicate the
progress of a lengthy operation such as calculating a complex result,
downloading a large file from the Web etc.
– Minimum : Sets the lower value for the range of valid values for
progress.
– Maximum : Sets the upper value for the range of valid values for
progress.
– Value : This property obtains or sets the current level of progress.
5.12 ImageList
• An ImageList component is exactly what the name implies — a list of
images.
• You add images to the ImageList component by using the Add method
of the ImageList.
In this example, we have a list of file names, and then add each as an
Image object using the Image.FromFile method to read the data. The
Form1_Load event handler is used to make sure the code is run at startup of
the application.
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4 namespace WindowsFormsApplication1
5 {
6 public partial class Form1 : Form
7 {
8 public Form1 ()
9 {
10 InitializeComponent ();
11 }
12 private void Form1_Load ( object sender , EventArgs e)
13 {
14 // Add these file names to the ImageList on load.
15 string [] files = {
16 "image .png",
17 "logo.jpg"
18 };
19 var images = imageList1 . Images ;
20 foreach ( string file in files )
21 {
5.13. HELPPROVIDER 79
5.13 HelpProvider
The Windows Forms HelpProvider component is used to associate an HTML
Help 1.x Help file (either a .chm file, produced with the HTML Help Work-
shop, or an .htm file) with your Windows application. You can provide help
in a variety of ways:
• Open a Help file to specific areas, such as the main page of a Table of
Contents, the Index, or a search function.
• It does not require a lot of work on your part. This is its key feature.
5.16 Timer
• This class regularly invokes code. Every several seconds or minutes, it
executes a method.
Timer Control
The Timer Control plays an important role in the development of programs
both Client side and Server side development as well as in Windows Services.
With the Timer Control we can raise events at a specific interval of time
without the interaction of another thread.
We require Timer Object in many situations on our development envi-
ronment. We have to use Timer Object when we want to set an interval
between events, periodic checking, to start a process at a fixed time schedule,
to increase or decrease the speed in an animation graphics with time schedule
etc.
A Timer control does not have a visual representation and works as a
component in the background.
We can control programs with Timer Control in millisecond, seconds,
minutes and even in hours. The Timer Control allows us to set Interval
property in milliseconds. That is, one second is equal to 1000 milliseconds.
By default, the Enabled property of Timer Control is False. So, before
running the program we have to set the Enabled property is True, then only
the Timer Control starts its function.
Timer example
In the following program we display the current time in a Label Control. In
order to develop this program, we need a Timer Control and a Label Control.
Here, we set the timer interval as 1000 milliseconds, that means one second,
for displaying current system time in Label control for the interval of one
second.
using System ;
TimerCallback Delegate
Callback represents the method that handles calls from a Timer. This
method does not execute in the thread that created the timer; it executes in
a separate thread pool thread that is provided by the system.
Timer Class
System.Timers.Timer fires an event at regular intervals. This is a somewhat
more powerful timer. Instead of a Tick event, it has the Elapsed event.
The Start and Stop methods of System.Timers.Timer which are similar to
changing the Enabled property. Unlike the System.Windows.Forms.Timer,
the events are effectively queued — the timer doesn’t wait for one event to
have completed before starting to wait again and then firing off the next
event. The class is intended for use as a server-based or service component
5.17. SDI AND MDI APPLICATIONS 85
• Set elapsed event for the timer. This occurs when the interval elapses.
myTimer . Elapsed += OnTimedEvent ;
5.17.2 MDI
MDI stands for Multiple Document Interface. It is an interface design for
handling documents within a single application. When application consists
of an MDI parent form containing all other window consisted by app, then
MDI interface can be used. Switch focus to specific document can be easily
handled in MDI. For maximizing all documents, parent window is maximized
by MDI.
MDI Form
A Multiple Document Interface (MDI) programs can display multiple child
windows inside them. This is in contrast to single document interface (SDI)
86CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
The following C# program shows a MDI form with two child forms. Create
a new C# project, then you will get a default form Form1. Then add two
more forms in the project (Form2 , Form 3).
NOTE: If you want the MDI parent to auto-size the child form you can
code like this.
form. MdiParent = this;
1 using System ;
2 using System . Drawing ;
3 using System . Windows . Forms ;
4
5 namespace WindowsFormsApplication1 {
6 public partial class Form1 : Form {
7 public Form1 () {
8 InitializeComponent ();
9 }
10 private void Form1_Load ( object sender , EventArgs e) {
11 IsMdiContainer = true;
12 }
13 private void menu1ToolStripMenuItem_Click ( object sender ,
EventArgs e) {
14 Form2 frm2 = new Form2 ();
15 frm2.Show ();
16 frm2. MdiParent = this;
17 }
18 private void menu2ToolStripMenuItem_Click ( object sender ,
EventArgs e) {
19 Form3 frm3 = new Form3 ();
20 frm3.Show ();
21 frm3. MdiParent = this;
22 }
23 }
24 }
Main Difference
MDI and SDI are interface designs for handling documents within a single
application. MDI stands for “Multiple Document Interface” while SDI stands
for “Single Document Interface”. Both are different from each other in many
aspects. One document per window is enforced in SDI while child windows
per document are allowed in MDI. SDI contains one window only at a time
but MDI contain multiple document at a time appeared as child window.
MDI is a container control while SDI is not container control. MDI supports
many interfaces means we can handle many applications at a time according
to user’s requirement. But SDI supports one interface means you can handle
only one application at a time.
Key Differences
• MDI stands for “Multiple Document Interface” while SDI stands for
“Single Document Interface”.
• One document per window is enforced in SDI while child windows per
document are allowed in MDI.
• SDI contains one window only at a time but MDI contain multiple
document at a time appeared as child window.
• For switching between documents MDI uses special interface inside the
parent window while SDI uses Task Manager for that.
• A dialog box is most often used to provide the user with the means for
specifying how to implement a command or to respond to a question.
• Dialog boxes are used to interact with the user and retrieve information.
• In the class definition, add a reference to the form to inherit from. The
reference should include the namespace that contains the form, followed
by a period, then the name of the base form itself.
// Syntax :
public class CourseBCA : Faculty . ScienceAndTechnology
When inheriting forms, keep in mind that issues may arise with regard to
event handlers being called twice, because each event is being handled by
both the base class and the inherited class.
Custom Controls
Another way to create a control is to create one substantially from the be-
ginning by inheriting from Control. The Control class provides all the basic
functionality required by controls, including mouse and keyboard handling
events, but no control-specific functionality or graphical interface.
Creating a control by inheriting from the Control class requires much
more thought and effort than inheriting from UserControl or an existing
Windows Forms control. Because a great deal of implementation is left for
you, your control can have greater flexibility than a composite or extended
control, and you can tailor your control to suit your exact needs.
MaskedTextBox Control
If you need to require users to enter data in a well-defined format, such
as a telephone number or a part number, you can accomplish this quickly
and with minimal code by using the MaskedTextBox control. A mask is a
string made up of characters from a masking language that specifies which
characters can be entered at any given position in the text box. The control
displays a set of prompts to the user. If the user types an incorrect entry,
for example, the user types a letter when a digit is required, the control will
automatically reject the input.
Event-driven validation
Allows control over validation, complex validation checks. Each control that
accepts free-form user input has a Validating event that will occur whenever
the control requires data validation.
5.22 Delegates in C#
C# delegates are similar to pointers to functions, in C or C++. A delegate is
a reference type variable that holds the reference to a method. The reference
can be changed at runtime.
Delegates are especially used for implementing events and the call-back
methods. All delegates are implicitly derived from the System.Delegate
class.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the
delegate. A delegate can refer to a method, which has the same signature as
that of the delegate. For example, consider a delegate:
1 public delegate int MyDelegate ( string s);
The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable. Syntax for delegate
declaration is:
1 delegate <return type > <delegate name > <parameter list >
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the
new keyword and be associated with a particular method. When creating a
delegate, the argument passed to the new expression is written similar to a
method call, but without the arguments to the method. For example
1 public delegate void printString ( string s);
2 ...
3 printString ps1 = new printString ( WriteToScreen );
4 printString ps2 = new printString ( WriteToFile );
7 num += p;
8 return num;
9 }
10 public static int MultNum (int q) {
11 num *= q;
12 return num;
13 }
14 public static int getNum () {
15 return num;
16 }
17 static void Main( string [] args) {
18 // create delegate instances
19 NumberChanger nc1 = new NumberChanger ( AddNum );
20 NumberChanger nc2 = new NumberChanger ( MultNum );
21 // calling the methods using the delegate objects
22 nc1 (25);
23 Console . WriteLine ("Value of Num: {0}", getNum ());
24 nc2 (5);
25 Console . WriteLine ("Value of Num: {0}", getNum ());
26 Console . ReadKey ();
27 }
28 }
29 }
30 /* output :
31 Value of Num: 35
32 Value of Num: 175
33 */
class. Some other class that accepts this event is called the subscriber class.
Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the
delegate. The event- delegate association is also defined in this object. A
publisher class object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event
handler. The delegate in the publisher class invokes the method (event han-
dler) of the subscriber class.
Declaring Events
To declare an event inside a class, first a delegate type for the event must be
declared. For example,
public delegate string MyDel ( string str);
Example
1 using System ;
2 namespace SampleApp {
3 public delegate string MyDel ( string str);
4 class EventProgram {
5 event MyDel MyEvent ;
6 }
7 public EventProgram () {
8 this. MyEvent += new MyDel (this. WelcomeUser );
9 }
10 public string WelcomeUser ( string username ) {
11 return " Welcome " + username ;
12 }
13 static void Main( string [] args) {
14 EventProgram obj1 = new EventProgram ();
15 string result = obj1. MyEvent ("Mr User");
16 Console . WriteLine ( result );
17 }
18 }
19
20 /* output :
21 Welcome Mr User
22 */
• try - A try block identifies a block of code for which particular excep-
tions is activated. It is followed by one or more catch blocks.
C#
// Syntax
try {
// statements causing exception
} catch ( ExceptionName e1) {
// error handling code
} catch ( ExceptionName e2) {
// error handling code
} catch ( ExceptionName eN) {
// error handling code
} finally {
// statements to be executed
}
96CHAPTER 5. WINDOWS FORMS AND STANDARD COMPONENTS
VB
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in different
situations.
22 }
23 }
24 /* output :
25 Exception caught : System . DivideByZeroException : Attempted to
divide by zero
26 at ...
27 Result : 0
28 */
VB
1 Module ExceptionExample
2 Sub division ( ByVal num1 As Integer , ByVal num2 As Integer )
3 Dim result As Integer
4 Try
5 result = num1 \ num2
6 Catch e As DivideByZeroException
7 Console . WriteLine (" Exception caught : {0}", e)
8 Finally
9 Console . WriteLine (" Result : {0}", result )
10 End Try
11 End Sub
12 Sub Main ()
13 division (50 , 0)
14 Console . ReadKey ()
15 End Sub
16 End Module
10 }
11 Console . ReadKey ();
12 }
13 }
14 }
15 public class TempIsZeroException : Exception {
16 public TempIsZeroException ( string message ): base( message ) {}
17 }
18 public class Temperature {
19 int temperature = 0;
20 public void showTemp () {
21 if ( temperature == 0) {
22 throw (new TempIsZeroException ("Zero Temperature found "));
23 } else {
24 Console . WriteLine (" Temperature : {0}", temperature );
25 }
26 }
27 }
28
29 /* output :
30 TempIsZeroException : Zero Temperature found
31 */
VB
1 Module CustomExceptionVB
2 Public Class TempIsZeroException : Inherits
ApplicationException
3 Public Sub New( ByVal message As String )
4 MyBase .New( message )
5 End Sub
6 End Class
7 Public Class Temperature
8 Dim temperature As Integer = 0
9 Sub showTemp ()
10 If ( temperature = 0) Then
11 Throw (New TempIsZeroException ("Zero Temperature
found "))
12 Else
13 Console . WriteLine (" Temperature : {0}", temperature )
14 End If
15 End Sub
16 End Class
17 Sub Main ()
18 Dim temp As Temperature = New Temperature ()
19 Try
5.24. EXCEPTION HANDLING 99
20 temp. showTemp ()
21 Catch e As TempIsZeroException
22 Console . WriteLine (" TempIsZeroException : {0}", e. Message
)
23 End Try
24 Console . ReadKey ()
25 End Sub
26 End Module
ADO . NET provides consistent access to data sources such as SQL Server
and XML, and to data sources exposed through OLEDB and ODBC. Data-
sharing consumer applications can use ADO . NET to connect to these data
sources and retrieve, handle, and update the data that they contain.
101
CHAPTER 6. DATA ACCESS WITH ADO (ACTIVEX DATA OBJECT)
102 . NET
• Maintainability
Since ADO . NET is different layer and independent of database, it
is loosely coupled with business logic, it enables easy transform of the
architectural changes in a deployed application.
• Performance
Provides fast execution of disconnected applications, over the discon-
nected RecordSets in classic ADO.
• Scalability
Provides the conservation of resources, such as database locks and
database connections. The applications that are based on ADO.NET
support disconnected across to data. So, that the databases are not
locked by user queries for long duration.
6.2.1.1 DataProvider
• The . NET framework Data Provider is component that has been explic-
itly designed for data manipulation and fast, forward-only, read-only
access to data.
Connection
• The base class for all Connection objects in the DbConnection class.
Command
• Command object performs the standard Select, Insert, Delete and Up-
date T-SQL operations.
• The base class for all Command objects is the DbCommand class.
DataReader
• The base class for all DataReader objects is the DbDataReader class.
DataAdapter
• The Data Adapter provides the bridge between the Data Set object
and the data source.
• The base class for all DataAdapter objects is the DbDataAdapter class.
The following lists the data providers that are included in the . NET frame-
work.
1. SQL Server
2. OLEDB
3. ODBC
4. Oracle
6.2.1.2 DataSet
• The dataset represents a subset of the database.
DataRelation
• Relationship can be built with more than one column per table by
specifying an array of Data Column objects as the key columns.
18 CountryName ";
19 SqlDataAdapter sda = new SqlDataAdapter ( objCommand );
20 DataTable dt = new DataTable ();
21 sda.Fill(dt);
22 objConnection . Close ();
23 }
24 }
25 }
DataTable
Properties Description
Properties Description
Listing 6.3: Example to connect sql server database and retrieve data using
connection, command and reader
If for some reason, you want to loop through each row in the
SqlDataReader object, then use the Read() method, which returns
true as long as there are rows to read. If there are no more rows to
read, then this method will return false. In the following example, we
loop through each row in the SqlDataReader and then compute the
10% discounted price.
1. Connection: 3. DataReader:
• SQLConnection, • SQLDataReader,
• OracleConnection, • OracleDataReader,
• OleDbConnection, • OleDbDataReader,
• OdbcConnection, etc. • OdbcDataReader, etc.
2. Command: 4. DataAdapter:
• SQLCommand, • SQLDataAdapter,
• OracleCommand, • OracleDataAdapter,
• OleDbCommand, • OleDbDataAdapter,
• OdbcCommand, etc. • OdbcDataAdapter, etc.
6.3.1 Connection
• It is used to establish an open connection to the SQL Server database.
• Connection does not close explicitly even it goes out of scope. There-
fore, you must explicitly close the connection by calling Close()
method.
Example
1 using System ;
2 using System .Data. SqlClient ;
3 namespace SqlConnectionExample {
4 class Program {
5 static void Main( string [] args) {
6 new Program (). Connecting ();
7 }
8 public void Connecting () {
9 using ( SqlConnection con = new SqlConnection ("data source
=.; database =bca; integrated security =SSPI")) {
10 con.Open ();
11 Console . WriteLine (" Connection to database successful .");
12 }
13 }
14 }
15 }
6.3.2 Command
• This class is used to store and execute SQL statement for SQL Server
database.
Example
1 using System ;
2 using System .Data. SqlClient ;
3 namespace SqlCommandExample {
4 class Program {
5 static void Main( string [] args) {
6 new Program (). CreateTable ();
7 }
8 public void CreateTable () {
9 SqlConnection con = null;
10 try {
11 // Creating Connection
12 con = new SqlConnection ("data source =.; database =bca;
integrated security =SSPI");
13 // writing sql query
14 SqlCommand cm = new SqlCommand (" select * from student ",
con);
15 // Opening Connection
16 con.Open ();
6.3. WORKING WITH CONNECTION, COMMAND, DATAREADER115
6.3.3 DataReader
• This class is used to read data from SQL Server database.
1 using System ;
2 using System .Data. SqlClient ;
3 namespace SqlDataReaderExample {
4 class Program {
5 static void Main( string [] args) {
6 new Program (). GetData ();
7 }
8 public void GetData () {
9 SqlConnection con = null;
10 try {
11 // Creating Connection
12 con = new SqlConnection ("data source =.; database =bca;
integrated security =SSPI");
13 // writing sql query
14 SqlCommand cm = new SqlCommand (" select * from stu", con)
;
15 // Opening Connection
16 con.Open ();
CHAPTER 6. DATA ACCESS WITH ADO (ACTIVEX DATA OBJECT)
116 . NET
1 using System ;
2 using System .Data;
3 class Program {
4 static void Main () {
5 // Create two DataTable instances .
6 DataTable table1 = new DataTable (" patients ");
7 table1 . Columns .Add("name");
8 table1 . Columns .Add("id");
9 table1 .Rows.Add("ram", 1);
10 table1 .Rows.Add(" shyam ", 2);
11 DataTable table2 = new DataTable (" medications ");
12 table2 . Columns .Add("id");
13 table2 . Columns .Add(" medication ");
14 table2 .Rows.Add (1, " massage ");
15 table2 .Rows.Add (2, " therapy ");
16 // Create a DataSet and put both tables in it.
17 DataSet set = new DataSet (" office ");
18 set. Tables .Add( table1 );
19 set. Tables .Add( table2 );
20 // Visualize DataSet .
21 Console . WriteLine (set. GetXml ());
22 }
23 }
1 <office >
2 <patients >
3 <name >ram </name >
4 <id >1</id >
5 </ patients >
6 <patients >
7 <name >shyam </name >
8 <id >2</id >
9 </ patients >
10 <medications >
11 <id >1</id >
12 <medication >massage </ medication >
13 </ medications >
14 <medications >
15 <id >2</id >
16 <medication >therapy </ medication >
17 </ medications >
CHAPTER 6. DATA ACCESS WITH ADO (ACTIVEX DATA OBJECT)
118 . NET
And the program is illustrated in Listing 6.10 calls stored procedure and
loads data into dataset.
1 string ConnectionString = ConfigurationManager . ConnectionStrings
[" DBConnectionString "]. ConnectionString ;
2 using ( SqlConnection connection = new SqlConnection (
ConnectionString )) {
3 SqlDataAdapter dataAdapter = new SqlDataAdapter ("
spGetProductAndCategoriesData ", connection );
4 dataAdapter . SelectCommand . CommandType = CommandType .
StoredProcedure ;
5 DataSet dataset = new DataSet ();
6 dataAdapter .Fill( dataset );
7 GridViewProducts . DataSource = dataset . Tables [0];
8 GridViewProducts . DataBind ();
9 GridViewCategories . DataSource = dataset . Tables [1];
10 GridViewCategories . DataBind ();
11 }
Editing/Modifying records:
To edit an existing row in a DataTable, you need to locate the DataRow you
want to edit, and then assign the updated values to the desired columns. If
you don’t know the index of the row you want to edit, use the FindBy method
to search by the primary key.
Adding records:
To add new records to a dataset, create a new data row by calling the method
on the DataTable. Then add the row to the DataRow collection (Rows) of
the DataTable.
Deleting records:
Call the Delete method of a DataRow.
Example
1 class Program {
2 static void Main( string [] args) {
3 DataTable table1 = new DataTable (" patients ");
4 table1 . Columns .Add("name");
5 table1 . Columns .Add("id");
6 table1 .Rows.Add("ram", 1);
7 table1 .Rows.Add(" shyam ", 2);
8
9 DataSet hospital = new DataSet (" Hospital ");
10 hospital . Tables .Add( table1 );
11
12 // Editing / updating record in DataSet
13 DataRow patient1 = table1 .Rows [0];
14 patient1 ["name"] = " khyam ";
15
• Using a DataView, you can expose the data in a table with different
sort orders, and you can filter the data by row state or based on a filter
expression.
• This behavior differs from the Select method of the DataTable, which
returns a DataRow array from a table based on a particular filter and/or
sort order:
– this content reflects changes to the underlying table, but its mem-
bership and ordering remain static.
• You can use a DataViewManager to manage view settings for all the
tables in a DataSet.
6.6. USING DATAVIEW 121
Creating DataView
There are two ways to create a DataView. You can use the DataView con-
structor, or you can create a reference to the DefaultView property of the
DataTable. The DataView constructor can be empty, or it can take either
a DataTable as a single argument, or a DataTable along with filter criteria,
sort criteria, and a row state filter.
The following code example demonstrates how to create a DataView
using the DataView constructor. A RowFilter, Sort column, and
DataViewRowState are supplied along with the DataTable.
1 DataView custDV = new DataView ( custDS . Tables [" Customers "], "
Country = 'Nepal '", " ContactName ", DataViewRowState .
CurrentRows );
Example of DataView
1 using System ;
2 using System .Data;
3 using System .Data. SqlClient ;
4 using System . Windows . Forms ;
5
6 namespace WindowsApplication1 {
7 public partial class Form1 : Form {
8 public Form1 () {
9 InitializeComponent ();
10 }
11
12 private void button1_Click ( object sender , EventArgs e) {
13 string connetionString = null;
14 SqlConnection connection ;
15 SqlCommand command ;
16 SqlDataAdapter adapter = new SqlDataAdapter ();
17 DataSet ds = new DataSet ();
CHAPTER 6. DATA ACCESS WITH ADO (ACTIVEX DATA OBJECT)
122 . NET
18 DataView dv;
19 string sql = null;
20 connetionString = "Data Source = ServerName ; Initial Catalog =
DatabaseName ;User ID= UserName ; Password = Password ";
21 sql = " Select * from product ";
22 connection = new SqlConnection ( connetionString );
23 try {
24 connection .Open ();
25 command = new SqlCommand (sql , connection );
26 adapter . SelectCommand = command ;
27 adapter .Fill(ds , " Create DataView ");
28 adapter . Dispose ();
29 command . Dispose ();
30 connection . Close ();
31
32 dv = ds. Tables [0]. DefaultView ;
33
11
12 // 4 Render data onto the screen
13 dataGridView1 . DataSource = t;
14 }
15 }
16 }
Example of DataGridView
1 using System ;
2 using System .Data;
3 using System . Windows . Forms ;
4 using System .Data. SqlClient ;
5
6 namespace WindowsFormsApplication1 {
7 public partial class Form1 : Form {
8 SqlCommand sCommand ;
9 SqlDataAdapter sAdapter ;
10 SqlCommandBuilder sBuilder ;
11 DataSet sDs;
12 DataTable sTable ;
13
14 public Form1 () {
15 InitializeComponent ();
16 }
17
18 private void button1_Click ( object sender , EventArgs e) {
19 string connectionString = "Data Source =.; Initial Catalog =
pubs; Integrated Security =True";
20 string sql = " SELECT * FROM Stores ";
21 SqlConnection connection = new SqlConnection (
connectionString );
22 connection .Open ();
23 sCommand = new SqlCommand (sql , connection );
24 sAdapter = new SqlDataAdapter ( sCommand );
25 sBuilder = new SqlCommandBuilder ( sAdapter );
26 sDs = new DataSet ();
27 sAdapter .Fill(sDs , " Stores ");
28 sTable = sDs. Tables [" Stores "];
29 connection . Close ();
30 dataGridView1 . DataSource = sDs. Tables [" Stores "];
31 dataGridView1 . ReadOnly = true;
32 save_btn . Enabled = false ;
33 dataGridView1 . SelectionMode = DataGridViewSelectionMode .
FullRowSelect ;
34 }
CHAPTER 6. DATA ACCESS WITH ADO (ACTIVEX DATA OBJECT)
124 . NET
35
36 private void new_btn_Click ( object sender , EventArgs e) {
37 dataGridView1 . ReadOnly = false ;
38 save_btn . Enabled = true;
39 new_btn . Enabled = false ;
40 delete_btn . Enabled = false ;
41 }
42
43 private void delete_btn_Click ( object sender , EventArgs e) {
44 if ( MessageBox .Show("Do you want to delete this row ?", "
Delete ", MessageBoxButtons . YesNo ) == DialogResult .Yes) {
45 dataGridView1 .Rows. RemoveAt ( dataGridView1 . SelectedRows
[0]. Index );
46 sAdapter . Update ( sTable );
47 }
48 }
49
WEB APPLICATION
127
128 CHAPTER 7. WEB APPLICATION
1 <%
2 /* create a cookie collection named 'student ' */
3 Response . Cookies (" student ")(" firstname ")=" Jeevan "
4 Response . Cookies (" student ")(" lastname ")="P"
5 Response . Cookies (" student ")(" district ")=" Taplejung "
6 %>
• In the example below, we retrieve the value of the cookie named ‘name’
and display it on a page:
1 <%
2 name= Request . Cookies ("name")
3 response . write ("Name=" & name)
4 // output : Name= Jeevan
5 %>
20 <!-- /*
21 student : firstname =Jee
22 student : lastname =P
23 student : district = Taplejung
24 */
25 -->
26 </body >
27 </html >
7.2.2 Session
The web server does not know who you are and what you do, because the
HTTP address doesn’t maintain state.
ASP solves this problem by creating a unique cookie for each user. The
cookie is sent to the user’s computer and it contains information that identi-
fies the user. This interface is called the Session object.
The Session object stores information about, or change settings for a user
session.
Variables stored in a Session object hold information about one single
user, and are available to all pages in one application. Common information
stored in session variables are name, id, and preferences. The server creates
a new Session object for each new user, and destroys the Session object when
the session expires.
A session starts when:
• A new user requests an ASP file, and the Global.asa file includes a
Session_OnStart procedure
• A user requests an ASP file, and the Global.asa file uses the <object>
tag to instantiate an object with session scope
A session ends if a user has not requested or refreshed a page in the applica-
tion for a specified period. By default, this is 20 minutes.
If you want to set a timeout interval that is shorter or longer than the
default, use the Timeout property.
The example below sets a timeout interval of 5 minutes:
1 <%
2 Session . Timeout =5
3 %>
7.2. IMPLEMENTING SESSION AND COOKIES 131
Note: The main problem with sessions is WHEN they should end. We
do not know if the user’s last request was the final one or not. So we do not
know how long we should keep the session “alive”. Waiting too long for an
idle session uses up resources on the server, but if the session is deleted too
soon the user has to start all over again because the server has deleted all
the information. Finding the right timeout interval can be difficult!
When the value is stored in a session variable it can be reached from ANY
page in the ASP application:
1 Welcome <% Response . Write ( Session (" username "))%>
The example below removes the session variable “sale” if the value of the
session variable “age” is lower than 18:
1 <%
2 If Session . Contents ("age") <18 then
3 Session . Contents . Remove ("sale")
4 End If
5 %>
If you do not know the number of items in the Contents collection, you can
use the Count property:
1 <%
2 dim i
3 dim j
4 j= Session . Contents . Count
5 Response . Write (" Session variables : " & j)
6 For i=1 to j
7 Response . Write ( Session . Contents (i) & "<br >")
8 Next
9
10 /* output :
11 Session variables : 2
7.3. CLIENT AND SERVER SIDE VALIDATION 133
12 Donald Duck
13 50
14 */
15 %>
With this said, client-side validation is the more insecure form of valida-
tion. When a page is generated in an end user’s browser, this end user can
look at the code of the page quite easily (simply by right-clicking his mouse
in the browser and selecting View Code). When he does this, in addition to
seeing the HTML code for the page, he can also see all the JavaScript that
is associated with the page. If you are validating your form client-side, it
doesn’t take much for the crafty hacker to repost a form (containing the val-
ues he wants in it) to your server as valid. There are also the cases in which
clients have simply disabled the client-scripting capabilities in their browsers
- thereby making your validations useless. Therefore, client-side validation
should be looked on as a convenience and a courtesy to the end user and
never as a security mechanism
1. RequiredFieldValidator 4. RegularExpressionValidator
2. CompareValidator 5. CustomValidator
3. RangeValidator 6. ValidationSummary
The Table 7.1 describes the functionality of each of the available valida-
tion server controls.
5 End Sub
6 </script >
7 <html xmlns ="http :// www.w3.org /1999/ xhtml ">
8 <head runat =" server ">
9 <title > RequiredFieldValidator </ title >
10 </head >
11 <body >
12 <form id="form1 " runat =" server ">
13 <div >
14 <asp: TextBox ID=" TextBox1 " Runat =" server " ></asp:
TextBox >
15 <asp: RequiredFieldValidator ID="
RequiredFieldValidator1 " Runat =" server " ErrorMessage ="
Required !" ControlToValidate =" TextBox1 ">
16 </asp: RequiredFieldValidator >
7.3. CLIENT AND SERVER SIDE VALIDATION 137
17 <br />
18 <asp: Button ID=" Button1 " Runat =" server " Text=" Submit "
19 OnClick =" Button1_Click " />
20 <br />
21 <br />
22 <asp: Label ID=" Label1 " Runat =" server " ></asp:Label >
23 </div >
24 </form >
25 </body >
26 </html >
• For instance, you can specify that a form element’s value must be an
integer and greater than a specified number.
• You can also state that values must be strings, dates, or other data
types that are at your disposal.
6 </script >
7 <html xmlns ="http :// www.w3.org /1999/ xhtml " >
8 <head runat =" server ">
9 <title > CompareFieldValidator </ title >
10 </head >
11 <body >
12 <form runat =" server ">
13 <p>
14 Password <br >
15 <asp: TextBox ID=" TextBox1 " Runat =" server "
16 TextMode =" Password " ></asp:TextBox >
17
18 <asp: CompareValidator ID=" CompareValidator1 "
19 Runat =" server " ErrorMessage =" Passwords do not
match !"
20 ControlToValidate =" TextBox2 "
21 ControlToCompare =" TextBox1 " ></asp:
CompareValidator >
22 </p>
23 <p>
24 Confirm Password <br >
25 <asp: TextBox ID=" TextBox2 " Runat =" server "
26 TextMode =" Password " ></asp:TextBox >
27 </p>
28 <p>
29 <asp: Button ID=" Button1 " OnClick =" Button1_Click "
30 Runat =" server " Text=" Login " ></asp:Button >
31 </p>
32 <p>
33 <asp: Label ID=" Label1 " Runat =" server " ></asp:Label >
34 </p>
35 </form >
36 </body >
37 </html >
Listing 7.4: Using the CompareValidator to test values against other control
values
Listing 7.5: Using the CompareValidator to test values against other control
values with C#
7.3. CLIENT AND SERVER SIDE VALIDATION 139
• For an example of this, go back to the text-box element that asks for
the age of the end user and performs a validation on the value provided.
Age:
<asp: TextBox ID=" TextBox1 " Runat =" server " ></asp:TextBox >
<asp: RangeValidator ID=" RangeValidator1 " Runat =" server "
ControlToValidate =" TextBox1 " Type=" Integer "
ErrorMessage ="You must be between 30 and 40"
MaximumValue ="40" MinimumValue ="30" ></asp: RangeValidator >
Listing 7.7: Using the RangeValidator control to test a string date value with
VB
10 }
11 protected void Button1_Click ( object sender , EventArgs e){
12 if (Page. IsValid ){
13 Label1 .Text = "You are set to arrive on: " +
TextBox1 .Text. ToString ();
14 }
15 }
16 </script >
Listing 7.8: Using the RangeValidator control to test a string date value with
C#
• This means that you can define a structure that a user’s input will be
applied against to see if its structure matches the one that you define.
• For instance, you can define that the structure of the user input must
be in the form of an e-mail address or an Internet URL; if it doesn’t
match this definition, the page is considered invalid.
Listing 7.9 shows how to validate what is input into a text box by making
sure it is in the form of an e-mail address.
1 Email:
2 <asp: TextBox ID=" TextBox1 " Runat =" server " ></asp:TextBox >
3
4 <asp: RegularExpressionValidator ID=" RegularExpressionValidator1 "
5 Runat=" server " ControlToValidate =" TextBox1 "
6 ErrorMessage ="You must enter an email address "
7 ValidationExpression ="\w+([ -+.]\w+)*@\w+([ -.]\w+) *\.\w+([ -.]\w+)
*">
8 </asp: RegularExpressionValidator >
ErrorMessage property to push out the error message to the screen if the
validation test fails. The unique property of this validation control is the
ValidationExpression property. This property takes a string value, which
is the regular expression you are going to apply to the input value.
• For example, look at a simple form that asks for a number from the
end user.
5 }
6 </script >
• Now let’s move this same validation check from the client to the server.
9 Try
10 Dim num As Integer = Integer .Parse (args. Value )
11 args. IsValid = (( num mod 5) = 0)
12 Catch ex As Exception
13 args. IsValid = False
14 End Try
15 End Sub
16 </script >
17 <html xmlns ="http :// www.w3.org /1999/ xhtml " >
18 <head runat =" server ">
19 <title > CustomValidator </ title >
20 </head >
21 <body >
22 <form id="form1 " runat =" server ">
23 <div >
24 <p>
25 Number :
26 <asp: TextBox ID=" TextBox1 "
27 Runat =" server " ></asp:TextBox >
28
29 <asp: CustomValidator ID=" CustomValidator1 "
30 Runat =" server " ControlToValidate =" TextBox1 "
31 ErrorMessage =" Number must be divisible by 5"
32 OnServerValidate =" ValidateNumber " ></asp:
CustomValidator >
33 </p>
34 <p>
35 <asp: Button ID=" Button1 " OnClick =" Button1_Click "
36 Runat =" server " Text=" Button " ></asp:Button >
37 </p>
38 <p>
39 <asp: Label ID=" Label1 " Runat =" server " ></asp:Label >
40 </p>
41 </div >
42 </form >
43 </body >
44 </html >
• Instead, this control is the reporting control, which is used by the other
validation controls on a page.
• You can use this validation control to consolidate error reporting for
all the validation errors that occur on a page instead of leaving this up
to each and every individual validation control.
1 <p>
2 First name
3 <asp: TextBox ID=" TextBox1 " Runat =" server "></asp: TextBox >
7.3. CLIENT AND SERVER SIDE VALIDATION 147
4
5 <asp: RequiredFieldValidator ID=" RequiredFieldValidator1 "
6 Runat =" server " ErrorMessage ="You must enter your first
name"
7 ControlToValidate =" TextBox1 "></asp: RequiredFieldValidator >
8 </p>
9 <p>
10 Last name
11 <asp: TextBox ID=" TextBox2 " Runat =" server "></asp: TextBox >
12
13 <asp: RequiredFieldValidator ID=" RequiredFieldValidator2 "
14 Runat =" server " ErrorMessage ="You must enter your last name
"
15 ControlToValidate =" TextBox2 "></asp: RequiredFieldValidator >
16 </p>
17 <p>
18 <asp: Button ID=" Button1 " OnClick =" Button1_Click " Runat ="
server "
19 Text=" Submit "></asp: Button >
20 </p>
21 <p>
22 <asp: ValidationSummary ID=" ValidationSummary1 " Runat =" server
"
23 HeaderText ="You received the following errors :"></asp:
ValidationSummary >
24 </p>
25 <p>
26 <asp: Label ID=" Label1 " Runat =" server "></asp: Label >
27 </p>
Features of IIS
Application pools Application pools form an important part of an IIS
server system. An individual application pool could have zero or many IIS
worker processes running. These worker processes are responsible for running
application instances.
7.4. BUILDING WEB APPLICATION 149
Security IIS comes with security features, like utilities for managing TLS
certificates, binding so SFTP and HTTPS can be enabled, and the ability to
filter requests so you can effectively whitelist and blacklist traffic. You can
implement authorization and permission rules and log requests and access a
suite of FTP security functions.
Candidates are required to give their own answers in their own words as far as practicable.
Figure in the margin indicate full marks.
Group A
Answer TWO questions. 2 × 12 = 24
1. What are the components of NET framework? How do you implement OOP in C#?
Explain with example.
3. (a) What is hosting? Write about IIS Web Server and its features
(b) What is the use of data bound control in web application? Give example.
Group B
Answer SIX questions. 6 × 6 = 36
6. What do you mean by concurrency control? How is concurrency control resolved and
maintained in ADO.NET? Explain with example.
Candidates are required to give their own answers in their own words as far as practicable.
Figure in the margin indicate full marks.
Group A
Answer TWO questions. 2 × 12 = 24
2. What do you mean by polymorphism? Describe with its types and example.
3. Write a program for Electricity Bill Statement (EBS). The EBS takes units consumed
from consumer and calculates; Electricity Charges (EC) using provided criteria:
(i) Units less than 100 Rs 500 minimum charge.
(ii) Units 100 above 300 below Rs 15 (per unit + minimum charge).
(iii) Units above 300 Rs 25 (per unit + minimum charge).
Group B
Answer SIX questions. 6 × 6 = 36
4. What is the difference between a class and an object, and how do these terms relate
to each other? Explain briefly with examples?
5. List different features of . NET Technology. What does ‘managed code’ means in .
NET context?
6. What are the difference between Radio Button control and Check Box control? Ex-
plain with an example.
7. Why do we use String Builder in place of String in C#. NET? Differentiate between
string and String Builder.
153
154
REFERENCES
155
156 REFERENCES
How to create a DataView. (n.d.). Retrieved February 22, 2021, from http:
//csharp.net-informations.com/dataview/create-dataview.htm