Microsoft .

Net

Overview of Microsoft. NET
The Microsoft. NET strategy was presented by Microsoft officials to the rest of the world in June 2000:
• • • • • • • •

.NET is Microsoft's new Internet and Web strategy .NET is NOT a new operating system .NET is a new Internet and Web based infrastructure .NET delivers software as Web Services .NET is a framework for universal services .NET is a server centric computing model .NET will run in any browser on any platform .NET is based on the newest Web standards

NET Internet Standards .NET is built on the following Internet standards:
• • • •

HTTP, the communication protocol between Internet Applications XML, the format for exchanging data between Internet Applications SOAP, the standard format for requesting Web Services UDDI, the standard to search and discover Web Services

NET Framework The .NET Framework is the infrastructure for the new Microsoft .NET Platform. The .NET Framework is a common environment for building, deploying, and running Web Services and Web Applications. The .NET Framework contains common class libraries - like ADO.NET, ASP.NET and Windows Forms - to provide advanced standard services that can be integrated into a variety of computer systems. The .NET Framework is language neutral. Currently it supports C++, C#, Visual Basic, JScript (The Microsoft version of JavaScript) and COBOL. Third-party languages - like Eiffel, Perl, Python, Smalltalk, and others - will also be available for building future .NET Framework applications. The new Visual Studio.NET is a common development environment for the new .NET Framework. It provides a feature-rich application execution environment, simplified development and easy integration between a number of different development languages. Common Language Run Time ( CLR) Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

1

SUNSAT The Perfect Team

Microsoft .Net
To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with the code; every loadable common language runtime portable executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries. The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Objects whose lifetimes are managed in this way are called managed data. Garbage collection eliminates memory leaks as well as some other common programming errors. If your code is managed, you can use managed data, unmanaged data, or both managed and unmanaged data in your .NET Framework application. Because language compilers supply their own types, such as primitive types, you might not always know (or need to know) whether your data is being managed. The common language runtime makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other, and their behaviors can be tightly integrated. For example, you can define a class and then use a different language to derive a class from your original class or call a method on the original class. You can also pass an instance of a class to a method of a class written in a different language. This cross-language integration is possible because language compilers and tools that target the runtime use a common type system defined by the runtime, and they follow the runtime's rules for defining new types, as well as for creating, using, persisting, and binding to types. As part of their metadata, all managed components carry information about the components and resources they were built against. The runtime uses this information to ensure that your component or application has the specified versions of everything it needs, which makes your code less likely to break because of some unmet dependency. Registration information and state data are no longer stored in the registry where they can be difficult to establish and maintain. Rather, information about the types you define (and their dependencies) is stored with the code as metadata, making the tasks of component replication and removal much less complicated. Language compilers and tools expose the runtime's functionality in ways that are intended to be useful and intuitive to developers. This means that some features of the runtime might be more noticeable in one environment than in another. How you experience the runtime depends on which language compilers or tools you use. For example, if you are a Visual Basic developer, you might notice that with the common language runtime, the Visual Basic language has more objectoriented features than before. Following are some benefits of the runtime:
• • • •

Performance improvements. The ability to easily use components developed in other languages. Extensible types provided by a class library. New language features such as inheritance, interfaces, and overloading for object-oriented programming; support for explicit free threading that allows creation of multithreaded, scalable applications; support for structured exception handling and custom attributes.

If you use Microsoft Visual C++.NET, you can write managed code using the Managed Extensions for C++, which provide the benefits of a managed execution environment as well as access to powerful capabilities and expressive data types that you are familiar with. Additional runtime features include:

2

SUNSAT The Perfect Team

Microsoft .Net
• • • •

Cross-language integration, especially cross-language inheritance. Garbage collection, which manages object lifetime so that reference counting is unnecessary. Self-describing objects, which make using Interface Definition Language (IDL) unnecessary. The ability to compile once and run on any CPU and operating system that supports the runtime.

Common Type System (CTS) Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution. Common Language Specification (CLS) The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. ASP.NET ASP.NET is the latest version of ASP. It includes Web Services to link applications, services and devices using HTTP, HTML, XML and SOAP. New in ASP.NET:
• • • • • • • • • • • •

New Language Support Programmable Controls Event Driven Programming XML Based Components User Authentication User Accounts and Roles High Scalability Compiled Code Easy Configuration Easy Deployment Not ASP Compatible Includes ADO.NET

Visual Basic.NET Visual Basic.NET has added language enhancements, making it a full object-oriented programming language.

3

SUNSAT The Perfect Team

Microsoft .Net
C# C# is a new computer programming language developed by Microsoft Corporation, USA. C# is a fully object – oriented language like JAVA. It has been developed to support the key features of .Net framework. SQL Server 2000 SQL Server 2000 is a fully web-enabled database. SQL Server 2000 has strong support for XML and HTTP which are two of the main infrastructure technologies for .NET. Some of the most important new SQL Server features are direct access to the database from a browser, query of relational data with results returned as XML, as well as storage of XML in relational formats. Internet Information Services 6.0 IIS 6.0 has strong support for more programming to take place on the server, to allow the new Web Applications to run in any browser on any platform. What are Web Services?
• • • • • •

Web services are small units of code Web services are designed to handle a limited set of tasks Web services use XML based communicating protocols Web services are independent of operating systems Web services are independent of programming languages Web services connect people, systems and devices

Benefits of Web Services
• • • •

Easier to communicate between applications Easier to reuse existing services Easier to distribute information to more consumers Rapid development

Web services make it easier to communicate between different applications. They also make it possible for developers to reuse existing web services instead of writing new ones. Web services can create new possibilities for many businesses because it provides an easy way to distribute information to a large number of consumers. One example could be flight schedules and ticket reservation systems.

4

SUNSAT The Perfect Team

Microsoft .Net

C Sharp
C# is a new computer programming language developed by Microsoft Corporation, USA. C# is a fully object – oriented language like JAVA. It has been developed to support the key features of .Net framework. It is a simple, efficient, productive and type-safe language derived from popular C and C++ languages. Although it belongs to the family of C / C++ , it is a purely object oriented, modern language suitable for developing web based applications. Major Features 1) It is a brand new language derived from the c / c++ family 2) It simplifies and modernizes c++ 3) Major parts of .Net framework are actually coded in c# Applications of C# 1) 2) 3) 4) 5) 6) Console application Windows application Developing windows controls Developing ASP.Net projects Creating Web Controls Providing web services

C++ Features Dropped 1) 2) 3) 4) 5) 6) 7) 8) 9) Macros Multiple Inheritance Templates Pointers Global Variables Typedef statement Default Arguments Constant member functions or parameters Forward declaration of classes

Enhancements to C++ C# Modernizes C++ by adding the following new features: 1) 2) 3) 4) 5) 6) Automatic Garbage Collection Strict type-safety Properties to access data members Delegates and events Boxing and unboxing Web services

Characteristics of C#

5

SUNSAT The Perfect Team

Microsoft .Net
C# is designed for both computing and communications is characterized by several key features. It is • • • • • Simple Consistent Modern Object-oriented Type-safe

Simple

C# Simplifies C++ by eliminating operators such as ->,:: and pointers. Consistent C# supports a unified type system which eliminates the problem of varying of integer types. All types are treated as objects and developers can extend the type system simply and easily. Modern C# is called a modern language due to a number of features it supports. It supports, • • • • • Automatic Garbage Collection Rich intrinsic model for error handling Decimal data type for financial Applications. Modern approach to debugging and Robust security model

Object – oriented C# is truly object oriented. It supports all the three tenets of object oriented systems, namely • • • Encapsulation Inheritance and Polymorphism

The entire c# class model is built on top of the Virtual Object System (VOS) of the .Net Framework. In c#, everything is an object. Type-Safe Type – Safety promotes robust programs. C# incorporates a number of type-safe measures. • • • • • All dynamically allocated objects and arrays are initialized to zero. Use of any unintialized variables produces an error message by the compiler. Access to arrays is range-checked and warned if it goes out-of-bounds. C# enforces overflow checking in arithmetic operations. C# supports automatic Garbage Collection.

6

SUNSAT The Perfect Team

Microsoft .Net
A First C# Program: 'Hello World' Let's begin in the traditional way, by looking at the code of a Hello World program using System; public class HelloWorld { public static void Main() { // This is a single line comment /* This is a multiple line comment */ Console.WriteLine("Hello World!"); } } The first thing to note about C# is that it is case-sensitive. You will therefore get compiler errors if, for instance, you write 'console' rather than 'Console'. The second thing to note is that every statement finishes with a semicolon (;) or else takes a code block within curly braces. Class Declaration: C# is a true object oriented language and therefore everything must be placed inside a class. Class is a keyword and declares a new class definition. The Braces: C# is a block-structured language, meaning code blocks are always enclosed by braces { and }. The Main Method: public static void Main( ) define a method named Main. Every C# executable program must include the Main method in one of the classes. This is the starting point for the execution of the program. A C# application can have any number of classes but ‘only one’ class can have the Main method to initiate the execution. public – is a access modifier that tells the C# compiler that the main method is accessible by anyone.

7

SUNSAT The Perfect Team

Microsoft .Net
static – the keyword static declares that the Main method is a global one and can be called without creating an instance of the class. void - is a type modifier that states the Main method does not return any value. Interactive Console Input using System; class Sample { public static void Main( ) { Console.Write(“Enter your Name : “); string Name = Condole.ReadLine( ); Console.Write(“Enter your Pin No : “); int pinno = int.Parse(Condole.ReadLine( )); Console.WriteLine(“ Welcome “ + Name); Console.WriteLine(“ Your Pin is “ + pinno); } } Variable Types: Reference Types and Value Types C# is a type-safe language. Variables are declared as being of a particular type, and each variable is constrained to hold only values of its declared type. Variables can hold either value types or reference types, or they can be pointers. Here's a quick recap of the difference between value types and reference types. - where a variable v contains a value type, it directly contains an object with some value. No other variable v' can directly contain the object contained by v (although v' might contain an object with the same value). - where a variable v contains a reference type, what it directly contains is something which refers to an object. Another variable v' can contain a reference to the same object refered to by v.

8

SUNSAT The Perfect Team

Microsoft .Net
Value Types It is possible in C# to define your own value types by declaring enumerations or structs. These user-defined types are mostly treated in exactly the same way as C#'s predefined value types, although compilers are optimised for the latter. The following table lists, and gives information about, the predefined value types. Because in C# all of the apparently fundamental value types are in fact built up from the (actually fundamental) object type, the list also indicates which System types in the .Net framework correspond to these pre-defined types. C# Type sbyte short int long byte ushort uint ulong float double .Net Framework (System) type System.Sbyte System.Int16 System.Int32 System.Int64 System.Byte System.Uint16 System.UInt32 System.Uint64 System.Single System.Double Signed? Bytes Occupied Yes Yes Yes Yes No No No No Yes Yes 1 2 4 8 1 2 4 8 4 8 Possible Values -128 to 127 -32768 to 32767 -2147483648 to 2147483647 -9223372036854775808 to 9223372036854775807 0 to 255 0 to 65535 0 to 4294967295 0 to 18446744073709551615 Approximately ±1.5 x 10-45 to ±3.4 x 1038 with 7 significant figures Approximately ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 significant figures Approximately ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 significant figures Any Unicode character (16 bit) true or false

decimal System.Decimal char bool System.Char System.Boolean

Yes N/A N/A

12 2 1/2

In the following lines of code, two variables are declared and set with integer values. int x = 10; int y = x; y = 20; // after this statement x holds value 10 and y holds value 20 Reference Types The pre-defined reference types are object and string, where object - as we have mentioned above - is the ultimate base class of all other types. New reference types can be defined using 'class', 'interface', and 'delegate' declarations. Reference types actually hold the value of a memory address occupied by the object they reference. Consider the following piece of code, in which two variables are given a reference to

9

SUNSAT The Perfect Team

Microsoft .Net
the same object (for the sake of the example, this object is taken to contain the numeric property 'myValue'). object x = new object(); x.myValue = 10; object y = x; y.myValue = 20; // after this statement both x.myValue and y.myValue equal 20 This code illustrates how changing a property of an object using a particular reference to it is reflected in all other references to it. Note, however, that although strings are reference types, they work rather more like value types. When one string is set to the value of another, eg string s1 = "hello"; string s2 = s1; Then s2 does at this point reference the same string object as s1. However, when the value of s1 is changed, for instance with s1 = "goodbye"; what happens is that a new string object is created for s1 to point to. Hence, following this piece of code, s1 equals "goodbye", whereas s2 still equals "hello". The reason for this behavior is that string objects are 'immutable'. That is, the properties of these objects can't themselves change. So in order to change what a string variable references, a new string object must be created. Boxing C# allows you convert any value type to a corresponding reference type, and to convert the resultant 'boxed' type back again. The following piece of code demonstrates boxing. When the second line executes, an object is initiated as the value of 'box', and the value held by i is copied across to this object. It is interesting to note that the runtime type of box is returned as the boxed value type; the 'is' operator thus returns the type of box below as 'int'. int i = 123; object box = i; if (box is int) {Console.Write("Box contains an int");} // this line is printed Unboxing Unboxing is the process of converting the object type back to the value type. Remember that we can only unbox a variable that has previously been boxed. Casting There are many conversions that cannot be implicitly made between types. If we attempt such conversions, the compiler will give an error message. For example the following conversions cannot be made implicitly: 1) int to short 2) float to int

10

SUNSAT The Perfect Team

Microsoft .Net
3) any numeric type to char etc., However, we can explicitly carry out such conversions using the cast operator. This process is known as casting. type variable1 = (type) variable2; Example: long x = 1234L; int y = ( int ) x; double x =89.77; double y =667.09; int x = (int) (x+0.5); // x = 90 int y = (int) (y+0.5); // y = 667 Constants Constants are unchanging types, associated with classes that are accessible at compile time. Because of this latter fact, constants can only be value types rather than reference types.Constant declarations take the 'const' keyword (not 'static', even though they are associated with classes), and the five modifiers 'public', 'protected', 'internal', 'private' and 'new'. The following is a simple constant declaration, although multiple constants can be simultaneously declared. public const int area = 4; C# provides a number of the common loop statements: while loops syntax: while (expression) statement[s] A 'while' loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the boolean expression returns false. For instance, the following code int a = 0; While (a < 3) { System.Console.WriteLine(a); a++; }

11

SUNSAT The Perfect Team

Microsoft .Net
produces the following output: 0 1 2 do-while loops syntax: do statement[s] while (expression) A 'do-while' loop is just like a 'while' loop except that the condition is evaluated after the block of code specified in the 'do' clause has been run. So even where the condition is initially false, the block runs once. For instance, the following code outputs '4': int a = 4; Do { System.Console.WriteLine(a); a++; } while (a < 3);

for loops syntax: for (statement1; expression; statement2) statement[s]3 The 'for' clause contains three parts. Statement1 is executed before the loop is entered. The loop which is then executed corresponds to the following 'while' loop: statement1 while (expression) {statement[s]3; statement2} 'For' loops tend to be used when one needs to maintain an iterator value. Usually, as in the following example, the first statement initialises the iterator, the condition evaluates it against an end value, and the second statement changes the iterator value. 1. 2. 3. 4. foreach loops syntax: foreach (variable1 in variable2) statement[s] for (int a =0; a<5; a++) { System.Console.WriteLine(a); }

12

SUNSAT The Perfect Team

Microsoft .Net
The 'foreach' loop is used to iterate through the values contained by any object which implements the IEnumerable interface. When a 'foreach' loop runs, the given variable1 is set in turn to each value exposed by the object named by variable2. As we have seen previously, such loops can be used to access array values. So, we could loop through the values of an array in the following way: 1. 2. 3. int[] a = new int[]{1,2,3}; foreach (int b in a) System.Console.WriteLine(b);

The main drawback of 'foreach' loops is that each value extracted (held in the given example by the variable 'b') is read-only. Selection Statements if - else 'If-else' statements are used to run blocks of code conditionally upon a boolean expression evaluating to true. The 'else' clause, present in the following example, is optional. 1. 2. 3. 4. if (a == 5) System.Console.WriteLine("A is 5"); Else System.Console.WriteLine("A is not 5");

If statements can also be emulated by using the conditional operator. The conditional operator returns one of two values, depending upon the value of a boolean expression. To take a simple example, the line of code int i = (myBoolean) ? 1 : 0 ; sets i to 1 if myBoolean is true, and sets i to 0 if myBoolean is false. The 'if' statement in the previous code example could therefore be written like this: 1. switch - default 'Switch' statements provide a clean way of writing multiple if - else statements. In the following example, the variable whose value is in question is 'a'. If a equals 1, then the output is 'a>0'; if a equals 2, then the output is 'a>1 and a>0'. Otherwise, it is reported that the variable is not set. System.Console.WriteLine( a==5 ? "A is 5" : "A is not 5");

13

SUNSAT The Perfect Team

Microsoft .Net

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

switch(a) { Case 2: Console.WriteLine("a>1 and "); goto case 1; Case 1: Console.WriteLine("a>0"); break; default: Console.WriteLine("a is not set"); break; }

Each case (where this is taken to include the 'default' case) will either have code specifying a conditional action, or no such code. Where a case does have such code, the code must (unless the case is the last one in the switch statement) end with one of the following statements: break; goto case k; (where k is one of the cases specified) goto default; From the above it can be seen that C# 'switch' statements lack the default 'fall through' behaviour found in C++ and Java. However, program control does fall through wherever a case fails to specify any action. The following example illustrates this point; the response "a>0" is given when a is either 1 or 2.

14

SUNSAT The Perfect Team

Microsoft .Net
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Jump Statements Break The 'break' statement breaks out of the 'while' and 'for' loops and the 'switch' statements. The following code gives an example - albeit a very inefficient one - of how it could be used. The output of the loop is from 0 to 4. int a=0; while(true) { System.Console.writeline(a); a++; if(a==5) break; } continue The 'continue' statement can be placed in any loop structure. When it executes, it moves the program counter immediately to the next iteration of the loop. The following code example uses the 'continue' statement to count the number of values between 1 and 100 inclusive that are not multiples of seven. At the end of the loop the variable y holds the required value. int y =0; for(int x=0;x < 101 ; x++) { if ((x%7) = = 0) continue; y++; } goto switch(a) { Case 1: Case 2: Console.WriteLine("a>0"); break; default: Console.WriteLine("a is not set"); break; }

15

SUNSAT The Perfect Team

Microsoft .Net
The 'goto' statement is used to make a jump to a particular labelled part of the program code. It is also used in the 'switch' statement described below. We can use a 'goto' statement to construct a loop, as in the following example (but again, this usage is not recommended): int a = 0; start: system.console.writeline(a); a++; if(a<5) goto start; Declaring Methods Modifiers type method name (formal-parameter-list) { Method body } Method declaration has five parts: 1) Name of the method (method name) 2) Type of value the method returns (type) 3) List of parameters (formal-parameter-list) 4) Body of the method 5) Method modifiers (modifier) Modifiers: Public – The method can be accessed from any where, including outside the class Protected – The method can be accessed from within the class to which it belongs, or a type derived from that class. Private – The method can only be accessed from inside the class to which it belongs. Static – The method does not operate on a specific instance of the class. Example 1: using system; class methodex { int cube(int x) { return(x * x * x); } } class methodtest { public static void Main( ) { methodex m = new methodex; int y = m.cube(5); system.console.writeline(y);

16

SUNSAT The Perfect Team

Microsoft .Net
} } Example 2: using system; class statictest { public static void Main( ) { double y = square(2.5F); system.console.writeline(y); } static double square(float x) { return(x * x); } } Nesting of methods: using system; class nesting { void largest(int n, int m) { int large= max(m,n); system.console.writeline(large); } int max( int a, int b) { int x = (a > b) ? a : b; return(x); } } class nestingtest { public static void Main( ) { nesting N = new nesting(); N.largest(100,200); } } Read – Only Members ‘Read – Only’ modifier is used to set the value for the constant member at runtime and also to have different value for different object of the class. Value can be set to the member using a constructor method, but cannot be modified later.

17

SUNSAT The Perfect Team

Microsoft .Net
‘Read – Only’ member may be declared as either static or instance fields. If instance they have different values with different objects. class Number { public readonly int m; public static readonly int n; public Number( int x) { m = x; } static Numbers( ) { n = 100; } }

Pass By Value By default method parameters are passed by value. That is, a parameter declared with no modifier is passed by value and is called a value parameter. When a method is invoked, the values of actual parameters are assigned to the corresponding formal parameters. The value parameters can be changed within the methods. using System; class Test { static void TestMtd ( int M) { M + = 10; } public static void Main( ) { int x = 23; TestMtd( x ); Console.WriteLine( “ X = “ + x); } } This program will produce the output X = 23; When the method TestMtd( ) is invoked, the value of x is assigned to M and a new location for M is created in the memory. Therefore, any change in M does not affect the value stored in the location x. Pass By Reference

18

SUNSAT The Perfect Team

Microsoft .Net
We can use the ref keyword to force the value parameters to be passed by reference. A parameter declared with ref modifier is a reference parameter. void Modify ( ref int x ) Here, x is declared as a reference parameter. Unlike a value parameter, a reference parameter does not create a new storage location. Instead, it represents the same storage location as the actual parameter used in the method invocation. When a formal parameter is declared as ref, the corresponding argument in the method invocation must also be declared as ref. void Modify ( ref int x ) { x + = 0; } ……… int m = 5; Modify ( ref m ) ; ………. Variable Argument Lists In c# we can define methods that can handle variable number of arguments using what are known as parameter arrays. Parameter arrays are declared using the keyword params. using system; class paramstest { static void parray(params int [] arr) { system.console.write(“Array elements are : “); foreach (int i in arr) system.console.write(“ “ + arr[i]); system.console.writeline(); } public static void Main( ) { int [] x = { 11, 12 ,13}; parray(x); parray(); parray(100,200); } } Method Overloading C# allows us to create more than one method with the same name, but with the different parameter lists and different definitions. This is called method overloading. Method overloading is used when methods are required to perform similar tasks but using different input parameter. using system; class overloading

// value of m will be changed // m is initialized //pass by reference

19

SUNSAT The Perfect Team

Microsoft .Net
{ public static void main() { system.console.writeline(volume(10)); system.console.writeline(volume(2.5F,8)); system.console.writeline(volume(100L,75,15)); } static int volume(int x) { return(x * x * x); // cube } static double volume(float r,int h) { return(3.14 * r * r * h); // cylinder } static long volume(long l, int b, int h) { return(l * b * h); //box } } Arrays Single-Dimensional Arrays The type of each array declared is given firstly by the type of basic elements it can hold, and secondly by the number of dimensions it has. Single-dimensional arrays have a single dimension (ie, are of rank 1). They are declared using square brackets, eg: int[] i = new int[100]; This line of code declares variable i to be an integer array of size 100. It contains space for 100 integer elements, ranging from i[0] to i[99]. To populate an array one can simply specify values for each element, as in the following code: int [] i = new int[2]; i[0]=1; i[1]=2; One can also run together the array declaration with the assignment of values to elements using int[] i = new int[] {1,2}; or the even shorter version of this: int[] i = {1,2};

20

SUNSAT The Perfect Team

Microsoft .Net
Rectangular Arrays C# supports two types of multidimensional arrays: rectangular and jagged. A rectangular array is a single array with more than one dimension, with the dimensions' sizes fixed in the array's declaration. The following code creates a 2 by 3 multi-dimensional array: int[,] squareArray = new int[2,3]; As with single-dimensional arrays, rectangular arrays can be filled at the time they are declared. For instance, the code int [,] squareArray = {{1, 2, 3}, {4, 5, 6}}; creates a 2 by 3 array with the given values. It is, of course, important that the given values do fill out exactly a rectangular array. Variable size Arrays: C# treats multidimensional arrys as ‘arrys of arrays’. It is possible to declare a two-dimensional array as follows: int [ ] [ ] sam = new int [ 3] [ ] ; sam[0] = new int[2] ; sam[1] = new int[4] ; sam[2] = new int[3] ; Variable size arrays are called jagged arrays. The elements can be accessed as follows: sam [1] [1] = 10; In C#, every array we create is automatically derived from the System.Array class. Some commonly used methods of System.Array class are Clear ( ) – Sets a range of elements to empty values. CopyTo ( ) – Copies elements from the source array into the destination array. GetLength( ) – Gives the number of elements in a given dimension of the array GetValue( ) – Gets the value for a given index in the array Length – Gives the length of an array SetValue( ) – Sets the value for a given index in the array //three rows array // first row has two elements //second row has four elements //third row has three elements

21

SUNSAT The Perfect Team

Microsoft .Net
Reverse( ) – Reverses the contents of a one-dimensional array Sort( ) – Sorts the elements in a one-dimensional array. Array List Class System.Collections namespace defines a class know as Arraylist that can store a dynamically sized array of objects. An arraylist is very similar to an array, except that it has the ability to grow dynamically. ArrayList country = new ArrayList( ); Elements can be added to an array list as follows: countries.Add(“India”); countries.Add(“Australia”); Some of the properties / methods of an Array list: Add( ) – Adds an element to the Array list. Clear( ) – removes all the elements from the list Contains( ) – determines if an element is in the list CopyTo( ) - copies an list to another Remove( ) – removes the first occurrence of an element RemoveAt( ) – removes the element at the specifies place. Sort( ) – sorts the elements. Count – gets the number of elements currently in the list. Example: using Sytsem; using System.Collections; class ArrayTest { public static void Main( )

22

SUNSAT The Perfect Team

Microsoft .Net
{ ArrayList country = new ArrayList( ); country.Add(“India”); country.Add(“Iran”); country.Add(“Australia”); country.Add(“China”); Console.WriteLine(“Elements Present = “ + country.count); country.Sort( ); int i; for(i = 0; i < country.count; i++) Console.WriteLine(country[i]); Console.WriteLine( ); country.RemoveAt(2); for(i = 0; i < country.count; i++) Console.WriteLine(country[i]); } } Strings The most common way to create a string is to assign a quoted string of characters known as string literal to a string object. For example, string Strtest; Strtest = “test”; Both these elements may be combined into one as follows: string Strtest = “test” ; Manipulating Strings:

23

SUNSAT The Perfect Team

Microsoft .Net
Copying Strings: Two ways: 1)Using the overloaded = operator 2)Using the static Copy method Example: string s2 = s1; string s2 = string.Copy(s1); Concatenating Strings Two Ways: 1)Using the overloaded + operator 2)Using the static Concat method Example: string s3 = s1 + s2 string s3 = string.Concat(s1,s2) The ToString Method The another way of creating a string is to call the ToString method on an object and assign the result to a string variable. int number = 123; int newnumber= number + 1; string numStr = number.ToString(); string newStr= number.ToString() + 1; This statement converts the number 123 to a string '123' and then assigns the string value to the string variable numStr. String Methods: Method Compare() ConCat() Copy() EndsWith() Equals() Insert() Remove() Operation Compares two strings Concatenates two or more strings Creates a new string by copying another Determines whether a substring exists at the end of the string Determines if two strings are equal Returns a new string with a substring inserted at a specified location. Deletes characters from the string

24

SUNSAT The Perfect Team

Microsoft .Net
Replace() Split() Substring() ToLower() ToUpper() Inserting String: using System; class strtest { public static void Main() { string s1="Hi"; string s2 = s1.Insert(1,"a"); String s3 = s2.Insert(3,"Hello"); System.console.writeLine(s3); } } Compare Method: There are two versions of overloaded static Compare method. The first one takes two strings as parameters and compare them. Example: int n = string.Compare(s1,s2); This performs a case-sensitive comparison and returns different integer values for different conditions: 1) Zero integer, if s1 equal to s2 2) A positive integer (1), if s1 is greater than s2 3) A negative integer (-1), if s1 is less than s2 We can use such comparison statements in if statements like: If ( string.Compare(s1,s2) = = 0 ) Console.WriteLine(“ They are Equal”); Replaces all instances of a character with a new character Creates an array of strings by splitting the string at any occurrence of one or more characters Extracts a substring Returns a lower-case version of the string Returns a upper-case version of the string

25

SUNSAT The Perfect Team

Microsoft .Net
The second version of Compare takes an additional bool type parameter to decide whether case should be ignored or not. If the bool parameter is true, case is ignored. int n = string.Compare(s1,s2,true); Equals Methods: There are two versions of Equals method. They are implemented as follows: bool b1 = s2.Equals(s1); bool b2 = string.Equals(s2,s1); These methods return a Boolean value true if s1 and s2 are equal, otherwise false. The = = operator: A simple and natural way of testing the equality of strings is by using the overloaded = = operator. bool b1 = ( s1 = = s2); we very often use such statements in decision statements, like if ( s1 = = s2) Console.WriteLine(“They are Equal”); Finding Substrings It is possible to extract substrings from a given string using the overloaded Substring method available in string class. There are two version of Substring: 1) s.Substring(n) 2) s.Substring(n1,n2) The first one extracts a substring starting from the nth position to the last character of the string contained in s. The second one extracts a substring from s beginning at n1 position and ending at n2 position. Example: string s1 = “New York” string s2 = s1.Substring(5); string s3 = s1.Substring(0,3); string s4 = s1.Substring(5,8); Arrays Of Strings: Creation of string array:

26

SUNSAT The Perfect Team

Microsoft .Net
string [ ] itemarray = new string [3]; string [ ] itemarray = { “ASP.Net” , “VB.Net” , “C#” }; using system; class strtest { public static void Main() { string [ ] countries = { “India” , “Germany” , “America” , “France” } int n = countries.Length; Array.sort(countries); For(int i = 0 ; I < n; i++) { system.console.WriteLine(countries[i]); } system.console.WriteLine(); Array.Reverse(countries); For(int i = 0; i < n; i ++) { system.console.WriteLine(countries[i]); }}} This Reference C# supports the keyword this which is a reference to the object that called the method. The this reference is available within all the member methods and always refers to the current instance. It is normally used to distinguish between local and instance variables that have the same name. Example: class Test { int x, y; public static void SetXY(int x, int y) { this.x = x; this.y = y; }

27

SUNSAT The Perfect Team

Microsoft .Net
…………. …………. } in the assignment statements, this.x and this.y refer to the class members named x and y whereas simple x and y refers to the parameters of the SetXY( ) method. Constructors Constructors enable an object to initialize itself when it is created. Constructors have the same name as the class itself. They do not specify a return type, not even void. This is because they do not return any value. using system; class Rectangle { public int length, width; public Rectangle ( int x , int y ) { length = x ; width = y ; } public int RectArea( ) { return ( length * width ); } } class RectangleArea { public static void Main( ) { // Definig Constructor

28

SUNSAT The Perfect Team

Microsoft .Net
Rectangle rect1 = new Rectangle ( 10, 15); int area1 = rect1.RectArea( ); Console.WriteLine(“ Area = “ + area1); } } Overloaded Constructor To create an overloaded constructor method, all we have to do is to provide several different constructor definitions with different parameter lists. The difference may be in either the number of type of arguments. That is, each parameter list should be unique. Class Room { public double length, width; public Room (double x, double y) { length = x; width = y; } public Room ( double x) { length = width = x; } public int Area( ) { return( length * width ) ; } // constructor 2 // constructor 1

29

SUNSAT The Perfect Team

Microsoft .Net
} Here, we are overloading the constructor method Room( ). An object representing a rectangular room will be created as Room objRoom1 = new Room(12.3, 34.5) ; // using constructor 1 On the other hand, if the room is square then we may create the corresponding object as Room objRoom2 = new Room(66.3) ; // using constructor 2 The Destructor While a constructor is a method used to initialize an instance of a class, a destructor is used to destruct an instance of class when that variable is not used anymore. Like the constructor, the destructor has the same name as the class. To indicate that the method is a destructor, its name is preceded with a tilde. Here is an example of a destructor in a class: using System; class SampleClass { // Constructor public SampleClass() { Console.WriteLine("SampleClass - Constructor"); } ~SampleClass () { Console.WriteLine("Destructor of SampleClass"); } } public class NewProject { static void Main() { SampleClass Sample = new SampleClass(); Console.WriteLine(); } } This would produce: SampleClass - Constructor

30

SUNSAT The Perfect Team

Microsoft .Net

Destructor of SampleClass Like a (default) constructor, a destructor is automatically created for your class but you can also create it if you want. A class can have only one constructor. If you don't create it, the compiler would create it for your class. If you create it, the compiler would not create another. A destructor cannot have an access level. A destructor is called when the memory that a class was used is no longer needed. This is done automatically by the compiler. For this reason, you will hardly need to create a constructor, since its job is automatically taken care of behind the scenes by the compiler. Inheritance C# class can be reused in several ways. Reusability is achieved by designing new classes, reusing all or some of the properties of existing ones. The mechanism of designing or constructing one class from another is called inheritance. Inheritance can be classified as two: 1) Classical Inheritance 2) Containment Inheritance Classical Inheritance: Inheritance represents a kind of relationship between two classes. Let us consider two classes A and B. we can create a class hierarchy such that B is derived from A.

Class A

Class B
Class A, the initial class that is used as the basis for the derived class is referred to as the base class, parent class or super class. Class B, the derived class, is referred to as derived class, child class or sub class. A derived class is a completely new class that incorporates all the data and methods of its base class. It can also have its own data and method members that are unique to itself. That is, it can enhance the content and behavior of the base class. Inheritance may be implemented in different combinations as follows: Single Inheritance – Only one base class Hierarchical Inheritance – One base class and many subclasses Multilevel Inheritance – Derived from a derived Class. Multiple Inheritance – Several base classes.

31

SUNSAT The Perfect Team

Microsoft .Net

A

A

B

B

C

D

A

A

B

B C C
C# does not directly implement multiple inheritances. However, this concept is implemented using a secondary inheritance path in the form of interfaces. Containment Inheritance: We can also define another form of inheritance relationship known as containership between class A and class B. Example: class A { …… } class B { ……

32

SUNSAT The Perfect Team

Microsoft .Net
A a ; // a is contained in b } Bb; In such cases, we say that the object a is contained in object b. This relationship between a and b is referred to as ‘ has – a ‘ relationship. The outer class B which contains the inner class A is termed as the parent class and the contained class A is termed as a ‘child‘class. Simple inheritance: using system; class Item { public void Company( ) { system.console.WriteLine(“Item Code = XXX”); } } class Fan : Item { public void model ( ) { system.console.WriteLine(“ Fan Model : Classic “); } } class simple { public static void Main ( ) { Item item = new Item ( ); Fan fan = new Fan ( ); item.Company ( ); fan.Company ( ); fan.model ( ); } } Application of single inheritance: using system; class Room { public int Length; public int Breath; public Room (int x ,int y) //base class constructor { Length = x; Breath = y; }

33

SUNSAT The Perfect Team

Microsoft .Net
public int Area ( ) { return (Length * Breath ) ; } } class BedRoom : Room // Inheriting Room { int height; public BedRoom ( int x, int y, int z) : base(x,y) { height = z; } public int volume ( ) { return ( Length * Breath * height); } } class InTest { public static void Main ( ) { BedRoom room1 = new BedRoom(14,12,10); int area1 = room1.Area(); // superclass method int volume1 = room1.volume(); //subclass method system.console.writeLine ( “ Area1 = “ + area1); system.console.writeLine(“Volume1 = “ + volume1); } } Interfaces: Multiple Inheritance C# provides an alternate approach known as interface to support the concept of multiple inheritance. An interface in c# is basically a kind of class with some differences. Major differences include: 1) All members of an interface are implicitly public and abstract. 2) An interface cannot contain constant fields, constructors and destructors. 3) Its members cannot be declared as static. 4) Since the methods in a interface are abstract, they do not include implementation code. 5) An interface can inherit multiple interfaces. Defining an Interface: An interface contains one or more methods but none of them are implemented in the interface itself. It is the responsibility of the class that implements the interface to define the implementation code for these members. The general form of an interface definition is: interface interface-name

34

SUNSAT The Perfect Team

Microsoft .Net
{ Member declaration; } Example: interface Show { void Display ( ); } The accessibility of an interface can be controlled using modifiers public, protected, internal and private. Extending an interface: Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other interfaces. The new sub interface will inherit all the members of the super interface in the manner similar to sub classes. interface name2 : name1 { members of name2; } Example: We can put all the methods of particular behavior category in one interface and the members of another category in the other. interface Addition { int Add ( int x, int y) ; } interface Compute : Addition { int Sub ( int x , int y) ; } The interface Compute will have both the methods and any class implementing the interface Compute should implement both of them; otherwise, it is an error We can also combine several interfaces together into a single interface. Following declarations are valid: iterface I1 { ---} interface I2

35

SUNSAT The Perfect Team

Microsoft .Net
{ ----} interface I3 : I1, I2 //multiple inheritance { --------} While interfaces are allowed to extend other interfaces , subinterfaces cannot define the methods declared in the supreinterfaces. Implementing interfaces: Interfaces are used as ‘superclasses ‘ whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. This is done as follows: class classname : interfacename { body of classname } Implementation of multiple interfaces: using system; interface Addition { int Add ( ) ; } interface Multiplication { int Mul ( ) ; } class Computation : Addition , Multiplication { int x , y; public Computation ( int x, int y) { this.x = x; this.y = y; } public int Add ( ) { return ( x + y ); } public int Mul ( ) { return ( x * y); } }

36

SUNSAT The Perfect Team

Microsoft .Net
class interTest { public static void Main ( ) { Computation com = new Computation ( 10, 20); Addition add = (Addition) com; System.Console.WriteLine ( “Sum = “ + add.Add( )); Multiplication mul = (Multiplication) com; System.Console.WriteLine (“Product = “ + mul.Mul ( ) ); } } Interfaces and Inheritance: Inheriting a class that implements an interface: using system; interface Display { void print ( ); } class B : Display // implements display { public void print ( ) { system.Console.WriteLine ( “Base Display “); } } class D : B // inherits b class { public new void print ( ) { system.Console.WriteLine ( “ Derived Display”); } } class test { public static void Main( ) { D d = new D ( ); d.print ( ); Display dis = (Display) d; Dis.print( ); }

37

SUNSAT The Perfect Team

Microsoft .Net
} The use of modifier new in the derived class “hides” the print method implemented in the base class. Abstract Classes In a number of hierarchical applications, we would have one base class and a number of different derived classes. The top-most base class simply acts as a base for others and is not useful on its own. In such situations, we might not want any one to create its objects. We can do this by making the base class abstract. The abstract is a modifier and when used to declare a class indicates that the class cannot be instantiated. Only its derived (that are not marked abstract) can be instantiated. Some characteristics of an abstract class are: 1) It cannot be instantiated directly 2) It can have abstract members 3) We cannot apply a sealed modifier to it abstract class Base { ……………… } class Derived : Base { ……….. } …………. …………. Base b; //Error Derived d; //ok Abstract Methods Similar to abstract classes, we can also create abstract methods. Where as instance method declaration includes the modifier abstract, the method is said to be an abstract method An abstract method is implicitly a virtual method and does not provide any implementation. Therefore, an abstract method does not have method body. Example: public abstract void Draw(int x ,int y); It can be declared only in abstract classes, it cannot take either static or virtual Modifier. Its implementation must be provided in non-abstract derived classes by overriding the method.

38

SUNSAT The Perfect Team

Microsoft .Net
Sealed Classes: Preventing Inheritance Sometimes, we may like to prevent a class being further subclassed for security reasons. A class that cannot be subclassed is called a sealed class. This is achieved in C# using the modifier sealed as follows: sealed class Aclass { ……….. } sealed class Bclass : Dclass { ………….. } Any attempt to inherit these classes will cause an error and the compiler will not allow it. Declaring as class sealed prevents any unwanted extensions to the class. A sealed class cannot be an abstract class. Sealed Methods: When an instance method declaration includes the sealed modifier, the method is said to be a sealed. It means a derived class cannot override this method. A sealed modifier is used to override an inherited virtual method with the same signature. This means, the sealed modifier is always used in combination with the override modifier. Example: class A { public virtual void Fun ( ) { ……….. } } class B : A { public sealed override void Fun ( ) { ………. } }

39

SUNSAT The Perfect Team

Microsoft .Net
The sealed method Fun ( ) overrides the virtual method Fun ( ) defined in Class A. Any derived class of B cannot further override the method Fun ( ).

Overriding Methods We have seen that a method defined in a super class is inherited by its subclass and is used by the objects created by the sub class. Method inheritance enables us to define and use methods repeatedly in sub classes. However, there may be some occasions when we want an object to respond to the same method but behave differently when that method is called. That means, we should override the method defined in the super class. This I possible by defining a method in the sub class that has the same name, same arguments and same return type as a method in the super class. Then, when that method is called, the method defined in the subclass is invoked and executed instead of the one in the super class, provided that: 1) We specify the method in the base class as virtual 2) Implement the method in subclass using the keyword override. This is known as overriding. Example: using system; class Super { protected int x; public Super ( int x ) { this.x=x; } public virtual void Display ( ) // method defined with virtual { system.console.writeLine(“Super x = “ + x ); } } class Sub : Super { int y; public Sub ( int x, int y) : base(x) { this.y = y; } public override void Display ( ) // method defined again with override { system.Console.WirteLine(“Super x = “ + x); system.Console.WriteLine(“Sub y = “ + y); } }

40

SUNSAT The Perfect Team

Microsoft .Net
class Test { public static void Main ( ) { Sub s1 = new Sub (100,200); s1.Display ( ); } } Structures Structures are similar to classes in c#. Although classes will be used to implement most objects, it is desirable to use structs where simple composite data types are required. Defining a Struct: A struct in c# provides a unique way of packing together data to different types. It is a convenient tool for handling a group of logically related data items. It creates a template that may be used to define its data properties. Example: struct Student { public string Name; public int RollNo; public double TotalMarks; } The keyword struct declares Student as a new data type that hold three variables of different data types. These variables are known as members or fields or elements. The identifier Student can now be used to create variables of type Student. Example: Student s1; s1 is a variable of type Student and has three member variables as defined by the template. Assigning Values to Members: Member variables can be accessed using the simple dot notation as follows: s1.Name = “John” ; s1.RollNo = 12 ; s1.TotalMarks = 575 ; We may also use the member variables in expressions on the right hand side. Example: FinalMarks = s1.TotalMarks + 10 ;

41

SUNSAT The Perfect Team

Microsoft .Net

A Simple Application of structs: using System; struct Item { public string name; public int code; public double price; } class StructTest { public static void Main() { Item fan ; // create an item // Assign values to members fan.name = “Bajaj” ; fan.code= 123 ; fan.price = 2000.50 ; //Display item details system.console.WriteLine(“ Fan Name : “ + fan.name) ; system.console.WriteLine(“ Fan Code : “ + fan.code) ; system.console.WriteLine(“ Fan Price : “ + fan.price) ; } } Structs with Methods: We have seen that values may be assigned to the data members using struct objects and the dot operator. We can also assign values to the data members using what are known as constructors. Using Methods in structs: using system; struct Rect { int a,b; public Rect ( int x, int y) { a=x; b=y; } public int Area ( ) { return ( a * b ) ;

42

SUNSAT The Perfect Team

Microsoft .Net
} public void Display ( ) { system.console.WriteLine(“Area = “ + Area () ); } } class TestRect { public static void Main ( ) { Rect rr = new Rect(10,20) rr.Display(); } } Enumerations An enumeration is a user defined integer type which provides a way for attaching names to numbers, there by increasing the comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning those values 0, 1, 2 and so on. The syntax of an enum statement is enum Shape { circle, square, triangle } can be written as enum Shape { circle, square, triangle } Enumerator Initialization: we may assign specific values for different members. enum color { Red = 2, Blue = 5, Green = 6, Yellow = 9 } we can also have expressions , enum color { Red = 1, Blue = Red + 1,

43

SUNSAT The Perfect Team

Microsoft .Net
Green = Red + Blue + 3, Yellow = Blue + 3 } If the declaration of an enum member has no intilizer, then its value is set implicitly as follows: • If it is the first member, its value is zero. • Otherwise, its value is obtained by adding one to the value of the previous member. enum Alphabets { A, B = 3, C, D = 12, E } Example: using System; class Area { public enum Shape { circle, square } public void Areashape ( int x, Shape shape) { double area; switch( shape) { case Shape.circle: area = Math.PI * x * x; Console.WriteLine(“Circle Area : “ + area ); break; case Shape.square: area = x * x; Console.WriteLine(“Square Area : “ + area ); break; default: Console.WriteLine(“Invalid Input”); } } class Test { public static void Main( ) { Area ObjArea = new Area( );

44

SUNSAT The Perfect Team

Microsoft .Net
ObjArea.Areashape ( 13, Area.Shape.circle); ObjArea.Areashape ( 13, Area.Shape.square); ObjArea.Areashape ( 13, (Area.Shape) 1); ObjArea.Areashape ( 13, (Area.Shape) 10); } } Polymorphism Polymorphism means ‘one name, many forms’. Essentially, polymorphism is the capability of one objectto behave in multiple ways. Polymorphism can be achieved in two ways.

Polymorphism

Operation Polymorphism

Inclusion Polymorphism

Using Overloaded Methods
Operation Polymorphism

Using Virtual Methods

Operation Polymorphism is implemented using overloaded methods and operators. The overloaded methods are ‘selected’ for invoking by matching arguments, in terms of number, type and order. This information is known to compiler at the time of compilation and, therefore, the compiler is able to select and bind the appropriate method to the object for a particular call at compile time itself. This process is called early binding, or static binding, or static linking. It is also known as compile time polymorphism. Example: using System; class Dog { }

45

SUNSAT The Perfect Team

Microsoft .Net
class Cat { } class Operation { static void Call(Dog d) { Console.WiteLine (“Dog is called”); } static void Call(Cat c) { Console.WriteLine(“Cat is called”); } public static void Main() { Dog dog=new Dog(); Cat cat= new Cat(); Call(dog); Call(cat); } } Casting Between Types C# permits upcasting of an object of a derived class to an object of its base class. We cannot downcast implicitly an object of a base class to an object of its derived classes. Examples: class Base { } class Derived : Base { } ……………… ……………… Base b = new Cerived ( ) ; // ok , upcasting ………….. ………….. Derived d = new Base ( ) ; // Error, downcasting ……………. ……………. In case a downcast is required, it can be achieved using an explicit cast operation. Inclusion Polymorphism: Inclusion polymorphism is achieved through the use of virtual functions. Inclusion polymorphism allows you to implement methods of a derived class during run time. The decision on exactly which method to call is delayed until runtime and, therefore, it is also known as runtime polymorphism. Example:

46

SUNSAT The Perfect Team

Microsoft .Net
using System; class DrawObj { public virtual void Draw( ) { Console.WriteLine( “Base Draw”); } } class Line : DrawObj { public override void Draw( ) { Console.WriteLine(“Line Draw”); } } class Circle : DrawObj { public override void Draw( ) { Console.WriteLine(“ Circle Draw”): } } class Test { public static void Mian( ) { DrawObj objD = new DrawObj( ); objD = new Line( ); objD.Draw( ); objD = new Circle( ); objD.Draw( ); } } Properties Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods. Simple syntax of properties can see in the following example: public int Old { get {return m_old;} set {m_old = value;} } public string Name {

47

SUNSAT The Perfect Team

Microsoft .Net
get {return m_name;} } Example: using System; class Number { private int number; public int ANumber { get { return number; } set { number = value; } } } class Test { public void static Main( ) { Number n = new Number( ); n.ANumber = 100 ; // set //property

48

SUNSAT The Perfect Team

Microsoft .Net
int m = n.ANumber ; // get

Console.WriteLine ( “ Number = “ + m ); } } The class new declares a property called ANumber of type int and defines a get accessor method ( also known as getter ) and a set accessor method ( also known as setter). The getter method used the keyword return to return the field’s value to the caller. The settermethod sues the keyword value to receive the value being passed in from the user. The type of value is determined by the type of property. Delegates Delegate means method acting for another method. A Delegate in C# 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.Delagate as a base class. Delegate methods are any functions (defined in a class) whose signature matches the delegate signature exactly. The delegate instance holds the reference to delegate methods. The instance is used to invoke the methods indirectly. A delegate can be used to hold reference to a method of any class. The only requirement is that its Signature must match the Signature of the method. Delegate declaration General syntax for Delegate declaration is, modifier delegate return-type delegate-name ( parameters) ; Delegate Methods delegate void Delegate1(); public void F1() //instance method { Console.WriteLine (); } Static public void F2() // static method { Console.WriteLine(“F2”); }

49

SUNSAT The Perfect Team

Microsoft .Net
Similarly, Delegate double Mathop (double x, double y) Public static double multiply(double a, double b) { return(a*b); } public double divide(double a, double b) { return(a/b); } Delegate Instantiation //delegate declaration delegate int Productdelegate (int x, int y); class delegateSample { Static float product(float a, float b) //Siganture does not match { return(a*b); } Stat int product (int a, int b) // Signature matches { return(a*b); } //delegate instantiation product delegate p =new productdelegate(product); Delegate Invocation int m= p(10,20); delegate –object(parameter list) Parameter list provides for the parameters of the method to be used. Using Delegate Using system; Delegate int DeleMtd (int a, int b); Class DM { public int AddMe(int a, int b) { return(a+b); } public int SubMe(int a, int b) { return(a-b); } }

50

SUNSAT The Perfect Team

Microsoft .Net
class Test { Public Static Void Main() { DM objDM=new DM() DeleMtd[] Deleobj = {new DeleMtd(objDM.Addme), new DeleMtd(objDM.SubMe)}; Int t1=Deleobj[0](6,5); Int t2=Deleobj[1](6,5); System.Console.WriteLine(“The result of t1: “+t1); System.Console.WrteLine(“The result of t2:”+t2); } } Exception Handling An exception is a condition that is caused by a run time error in the program. The purpose of the exception handling mechanism is to provide a means to detect and report on ‘exceptional circumstances’. So that appropriate action can be taken. The mechanism suggests incorporation of a separate error handling code that performs the following tasks: • Find the problem (Hit the exception) • Inform that an error has occurred (Throw the exception) • Receive the error information (Catch the exception) • Take corrective actions (Handle the exception) Some of the common C# Exceptions are Argument Exception – An argument to a method was not valid. Arithmetic Exception – Arithmetic over or underflow has occurred. ArrayTypeMismatchException – Attempt to store the wrong type of object in an array. DivideByZeroException – An attempt was made to divide by zero. OutOfMemoryException – Not enough memory to continue the execution. To catch a particular type of exception in a piece of code, you have to first wrap it in a 'try' block and then specify a 'catch' block matching that type of exception. When an exception occurs in code within the 'try' block, the code execution moves to the end of the try box and looks for an appropriate exception handler. For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero: try { int zero = 0; res = (num / zero); } catch (System.DivideByZeroException e)

51

SUNSAT The Perfect Team

Microsoft .Net
{ Console.WriteLine("Error: an attempt to divide by zero"); } Multiple Catch Statements It is possible to have more than one catch statement in the catch block. Example: using System; class Test { public static void Main( ) { int [ ] a = { 5 , 10 }; int b = 5; try { int x = a[2] / b – a[1]; } catch ( Arithmetic Exception e) { Console.WriteLine( “Division by Zero” ); } catch(IndexOutOfRangeException e) { Console.WriteLine(“Array Index Error”); } catch(ArrayTypeMisMatchException e) { Console.WriteLine(“Wrong Data Type”); } int y = a[1] / a[0] ; Console.WriteLine(“y = “ + y); } } 'finally'block You can optionally use a 'finally' block along with the try-catch. The 'finally' block is guaranteed to be executed even if there is an exception. If an exception is raised, the code in the finally block gets executed after the code in the catch block. Example: using System; class Test {

52

SUNSAT The Perfect Team

Microsoft .Net
public static void Main( ) { int a = 100, num, R = 0; Console.WriteLine( “ Enter a number : “); try { num = int.Parse(Console.ReadLine( )): R = a / num; } catch(System.DivideByZeroException e) { Console.WriteLine(“Please enter a Number “); } finally { if(R != 0) { Console.WriteLine(“The Result is “ + R ); } } } } Formatted Output We can produce formatted output using the overloaded WriteLine( ) method. This method takes a string containing a format and a list of variables whose values have to be printed out. The general form of formatted WriteLine( ) method is: Console.WriteLine( format-string, v1, v2 ….. ); Format string contains both static text and markers which indicate • Where the values to be printed • How the values are to be formatted In this simplest form the marker is an index number in curly brackets, that indicates which variable of the argument list is to be substituted. Examples, Console.WriteLine(“Total is {0}”, total); Console.WriteLine(“ Sum of {0} and {1} is {2} “, a,b,c); In this examples, {0} represents the first argument in the list, {1} represents the second, and so on. Example: using System; class test { public static void Main( ) { string s = “Items”; int a = 100; float x = 67.66F; Console.WriteLine(“{0}\nIntValue : {1}\n FloatValue : {2}”,s,a,x); }

53

SUNSAT The Perfect Team

Microsoft .Net
}

VB.NET
Visual Basic .NET (VB.NET) is an object-oriented computer language that can be viewed as an spiritual evolution of Microsoft's Visual Basic (VB) implemented on the Microsoft .NET framework. Its introduction has been controversial, as significant changes were made that broke backward compatibility with VB and caused a rift within the developer community that may or may not be resolved with the introduction of Visual Studio 2005. Visual Basic .NET, the next generation of Visual Basic, is designed to be the easiest and most productive tool for creating .NET applications, including Windows applications, Web Services, and Web applications. While providing the traditional ease-of-use of Visual Basic development, Visual Basic .NET also allows optional use of new language features. Inheritance, method overloading, structured exception handling, and free threading all make Visual Basic a powerful objectoriented programming language. Visual Basic .NET fully integrates with the .NET Framework and the Common Language Runtime, which together provide language interoperability, simplified deployment, enhanced security, and improved versioning support. Difference between VB and VB.NET VB: 1. Object-based language 2. Does not support inheritance 3. ADO does not give support for disconnected data architecture 4. No interoperability function 5. No support for threading VB.Net 1. Object-Oriented Programming language 2. ADO.Net gives support for disconnected data architecture 3. It provides interoperability 4. It uses managed code 5. Supports threading 6. Provides access to third-party controls like COM, DCOM Windows Forms In Visual Basic its these Forms with which we work. They are the base on which we build, develop all our user interface and they come with a rich set of classes. Forms allow us to work visually with controls and other items from the toolbox. In VB .NET forms are based on the System.Windows.Forms namespace and the form class is System.Windows.Forms.Form. The

54

SUNSAT The Perfect Team

Microsoft .Net
form class is based on the Control class which allows it to share many properties and methods with other controls. When we open a new project in Visual Basic the dialogue box that appears first is the one which looks like the image below. Since we are working with Windows Applications (Forms) you need to select WindowsApplication and click OK.

Once you click OK a new Form opens with the title, Form1, towards the top-left side of the form and maximize, minimize and close buttons towards the top right of the form. The whole form is surrounded with a border. The main area of the form in which we work is called the Client Area. It's in this client area we design the user interface leaving all the code to the code behind file. Forms also support events which let's the form know that something happened with the form, for example, when we double-click on the form, the Form load event occurs. VB .NET also supports forms to be inherited. Image of a Windows Form.

55

SUNSAT The Perfect Team

Microsoft .Net

Typically the Form looks like this in Code which is handled by the Framework. Public Class Form1 Inherits System.Windows.Forms.Form #Region " Windows generated Form Designer code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(496, 493) Me.Name = "Form1" Me.Text = "Form1" End Sub #End Region

56

SUNSAT The Perfect Team

Microsoft .Net
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class Controls A control is an object that can be drawn on to the Form to enable or enhance user interaction with the application. Examples of these controls, TextBoxes, Buttons, Labels, Radio Buttons, etc. All these Windows Controls are based on the Control class, the base class for all controls. Visual Basic allows us to work with controls in two ways: at design time and at runtime. Working with controls at design time means, controls are visible to us and we can work with them by dragging and dropping them from the Toolbox and setting their properties in the properties window. Working at runtime means, controls are not visible while designing, are created and assigned properties in code and are visible only when the application is executed. There are many new controls added in Visual Basic.Net and we will be working with some of the most popular controls in this section. Notable properties of most of these Windows Controls which are based on the Control class itself are summarized in the table below. You can always find the properties of the control with which you are working by pressing F4 on the keyboard or by selecting View->Properties Window from the main menu. The Control Class The Control class is in the System.Windows.Forms namespace. It is a base class for the Windows Controls. The properties of the Control object are summarized below. Properties are alphabetical as seen in the properties window. AllowDrop Anchor BackColor Indicates if the form can accept data that the user drags and drops into it Gets/Sets which edges of the control are anchored Gets/Sets the background color for the control Gets the distance bewteen the bottom of the control and the top of its container client area Gets/Sets the controls bounding rectangle Returns a value specifying if the control can recieve focus Returns a value specifying if the control can be selected Gets/Sets a value specifying if the control has captured the mouse Gets/Sets a value specfying if the control causes validation for all controls that require validation

BackgroundImage Gets/Sets the back ground image in the control Bottom Bounds CanFocus CanSelect Capture CausesValidation

57

SUNSAT The Perfect Team

Microsoft .Net
Returns a value specifying if the control has the input focus Gets/Sets the shortcut menu for the control Gets/Sets the collection of controls contained within the control Gets/Sets the cursor to be displayed when the user moves the mouse over the form Gets the data bindings for the control Gets/Sets which edge of the parent a control is docked to Gets/Sets a value indicating if the control is enabled Returns a value specifying if the control has input focus Gets/Sets the font for the control Gets/Sets the foreground color of the control Returns a value specifying if the control contains child controls Gets/Sets the height of the control Gets/Sets the x-coordinates of a control's left edge in pixels Gets/Sets the co-ordinates of the upper-left corner of the control Gets/Sets name for the control Gets/Sets the control's parent container Returns the distance between the right edge of the control and the left edge of it's container Gets/Sets the value indicating if the alignment of the control's elements is reversed to support right-to-left fonts Gets/Sets size of the control in pixels Gets/Sets the tab order of this control in its container Gets/Sets a value specifying if the user can tab to this control with the tab key Gets/Sets an object that contains data about the control Gets/Sets the text for this control Gets/Sets the top coordinates of the control Gets/Sets a value specifying if the control is visible Gets/Sets the width of the control

ContainsFocus ContextMenu Controls Cursor DataBindings Dock Enabled Focused Font ForeColor HasChildren Height Left Location Name Parent Right RightToLeft Size TabIndex TabStop Tag Text Top Visible Width

Button Control

58

SUNSAT The Perfect Team

Microsoft .Net
One of the most popular control in Visual Basic is the Button Control (previously Command Control). They are the controls which we click and release to perform some action. Buttons are used mostly for handling events in code, say, for sending data entered in the form to the database and so on. The default event of the Button is the Click event and the Button class is based on the ButtonBase class which is based on the Control class. Button Event The default event of the Button is the Click event. When a Button is clicked it responds with the Click Event. The Click event of Button looks like this in code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click 'You place the code here to perform action when Button is clicked End Sub Working with Buttons Well, it's time to work with Buttons. Drag a Button from the toolbox onto the Form. The default text on the Button is Button1. Click on Button1 and select it's properties by pressing F4 on the keyboard or by selecting View->Properties Window from the main menu. That displays the Properties for Button1. Important Properties of Button1 from Properties Window: Appearance Appearance section of the properties window allows us to make changes to the appearance of the Button. With the help of BackColor and Back Ground Image properties we can set a background color and a background image to the button. We set the fontcolor and font style for the text that appears on button with ForeColor and the Font property. We change the appearance style of the button with the FlatStyle property. We can change the text that appears on button with the Text property and with the TextAlign property we can set where on the button the text should appear from a predefined set of options. Behavior Notable Behavior properties of the Button are the Enabled and Visible properties. The Enabled property is set to True by default which makes the button enabled and setting it's property to False makes the button Disabled. With the Visible property we can make the Button Visible or Invisible. The default value is set to True and to make the button Invisible set it's property to False. Layout Layout properties are about the look of the Button. Note the Dock property here. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container. The default value is set to none. If you want to dock the control towards the left, right, top, bottom and center you can do that by selecting from the button like image this property displays. With the Location property you can change the location of the button. With the Size

59

SUNSAT The Perfect Team

Microsoft .Net
property you can set the size of the button. Apart from the Dock property you can set it's size and location by moving and stretching the Button on the form itself. Below is the image of a Button.

Creating a Button in Code Below is the code to create a button. Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles_ MyBase.Load Dim Button1 as New Button() 'declaring the button, Button1 Button1.Text="Creating a Button" 'setting the text to be displayed on the Button Button1.Location=New Point(100,50) 'setting the location for the Button where it should be created Button1.Size=New Size(75,23) 'setting the size of the Button Me.Controls.Add(Button1) 'adding the Button that is created to the form 'the Me keyword is used to refer to the current object, in this case the Form End Sub End Class TextBox Control Windows users should be familiar with textboxes. This control looks like a box and accepts input from the user. The TextBox is based on the TextBoxBase class which is based on the Control class. TextBoxes are used to accept input from the user or used to display text. By default we can enter up to 2048 characters in a TextBox but if the Multiline property is set to True we can enter up to 32KB of text. The image below displays a Textbox.

60

SUNSAT The Perfect Team

Microsoft .Net

Some Notable Properties: Some important properties in the Behavior section of the Properties Window for TextBoxes. Enabled: Default value is True. To disable, set the property to False. Multiline: Setting this property to True makes the TextBox multiline which allows to accept multiple lines of text. Default value is False. PasswordChar: Used to set the password character. The text displayed in the TextBox will be the character set by the user. Say, if you enter *, the text that is entered in the TextBox is displayed as *. ReadOnly: Makes this TextBox readonly. It doesn't allow to enter any text. Visible: Default value is True. To hide it set the property to False. Important properties in the Appearance section TextAlign: Allows to align the text from three possible options. The default value is left and you can set the alignment of text to right or center. Scrollbars: Allows to add a scrollbar to a Textbox. Very useful when the TextBox is multiline. You have four options with this property. Options are are None, Horizontal, Vertical and Both. Depending on the size of the TextBox anyone of those can be used. TextBox Event The default event of the TextBox is the TextChanged Event which looks like this in code: Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles TextBox1.TextChanged End Sub Working With TextBoxes Lets work with some examples to understand TextBoxes. Drag two TextBoxes (TextBox1, TextBox2) and a Button (Button1) from the toolbox.

61

SUNSAT The Perfect Team

Microsoft .Net
Code to Display some text in the TextBox We want to display some text, say, "Welcome to TextBoxes", in TextBox1 when the Button is clicked. The code looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click TextBox1.Text = "Welcome to TextBoxes" End Sub Code to Work with PassWord Character Set the PasswordChar property of TextBox2 to *. Setting that will make the text entered in TextBox2 to be displayed as *. We want to display what is entered in TextBox2 in TextBox1. The code for that looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click TextBox1.Text = TextBox2.Text End Sub When you run the program and enter some text in TextBox2, text will be displayed as *. When you click the Button, the text you entered in TextBox2 will be displayed as plain text in TextBox1. Code to Validate User Input We can make sure that a TextBox can accept only characters or numbers which can restrict accidental operations. For example, adding two numbers of the form 27+2J cannot return anything. To avoid such kind of operations we use the KeyPress event of the TextBox. Code that allows you to enter only double digits in a TextBox looks like this: Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_ System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If(e.KeyChar < "10" Or e.KeyChar > "100") Then MessageBox.Show("Enter Double Digits") End If End Sub Creating a TextBox in Code Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MyBase.Load Dim TextBox1 as New TextBox() TextBox1.Text="Hello Mate" TextBox1.Location=New Point(100,50) TextBox1.Size=New Size(75,23) Me.Controls.Add(TextBox1) End Sub End Class

62

SUNSAT The Perfect Team

Microsoft .Net
RichTextBox RichTextBoxes are similar to TextBoxes but they provide some advanced features over the standard TextBox. RichTextBox allows formatting the text, say adding colors, displaying particular font types and so on. The RichTextBox, like the TextBox is based on the TextBoxBase class which is based on the Control class. These RichTextBoxes came into existence because many word processors these days allow us to save text in a rich text format. With RichTextBoxes we can also create our own word processors. We have two options when accessing text in a RichTextBox, text and rtf (rich text format). Text holds text in normal text and rtf holds text in rich text format. RichTextBox Event The default event of RichtextBox is the TextChanged event which looks like this in code: Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged End Sub Code Samples Code for creating bold and italic text in a RichTextBox Drag a RichTextBox (RichTextBox1) and a Button (Button1) onto the form. Enter some text in RichTextBox1, say, "We are working with RichTextBoxes". Paste the following code in the click event of Button1. The following code will search for text we mention in code and sets it to be displayed as Bold or Italic based on what text is searched for. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click RichTextBox1.SelectionStart = RichTextBox1.Find("are") 'using the Find method to find the text "are" and setting it's 'return property to SelectionStart which selects the text to format Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic) 'creating a new font object to set the font style RichTextBox1.SelectionFont = ifont 'assigning the value selected from the RichTextBox the font style RichTextBox1.SelectionStart = RichTextBox1.Find("working") Dim bfont As New Font(RichTextBox1.Font, FontStyle.Bold) RichTextBox1.SelectionFont = bfont End Sub When you run the above code and click Button1, the text "are" is displayed in Italic and the text "working" is displayed in Bold font. The image below displays the output. Code for Setting the Color of Text Lets work with previous example. Code for setting the color for particular text looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _

63

SUNSAT The Perfect Team

Microsoft .Net
System.EventArgs) Handles Button1.Click RichTextBox1.SelectionStart = RichTextBox1.Find("are") 'using the Find method to find the text "are" and setting it's return 'property to SelectionStart which selects the text RichTextBox1.SelectionColor = Color.Blue 'setting the color for the selected text with SelectionColor property RichTextBox1.SelectionStart = RichTextBox1.Find("working") RichTextBox1.SelectionColor = Color.Yellow End Sub The output when the Button is Clicked is the text "are" being displayed in Blue and the text "working" in yellow as shown in the image below.

Code for Saving Files to RTF Drag two RichTextBoxes and two Buttons (Save, Load) onto the form. When you enter some text in RichTextBox1 and click on Save button, the text from RichTextBox1 is saved into a rtf (rich text format) file. When you click on Load button the text from the rtf file is displayed into RichTextBox2. The code for that looks like this: Private Sub Save_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Save.Click RichTextBox1.SaveFile("hello.rtf") 'using SaveFile method to save text in a rich text box to hard disk End Sub Private Sub Load_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Load.Click RichTextBox2.LoadFile("hello.rtf")

64

SUNSAT The Perfect Team

Microsoft .Net
'using LoadFile method to read the saved file End Sub Label Labels are those controls that are used to display text in other parts of the application. They are based on the Control class. Notable property of the label control is the text property which is used to set the text for the label. Label Event The default event of Label is the Click event which looks like this in code: Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles Label1.Click End Sub Creating a Label in Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Load Dim Label1 As New Label() Label1.Text = "Label" Label1.Location = New Point(135, 70) Label1.Size = New Size(30, 30) Me.Controls.Add(Label1) End Sub

LinkLabel LinkLabel is similar to a Label but they display a hyperlink. Even multiple hyperlinks can be specified in the text of the control and each hyperlink can perform a different task within the application. They are based on the Label class which is based on the Control class.

65

SUNSAT The Perfect Team

Microsoft .Net
Notable properties of the LinkLabel control are the ActiveLinkColor, LinkColor and LinkVisited which are used to set the link color. LinkLabel Event The default event of LinkLabel is the LinkClicked event which looks like this in code: Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_ Handles LinkLabel1.LinkClicked End Sub Working with LinkLabel Drag a LinkLabel (LinkLabel1) onto the form. When we click this LinkLabel it will take us to "www.startvbdotnet.com". The code for that looks like this: Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal_ e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_ Handles LinkLabel1.LinkClicked System.Diagnostics.Process.Start("www.startvbdotnet.com") 'using the start method of system.diagnostics.process class 'process class gives access to local and remote processes End Sub Creating a LinkLabel in Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MyBase.Load Dim LinkLabel1 As New LinkLabel() LinkLabel1.Text = "Label" LinkLabel1.Location = New Point(135, 70) LinkLabel1.Size = New Size(30, 30) Me.Controls.Add(LinkLabel1) End Sub CheckBox CheckBoxes are those controls which gives us an option to select, say, Yes/No or True/False. A checkbox is clicked to select and clicked again to deselect some option. When a checkbox is selected a check (a tick mark) appears indicating a selection. The CheckBox control is based on the TextBoxBase class which is based on the Control class. Below is the image of a Checkbox.

66

SUNSAT The Perfect Team

Microsoft .Net

Notable Properties Important properties of the CheckBox in the Appearance section of the properties window are: Appearance: Default value is Normal. Set the value to Button if you want the CheckBox to be displayed as a Button. BackgroundImage: Used to set a background image for the checkbox. CheckAlign: Used to set the alignment for the CheckBox from a predefined list. Checked: Default value is False, set it to True if you want the CheckBox to be displayed as checked. CheckState: Default value is Unchecked. Set it to True if you want a check to appear. When set to Indeterminate it displays a check in gray background. FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the checkbox. Important property in the Behavior section of the properties window is the ThreeState property which is set to False by default. Set it to True to specify if the Checkbox can allow three check states than two. CheckBox Event The default event of the CheckBox is the CheckedChange event which looks like this in code: Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged End Sub

67

SUNSAT The Perfect Team

Microsoft .Net
Working with CheckBoxes Lets work with an example. Drag a CheckBox (CheckBox1), TextBox (TextBox1) and a Button (Button1) from the Toolbox. Code to display some text when the Checkbox is checked Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged TextBox1.Text = "CheckBox Checked" End Sub Code to check a CheckBox's state Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click If CheckBox1.Checked = True Then TextBox1.Text = "Checked" Else TextBox1.Text = "UnChecked" End If End Sub Creating a CheckBox in Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles_ MyBase.Load Dim CheckBox1 As New CheckBox() CheckBox1.Text = "Checkbox1" CheckBox1.Location = New Point(100, 50) CheckBox1.Size = New Size(95, 45) Me.Controls.Add(CheckBox1) End Sub RadioButton RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded instead of boxed as with a checkbox. Like CheckBoxes, RadioButtons are used to select and deselect options but they allow us to choose from mutually exclusive options. The RadioButton control is based on the ButtonBase class which is based on the Control class. A major difference between CheckBoxes and RadioButtons is, RadioButtons are mostly used together in a group. Below is the image of a RadioButton.

68

SUNSAT The Perfect Team

Microsoft .Net

Important properties of the RadioButton in the Appearance section of the properties window are: Appearance: Default value is Normal. Set the value to Button if you want the RadioButton to be displayed as a Button. BackgroundImage: Used to set a background image for the RadioButton. CheckAlign: Used to set the alignment for the RadioButton from a predefined list. Checked: Default value is False, set it to True if you want the RadioButton to be displayed as checked. FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the RadioButton. RadioButton Event The default event of the RadioButton is the CheckedChange event which looks like this in code: Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged End Sub Working with Examples Drag a RadioButton (RadioButton1), TextBox (TextBox1) and a Button (Button1) from the Toolbox. Code to display some text when the RadioButton is selected Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged TextBox1.Text = "RadioButton Selected" End Sub

69

SUNSAT The Perfect Team

Microsoft .Net
Code to check a RadioButton's state Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click If RadioButton1.Checked = True Then TextBox1.Text = "Selected" Else TextBox1.Text = "Not Selected" End If End Sub Creating a RadioButton in Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles_ MyBase.Load Dim RadioButton1 As New RadioButton() RadioButton1.Text = "RadioButton1" RadioButton1.Location = New Point(120,60) RadioButton1.Size = New Size(100, 50) Me.Controls.Add(RadioButton1) End Sub ListBox The ListBox control displays a list of items from which we can make a selection. We can select one or more than one of the items from the list. The ListBox control is based on the ListControl class which is based on the Control class. The image below displays a ListBox.

Notable Properties of the ListBox In the Behavior Section HorizontalScrollbar: Displays a horizontal scrollbar to the ListBox. Works when the ListBox has MultipleColumns. MultiColumn: The default value is set to False. Set it to True if you want the list box to display multiple columns. ScrollAlwaysVisible: Default value is set to False. Setting it to True will display both Vertical and Horizontal scrollbar always. SelectionMode: Default value is set to one. Select option None if you do not any item to be selected. Select it to MultiSimple if you want multiple items to be selected. Setting it to MultiExtended allows you to select multiple items with the help of Shift, Control and arrow keys on the keyboard.

70

SUNSAT The Perfect Team

Microsoft .Net
Sorted: Default value is set to False. Set it to True if you want the items displayed in the ListBox to be sorted by alphabetical order. In the Data Section Notable property in the Data section of the Properties window is the Items property. The Items property allows us to add the items we want to be displayed in the list box. Doing so is simple, click on the ellipses to open the String Collection Editor window and start entering what you want to be displayed in the ListBox. After entering the items click OK and doing that adds all the items to the ListBox. ListBox Event The default event of ListBox is the SelectedIndexChanged which looks like this in code: Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged End Sub Working with ListBoxes Drag a TextBox and a ListBox control to the form and add some items to the ListBox with it's items property. Referring to Items in the ListBox Items in a ListBox are referred by index. When items are added to the ListBox they are assigned an index. The first item in the ListBox always has an index of 0 the next 1 and so on. Code to display the index of an item Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedIndex 'using the selected index property of the list box to select the index End Sub When you run the code and select an item from the ListBox, it's index is displayed in the textbox. Counting the number of Items in a ListBox Add a Button to the form and place the following code in it's click event. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles Button1.Click TextBox1.Text = ListBox1.Items.Count 'counting the number of items in the ListBox with the Items.Count End Sub

71

SUNSAT The Perfect Team

Microsoft .Net
When you run the code and click the Button it will display the number of items available in the ListBox. Code to display the item selected from ListBox in a TextBox Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedItem 'using the selected item property End Sub When you run the code and click an item in the ListBox that item will be displayed in the TextBox. Code to Remove items from a ListBox You can remove all items or one particular item from the list box. Code to remove a particular item Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles Button1.Click ListBox1.Items.RemoveAt(4) 'removing an item by specifying it's index End Sub Code to Remove all items Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Items.Clear() 'using the clear method to clear the list box End Sub ComboBox ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing field (TextBox) combined with a ListBox allowing us to select from the list or to enter new text. ComboBox displays data in a drop-down style format. The ComboBox class is derived from the ListBox class. Below is the Image of a ComboBox.

72

SUNSAT The Perfect Team

Microsoft .Net

Notable properties of the ComboBox The DropDownStyle property in the Appearance section of the properties window allows us to set the look of the ComboBox. The default value is set to DropDown which means that the ComboBox displays the Text set by it's Text property in the Textbox and displays it's items in the DropDownListBox below. Setting it to simple makes the ComboBox to be displayed with a TextBox and the list box which doesn't drop down. Setting it to DropDownList makes the ComboBox to make selection only from the drop down list and restricts you from entering any text in the textbox. We can sort the ComboBox with it's Sorted property which is set to False by Default. We can add items to the ComboBox with it's Items property. ComboBox Event The default event of ComboBox is SelectedIndexChanged which looks like this in code: Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged End Sub Working with ComboBoxes Drag a ComboBox and a TextBox control onto the form. To display the selection made in the ComboBox in the Textbox the code looks like this: Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged TextBox1.Text = ComboBox1.SelectedItem 'selecting the item from the ComboBox with selected item property End Sub

73

SUNSAT The Perfect Team

Microsoft .Net
Removing items from a ComboBox You can remove all items or one particular item from the list box part of the ComboxBox. Code to remove a particular item by it's Index number looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click ComboBox1.Items.RemoveAt(4) 'removing an item by specifying it's index End Sub Code to remove all items from the ComboBox Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click ComboBox1.Items.Clear() 'using the clear method to clear the list box End Sub TreeView The tree view control is used to display a hierarchy of nodes (both parent, child). You can expand and collpase these nodes by clicking them. This control is similar to Windows Explorer which displays a tree view in it's left pane to list all the folders on the hard disk. Below is the image of a Tree View control.

Notable Properties of TreeView Bounds: Gets the actual bound of the tree node Checked: Gets/Sets whether the tree node is checked FirstNode: Gets the first child tree node FullPath: Gets the path from the root node to the current node ImageIndex: Gets/Sets the image list index of the image displayed for a node Index: Gets the location of the node in the node collection IsEditing: Gets whether the node can be edited IsExpaned: Gets whether the node is expaned IsSelected: Gets whether the node is selected LastNode: Gets the last child node NextNode: Gets the next sibling node

74

SUNSAT The Perfect Team

Microsoft .Net
NextVisibleNode: Gets the next visible node NodeFont: Gets/Sets the font for nodes Nodes: Gets the collection of nodes in the current node Parent: Gets the parent node of the current node PrevNode: Gets the previous sibling node PrevVisibleNode: Gets the previous visible node TreeView: Gets the node's parent tree view TreeView Event Default event of the Tree View control is the AfterSelect event which looks like this in code: Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As_ System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect End Sub Working with Tree Views Drag a Tree View control on to a form and to add nodes to it select the nodes property in the properties window, which displays the TreeNode editor as shown below.

To start adding nodes, you should click the Add Root button, which adds a top-level node. To add child nodes to that node, you should select that node and use the Add Child button. To set text for a node, select the node and set it's text in the textbox as shown in the image above. Assuming you added some nodes to the tree view, drag two Labels (Label1, Label2) from the toolbox on to the form. The following code displays the node you select on Label2 and the path to that node on Label1. The code looks like this: Public Class Form12 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code "

75

SUNSAT The Perfect Team

Microsoft .Net

#End Region Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As_ System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect Label1.Text = "You are here->" & " " & e.Node.FullPath 'displaying the path of the selected node Label2.Text = "Current node selected:" & " " & e.Node.Text 'displaying the selected node End Sub End Class The image below displays sample output from above code.

CheckedListBox As the name says, CheckedListBox is a combination of a ListBox and a CheckBox. It displays a ListBox with a CheckBox towards it's left. The CheckedListBox class is derived from the ListBox class and is based on that class. Since the CheckedListBox is derived from the ListBox it shares all the members of ListBox. Below is the Image of a CheckedListBox.

76

SUNSAT The Perfect Team

Microsoft .Net

Notable Properties of CheckedListBox The notable property in the appearance section of the properties window is the ThreeDCheckBoxes property which is set to False by default. Setting it to True makes the CheckedListBox to be displayed in Flat or Normal style. Notable property in the behavior section is the CheckOnClick property which is set to False by default. When set to False it means that to check or uncheck an item in the CheckedListBox we need to double-click the item. Setting it to True makes an item in the CheckedListBox to be checked or unchecked with a single click. Notable property in the Data section is the Items property with which we add items to the CheckedListBox. Private Sub CheckedListBox1_SelectedIndexChanged(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged End Sub Panel Panels are those controls which contain other controls, for example, a set of radio buttons, checkboxes, etc. Panels are similar to Groupboxes but the difference, Panels cannot display captions where as GroupBoxes can and Panels can have scrollbars where as GroupBoxes can't. If the Panel's Enabled property is set to False then the controls which the Panel contains are also disabled. Panels are based on the ScrollableControl class. Notable property of the Panel control in the appearance section is the BorderStyle property. The default value of the BorderStyle property is set to None. You can select from the predefined list to change a Panels BorderStyle. Notable property in the layout section is the AutoScroll property. Default value is set to False. Set it to True if you want a scrollbar with the Panel.

77

SUNSAT The Perfect Team

Microsoft .Net
Adding Controls to a Panel On a from drag a Panel (Panel1) from the toolbox. We want to place some controls, say, checkboxes on this Panel. Drag three checkboxes from the toolbox and place them on the Panel. When that is done all the checkboxes in the Panel are together as in a group but they can function independently. Creating a Panel and adding a Label and a CheckBox to it in Code Private Sub Form3_Load(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles MyBase.Load Dim Panel1 As New Panel() Dim CheckBox1 As New CheckBox() Dim Label1 As New Label() Panel1.Location = New Point(30, 60) Panel1.Size = New Size(200, 264) Panel1.BorderStyle = BorderStyle.Fixed3D 'setting the borderstyle of the panel Me.Controls.Add(Panel1) CheckBox1.Size = New Size(95, 45) CheckBox1.Location = New Point(20, 30) CheckBox1.Text = "Checkbox1" Label1.Size = New Size(100, 50) Label1.Location = New Point(20, 40) Label1.Text = "CheckMe" Panel1.Controls.Add(CheckBox1) Panel1.Controls.Add(Label1) 'adding the label and checkbox to the panel End Sub The image below displays a panel.

78

SUNSAT The Perfect Team

Microsoft .Net
GroupBox Control As said above, Groupboxes are used to Group controls. GroupBoxes display a frame around them and also allows to display captions to them which is not possible with the Panel control. The GroupBox class is based on the Control class. Creating a GroupBox and adding a Label and a CheckBox to it in Code Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles MyBase.Load Dim GroupBox1 As New GroupBox() Dim CheckBox1 As New CheckBox() Dim Label1 As New Label() GroupBox1.Location = New Point(30, 60) GroupBox1.Size = New Size(200, 264) GroupBox1.Text = "InGroupBox" 'setting the caption to the groupbox Me.Controls.Add(GroupBox1) CheckBox1.Size = New Size(95, 45) CheckBox1.Location = New Point(20, 30) CheckBox1.Text = "Checkbox1" label1.Size = New Size(100, 50) Label1.Location = New Point(20, 40) Label1.Text = "CheckMe" GroupBox1.Controls.Add(CheckBox1) GroupBox1.Controls.Add(Label1) 'adding the label and checkbox to the groupbox End Sub PictureBox Control PictureBoxes are used to display images on them. The images displayed can be anything varying from Bitmap, JPEG, GIF, PNG or any other image format files. The PictureBox control is based on the Control class. Notable property of the PictureBox Control in the Appearance section of the properties window is the Image property which allows to add the image to be displayed on the PictureBox. Adding Images to PictureBox Images can be added to the PictureBox with the Image property from the Properties window or by following lines of code. Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click PictureBox1.Image = Image.FromFile("C:\sample.gif") 'loading the image into the picturebox using the FromFile method of the image class 'assuming a GIF image named sample in C: drive End Sub

79

SUNSAT The Perfect Team

Microsoft .Net
ToolTip ToolTips are those small windows which display some text when the mouse is over a control giving a hint about what should be done with that control. ToolTip is not a control but a component which means that when we drag a ToolTip from the toolbox onto a form it will be displayed on the component tray. Tooltip is an Extender provider component which means that when you place an instance of a ToolTipProvider on a form, every control on that form receives a new property. This property can be viewed and set in the properties window where it appears as Tooltip on n, where n is the name of the ToolTipProvider. To assign ToolTip's with controls we use it's SetToolTip method. Notable property of the ToolTip is the Active property which is set to True by default and which allows the tool tip to be displayed. Setting a ToolTip Assume that we have a TextBox on the form and we want to display some text when your mouse is over the TextBox. Say the text that should appear is "Do not leave this blank". The code for that looks like this: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles MyBase.Load ToolTip1.SetToolTip(TextBox1, "Do not leave this blank") End Sub The image below displays output from above code.

ErrorProvider Component The ErrorProvider component provides an easy way to set validation errors. It allows us to set an error message for any control on the form when the input is not valid. When an error message is set, an icon indicating the error will appear next to the control and the error message is displayed as Tool Tip when the mouse is over the control.

80

SUNSAT The Perfect Team

Microsoft .Net
Notable property of ErrorProvider in the Appearance section is the Icon property which allows us to set an icon that should be displayed. Notable property in Behavior section is the BlinkRate property which allows to set the rate in milliseconds at which the icon blinks. Displaying an Error Let's work with an example. Assume we have a TextBox and a Button on a form. If the TextBox on the form is left blank and if the Button is clicked, an icon will be displayed next to the TextBox and the specified text will appear in the Tool Tip box when the mouse is over the control. The code for that looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click If TextBox1.Text = "" Then ErrorProvider1.SetError(TextBox1, "Cannot leave textbox blank") Else ErrorProvider1.SetError(TextBox1, "") End If End Sub The image below displays output from above code.

Menus Everyone should be familiar with Menus. Menus (File, Edit, Format etc in all windows applications) are those that allow us to make a selection when we want to perform some action with the application, for example, to format the text, open a new file, print and so on. In VB .NET MainMenu is the container for the Menu structure of the form. Menus are made of MenuItem objects that represent individual parts of a menu (like File->New, Open, Save, Save As etc). The two main classes involved in menu handling are, MainMenu and MenuItem. The MainMenu class let's us assign objects to a form's menu class and MenuItem is the class which supports the items in a menu system. Menus like File, Edit, Format etc and the items in those Menus are supported by this MenuItem class. It's this MenuItem's click event that makes these Menus work. For a MenuItem to be displayed, we need to add it to a MainMenu object.

81

SUNSAT The Perfect Team

Microsoft .Net
Event of the MenuItem The default event of the MenuItem is the Click event which looks like this in code: Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MenuItem1.Click End Sub Notable properties of the MenuItem class are summarized below. Under the Miscellaneous Section of the properties window: Checked: Default value is set to False. Changing it to True makes a checkmark appear towards the left of the Menu. DefaultItem: Default value is set to False. Changing it to True makes this menu item default menu item. RadioCheck: Changing it to True makes a menu item display a radio button instead of a checkmark. Shortcut: Enables to set a short cut key from a list of available shortcuts for the menu item. Working with Menus Creating Menus is simple. Drag a MainMenu component from the toolbar onto the form. When you add a MaiuMenu component to the form it appears in the component tray below the form. Windows form designer will add the MenuItem's for this by default, you need not add this. Once when you finish adding a MainMenu component to the form you will notice a "TypeHere" box towards the top-left corner of the form. To create a menu all you have to do is click on the "TypeHere" text which opens up a small textbox allowing you to enter text for the menu. You can view that in the image below. You can use the arrow keys on the keyboard to create a submenu or add other items to that menu or click on the first menu item and use the left/right arrow keys on the keyboard to create a new menu item. That's all it takes to add a menu to the form.

82

SUNSAT The Perfect Team

Microsoft .Net
Working with an example Let's work with an example to understand Menus. Drag a MainMenu and a TextBox onto the form. In the "Type Here" part, type File and under file type "New" and "Exit". Our intention here is to display "Welcome to Menus" in the TextBox when "New" is clicked and close the form when "Exit" is clicked. The Menu which we will create should look like this File->New, Exit (New and Exit below File). The code for that looks like this: Public Class Form3 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs)_ Handles MenuItem2.Click TextBox1.Text = "Welcome to Menus" End Sub Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_ Handles MenuItem3.Click Me.Close() 'Me refers to the current object (form) End Sub End Class Context Menus Context menus are menus that appear when an item is right-clicked. In any windows application when you right-click your mouse you get a menu which might display some shortcuts from the Edit Menu, for example, cut, copy, paste, paste special and so on. All these menu items which are available when you right-click are called Context Menus. In Visual Basic we create context menus with the ContextMenu component. The ContextMenu component is edited exactly the same way the MainMenu component is edited. The ContextMenu appears at the top of the form and you can add menu items by typing them. To associate a ContextMenu with a particular form or control we need to set the ContextMenu property of that form or control to the appropriate menu. Working With Example eLet's understand ContextMenus with an example. On a new Form drag a ContextMenu component from the toolbox. Click on the ContextMenu component to open the editor at the top of the form. In the type here box, enter cut, copy, paste. Cut is assigned MenuItem1, Copy with MenuItem2 and Paste with MenuItem3. Darg two RichTextBoxes onto the form. In the properties window for the form and the richtextboxes, select the ContextMenu property and set it to ContextMenu1. Make sure you set the ContextMenu property for both the richtextboxes. This sample application allows you to enter some text in RichTextBox1, select some text, cut/copy the slected text and paste it in RichTextBox2. It is similar to the right-click menu with which you work in other windows applications. The whole design should look like the image below.

83

SUNSAT The Perfect Team

Microsoft .Net

Code to get the desired result looks like this: Public Class Form3 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " #End Region Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles MenuItem1.Click RichTextBox1.Cut() End Sub Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles MenuItem2.Click RichTextBox1.Copy() End Sub Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles MenuItem3.Click RichTextBox2.Paste() End Sub End Class You can run the application, enter some text in richtextbox1, cut/copy it and paste it in richtextbox2. The images below display sample output from the above said code.

84

SUNSAT The Perfect Team

Microsoft .Net

Common Dialogs Visual Basic .NET comes with built-in dialog boxes which allow us to create our own File Open, File Save, Font, Color dialogs much like what we see in all other windows applications. To make a dialog box visible at run time we use the dialog box's ShowDialog method. The Dialog Boxes which come with Visual Basic .NET are: OpenFileDialog, SaveFileDialog, FontDialog, ColorDialog, PrintDialog, PrintPreviewDialog and PageSetupDialog. We will be working with OpenFile, SaveFile, Font and Color Dialog's in this section. The return values of all the above said dialog boxes which will determine which selection a user makes are: Abort, Cancel, Ignore, No, None, OK, Return, Retry and Yes. OpenFileDialog Open File Dialog's are supported by the OpenFileDialog class and they allow us to select a file to be opened. Below is the image of an OpenFileDialog.

85

SUNSAT The Perfect Team

Microsoft .Net
Properties of the OpenFileDialog are as follows: AddExtension: Gets/Sets if the dialog box adds extension to file names if the user doesn't supply the extension. CheckFileEixsts: Checks whether the specified file exists before returning from the dialog. CheckPathExists: Checks whether the specified path exists before returning from the dialog. DefaultExt: Allows you to set the default file extension. FileName: Gets/Sets file name selected in the file dialog box. FileNames: Gets the file names of all selected files. Filter: Gets/Sets the current file name filter string, which sets the choices that appear in the "Files of Type" box. FilterIndex: Gets/Sets the index of the filter selected in the file dialog box. InitialDirectory: This property allows to set the initial directory which should open when you use the OpenFileDialog. MultiSelect: This property when set to True allows to select multiple file extensions. ReadOnlyChecked: Gets/Sets whether the read-only checkbox is checked. RestoreDirectory: If True, this property restores the original directory before closing. ShowHelp: Gets/Sets whether the help button should be displayed. ShowReadOnly: Gets/Sets whether the dialog displays a read-only check box. Title: This property allows to set a title for the file dialog box. ValidateNames: This property is used to specify whether the dialog box accepts only valid file names. SaveFileDialog Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file in a specified location. Below is the image of a SaveFileDialog.

Properties of the Save File Dialog are the same as that of the Open File Dialog. Please refer above. Notable property of Save File dialog is the OverwritePromopt property which displays a warning if we choose to save to a name that already exists.

86

SUNSAT The Perfect Team

Microsoft .Net
FontDialog Font Dialog's are supported by the FontDialog Class and they allow us to select a font size, face, style, etc. Below is the image of a FontDialog.

Properties of the FontDialog are as follows: AllowSimulations: Gets/Sets whether the dialog box allows graphics device interface font simulations. AllowVectorFonts: Gets/Sets whether the dialog box allows vector fonts. AllowVerticalFonts: Gets/Sets whether the dialog box displays both vertical and horizontal fonts or only horizontal fonts. Color: Gets/Sets selected font color. FixedPitchOnly: Gets/Sets whether the dialog box allows only the selection of fixed-pitch fonts. Font: Gets/Sets the selected font. FontMustExist: Gets/Sets whether the dialog box specifies an error condition if the user attempts to select a font or size that doesn't exist. MaxSize: Gets/Sets the maximum point size the user can select. MinSize: Gets/Sets the mainimum point size the user can select. ShowApply: Gets/Sets whether the dialog box contains an apply button. ShowColors: Gets/Sets whether the dialog box displays the color choice. ShowEffects: Gets/Sets whether the dialog box contains controls that allow the user to specify to specify strikethrough, underline and text color options. ShowHelp: Gets/Sets whether the dialog box displays a help button. ColorDialogs Color Dialog's are supported by the ColorDialog Class and they allow us to select a color. The image below displays a color dialog.

87

SUNSAT The Perfect Team

Microsoft .Net

Properties of ColorDialog are as follows: AllowFullOpen: Gets/Sets whether the user can use the dialog box to define custom colors. AnyColor: Gets/Sets whether thedialog box displays all the available colors in the set of basic colons. Color: Gets/Sets the color selected by the user. CustomColors: Gets/Sets the set of custom colors shown in the dialog box. FullOpen: Gets/Sets whether the controls used to create custom colors are visible when the dialog box is opened. ShowHelp: Gets/Sets whether the dialog box displays a help button. SolidColorOnly: Gets/Sets whether the dialog box will restrict users to selecting solid colors only Putting Dialog Boxes to Work We will work with OpenFile, SaveFile, Font and Color Dialog's in this section. From the toolbox drag a MainMenu component, RichTextBox control, Button Control, OpenFileDialog, SaveFileDialog, FontDialog and ColorDialog onto the form. The sample code demonstrated below allows you to select a file to be opened and displays it in the RichTextBox with OpenFileDialog, allows you to save the text you enter in the RichTextBox to a location using the SaveFileDialog, allows you to select a font and applies the selected font to text in the RTB using FontDialog and allows you to select a color and applies the color to text in the RTB using the ColorDialog. Select the MainMenu component and in the "Type Here" part of the MainMenu type File and using the down arrow keys on the keyboard start typing Open, Save, SelectFont and SelectColor under the File menu. It should look like this: File-> Open, Save, SelectFont, SelectColor. We will assign OpenFileDialog to Open, SaveFileDialog to Save, FontDialog to SelectFont and ColorDialog to SelectColor under File Menu. The form in design view should look similar to the image below.

88

SUNSAT The Perfect Team

Microsoft .Net

Before proceeding further you need to set properties for these dialogs in their properties window. They are listed below. For OpenFileDialog1, set the DefaultExt property to txt so that it opens text files, InitialDirectory property to C:, RestoreDirectory propery to True and the Text property to Open File From. For SaveFileDialog1, set the DefaultExt property to txt so that it saves files in text format, InitialDirectory property to C: so that when you save a file, it first provides C: drive as the choice of location, OverwritePrompt property to False, RestoreDirectory propery to True and the Text property to Save File In. For FontDialog1, set the AllowSimulations, AllowVectorFonts, AllowverticalFonts properties to false, MaxSize to 50, MinSize to 5 and ShowApply and ShowColor properties to True. For ColorDialog1, set AnyColor and SolidColorOnly properties to True. Code Imports System.IO Public Class Form1 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " #End Region Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click RichTextBox1.Text = " "

89

SUNSAT The Perfect Team

Microsoft .Net
'clears the text in richtextbox End Sub Private FileName As String 'declaring filename that will be selected Dim sr As StreamReader 'streamreader is used to read text Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MenuItem2.Click Try With OpenFileDialog1 'With statement is used to execute statements using a particular object, here,_ 'OpenFileDialog1 .Filter = "Text files (*.txt)|*.txt|" & "All files|*.*" 'setting filters so that Text files and All Files choice appears in the Files of Type box 'in the dialog If .ShowDialog() = DialogResult.OK Then 'showDialog method makes the dialog box visible at run time FileName = .FileName sr = New StreamReader(.OpenFile) 'using streamreader to read the opened text file RichTextBox1.Text = sr.ReadToEnd() 'displaying text from streamreader in richtextbox End If End With Catch es As Exception MessageBox.Show(es.Message) Finally If Not (sr Is Nothing) Then sr.Close() End If End Try End Sub Private Sub MenuItem3_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MenuItem3.Click Dim sw As StreamWriter 'streamwriter is used to write text Try With SaveFileDialog1 .FileName = FileName .Filter = "Text files (*.txt)|*.txt|" & "All files|*.*" If .ShowDialog() = DialogResult.OK Then FileName = .FileName sw = New StreamWriter(FileName) 'using streamwriter to write text from richtextbox and saving it sw.Write(RichTextBox1.Text) End If End With

90

SUNSAT The Perfect Team

Microsoft .Net
Catch es As Exception MessageBox.Show(es.Message) Finally If Not (sw Is Nothing) Then sw.Close() End If End Try End Sub Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles MenuItem4.Click Try With FontDialog1 .Font = RichTextBox1.Font 'initializing the dialog box to match the font used in the richtextbox .Color = RichTextBox1.ForeColor 'default color is Black If .ShowDialog = DialogResult.OK Then setFont() 'calling a method setFont() to set the selected font and color End If End With Catch es As Exception MessageBox.Show(es.Message) End Try End Sub Private Sub setFont() Try With FontDialog1 RichTextBox1.Font = .Font If .ShowColor Then RichTextBox1.ForeColor = .Color 'setting the color End If End With Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub MenuItem5_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles MenuItem5.Click Static CustomColors() As Integer = {RGB(255, 0, 0), RGB(0, 255, 0), RGB(0, 0, 255)} 'initializing CustomColors with an array of integers and putting Red, Green, 'and Blue in the custom colors section Try With ColorDialog1 .Color = RichTextBox1.ForeColor 'initializing the selected color to match the color currently used

91

SUNSAT The Perfect Team

Microsoft .Net
'by the richtextbox's foreground color .CustomColors = CustomColors 'filling custom colors on the dialog box with the array declared above If .ShowDialog() = DialogResult.OK Then RichTextBox1.ForeColor = .Color CustomColors = .CustomColors 'Storing the custom colors to use again End If ColorDialog1.Reset() 'resetting all colors in the dialog box End With Catch es As Exception MessageBox.Show(es.Message) End Try End Sub End Class Date TimePicker Date TimePicker allows us to select date and time. Date TimePicker is based on the control class. When we click on the drop-down arrow on this control it displays a month calendar from which we can make selections. When we make a selection that selection appears in the textbox part of the Date TimePicker. The image below displays the Date TimePicker. Notable Properties of Date TimePicker The Format property in the Appearance section is used to select the format of the date and time selected. Default value is long which displays the date in long format. Other values include short, time and custom Behavior Section The CustomFormat property allows us to set the format for date and time depending on what we like. To use the CustomFormat property we need to set the Format property to Custom. The MaxDate Property allows us to set the maximum date we want the Date TimePicker to hold. Default MaxDate value set by the software is 12/31/9998 . The MinDate Property allows us to set the minimum date we want the Date TimePicker to hold. Default MinDate value set by the software is 1/1/1753 . MonthCalendar The MonthCalendar control allows us to select date. The difference between a Date TimePicker and MonthCalendar is, in MonthCalendar we select the date visually and in Date TimePicker when we want to make a selection we click on the drop-down arrow and select the date from the MonthCalendar which is displayed. The image below displays a MonthCalendar control. Notable Behavior properties of MonthCalendar

92

SUNSAT The Perfect Team

Microsoft .Net
FirstDayOfWeek: Default value is Default which means that the week starts with Sunday as the first day and Saturday as last. You can set the first day of the week depending upon your choice by selecting from the predefined list with this property. ShowToday: Default value is set to True which displays the current date at the bottom of the Calendar. Setting it to False will hide it. ShowTodayCircle: Default value is set to True which displays a red circle on the current date. Setting it to False will make the circle disappear. ShowWeekNumber: Default is False. Setting it to True will display the week number of the current week in the 52 week year. That will be displayed towards the left side of the control.

Splitter The Splitter control is used to resize other controls. The main purpose of Splitter control is to save space on the form. Once when we finish working with a particular control we can move it away from it's position or resize them with Splitter control. The Splitter control is invisible when we run the application but when the mouse is over it, the mouse cursor changes indicating that it's a Splitter control and it can be resized. This control can be very useful when we are working with controls both at design time and run time (which are not visible at design time). The Splitter control is based on the Control class. Working with Splitter Control To work with a Splitter Control we need to make sure that the other control with which this control works is docked towards the same side of the container. Let's do that with an example. Assume that we have a TextBox on the form. Drag a Splitter control onto the form. Set the TextBox's dock property to left. If we want to resize the TextBox once we finish using it set the Splitter's dock property to left (both the controls should be docked towards the same end). When the program is executed and when you pass the mouse over the Splitter control it allows us to resize the TextBox allowing us to move it away from it's current position.

93

SUNSAT The Perfect Team

Microsoft .Net
HelpProvider Providing help with your application is very useful as it allows your users to understand it more easily, thereby increasing productivity and saving some money. Support for help in Visual Basic exists and you can display HTML files that can contain a set of linked topics. Help Class The Help class allows us to display HTML help to users. The Help class provides two methods: ShowHelp and ShowHelpIndex. ShowHelp is used to display a help file for a particular control and requires that control to be displayed along with the help file. The URL you specify for the help file can be in the form of C:\myHelp (local machine) or http:\\www.startvbdotnet.com\help.htm (Web). Generally, the Help class is used in conjunction with Menus, Context Menus. Example The following code displays a help file. This code assumes that you have a Button, Button1, Label, Label1 on the form and a help file named Apphelp.htm in the C: drive of your machine. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_ As System.EventArgs) Handles Button1.Click Help.ShowHelp(Label1, "C:\Apphelp.htm") 'using the Help class with label control End Sub The ShowHelpIndex method is used to display the index of a specified help file. You call the ShowHelpIndex method just like you call the ShowHelp method. HelpProvider Component HelpProviderComponent allows us to provide help for controls on the form when F1 key is pressed. The HelpProviderComponent is an extender provider which means that it coordinates and maintains properties for each control on the form. Notable Property of HelpProvider component is the HelpNameSpace property which specifies the URL for the help file associated with it. The HelpProvider component provides three additional properties to each control on the form. These properties are: HelpString: Determines the help string associated with a control. HelpKeyWord: Determines the help keyword associated with a control. HelpNavigator: Determines the kind of help associated with a control. Provides six values: TableOfContents, Find, Index, Topic, AssociatedIndex and KeywordIndex. The above said three properties are visible in the properties window for each control once the HelpProvider component is added to the form. If the HelpNameSpace property is not set, the HelpString is automatically displayed, and other two properties are ignored.

94

SUNSAT The Perfect Team

Microsoft .Net
Example Drag two Buttons and the HelpProvider component onto the form. The following code displays a help string when Button2 has the focus and F1 key is pressed. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles MyBase.Load HelpProvider1.SetHelpString(Button2, "I am supported by HelpProvider1") 'button2 needs to have focus to display this string when F1 is pressed End Sub The image below displays output from code above.

StatusBar Status Bars are used to display status messages at the bottom of the form. They are generally used to provide additional information, such as page numbers, display a message, etc. There are two kinds of status bars: simple status bars and status bars that display a panel. Simple status bars display a single message on the status bar and a status bar with panels can display multiple messages. Below is the image of a StatusBar control.

95

SUNSAT The Perfect Team

Microsoft .Net
Notable properties of the Status bar: Panels: Gets the collection of status bar panels in a status bar. ShowPanels: Default is True. You can set it to False if you don't want to show panels. Text: Gets/Sets the text to be displayed. StatusBar Event Defalut event of the StatusBar control is the PanelClick event which looks like this in Code: Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, ByVal e _ As System.Windows.Forms.StatusBarPanelClickEventArgs) Handles StatusBar1.PanelClick End Sub Sample code for a Simple Status Bar From the toolbox add a status bar control to the form. The following code will display the message "Hello" on the StatusBar when the form loads. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles MyBase.Load StatusBar1.Text = "Hello" End Sub Status Bars with Panels You can add panels to a status bar by opening it's properties window and clicking the Panels property. When you click the Panels property it opens the StatusBarPanel Collection Editor which looks like the image below.

96

SUNSAT The Perfect Team

Microsoft .Net

You add panels by clicking the Add button found in the editor. While adding panels you can set the Text to be displayed for each panel, an icon, tooltip, width for each panel you add. To add panels to status bar in code we use the StatusBar.Panel.Add method and StatusBar.Panels.Remove, StatusBar.Panels.RemoveAt to remove the panels. To access text in each panel you use the text property of StatusbarPanel as: StatusBarPanels(0).Text="I am panel one". To handle status bar panel clicks you use the PanelClick event as shown in the code below. To work with this code, add a status bar control to the form, open it's properties window, select the Panels property and add three status bar panels. For StatusBarPanel1 set the text "More VB .NET? Please Visit ->", for StatusBarPanel2 set the text "MSDN" and for StatusBarPanel3 "Startvbdotnet.com". The form in design view should look like the image below.

Switch to code view and paste the following code: Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, ByVal e As _ System.Windows.Forms.StatusBarPanelClickEventArgs) Handles StatusBar1.PanelClick If e.StatusBarPanel Is StatusBar1.Panels(1) Then 'checks if status bar panel2 is clicked and if true opens a webpage System.Diagnostics.Process.Start("www.msdn.mcirosoft.com") ElseIf e.StatusBarPanel Is StatusBar1.Panels(2) Then 'checks if status bar panel3 is clicked and if true opens a webpage System.Diagnostics.Process.Start("www.startvbdotnet.com") End If End Sub

NotifyIcon Notify Icons display an icon in Windows System Tray. This is really useful for processes that run in the background and don't have their own interface. Since VB allows us to create Windows

97

SUNSAT The Perfect Team

Microsoft .Net
Services (services that run in the background and display control panels) now, we can use these notify icon's to associate funtionality to windows services. You can also use this icon to associate help with your application, launch another application or anything else which you think can be appropriate. Notable properties of Notify Icon: ContextMenu: Gets/Sets Context menu for the tray icon Icon: Gets/Sets current icon Text: Gets/Sets tooltip text that is displayed when the mouse hovers over the system tray Visible: Gets/Sets if the icon is visible in the windows system tray Notify Icon Event The default event associated with Notify Icon is the MouseDown event which looks like this in code: Private Sub NotifyIcon2_MouseDown(ByVal sender As System.Object, ByVal e As _ System.Windows.Forms.MouseEventArgs) Handles NotifyIcon2.MouseDown End Sub You can also handle click and double-click events for notify icon. The code sample below works with the click event of the Notify Icon to display a help file. To create a Notify Icon component you need an icon (.ico) file to assign to it's Icon property. If you have an icon then you can use it else you might need to create an icon. You can create new icons with Visual Studio's icon designer. To open the icon designer select Project->Add New Item and from the Add New Item dialog select Icon File and click open. You can use the toolbars that are visible to design your icon. The Icon Designer Window is displayed below.

Sample Code

98

SUNSAT The Perfect Team

Microsoft .Net
Drag a Notify Icon component and a Label control from the toolbar onto the form. Open the properties window for the Notify Icon and set the Icon property to the path of the icon and the text property to "Help with this Form". This is the icon that will be displayed when you run the application. The Label control is needed to set the help file. Set the text for label as "I have Help". The form in design view should look like the image below.

This sample code launches a help file when you click the Icon in System Tray. This sample code assumes that you have a help file, "Help.htm" in the C: drive of your machine. Private Sub NotifyIcon1_click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles NotifyIcon1.Click 'handling click event of the NotifyIcon Help.ShowHelp(Label1, "c:\help.htm") 'using the Help class and it's ShowHelp method to display a help file End Sub When you run the application, an icon will be visible in the System Tray and when you click the icon the help file named "Help.htm" will be launched. The image below displays the output from above code.

99

SUNSAT The Perfect Team

Microsoft .Net

ASP.NET
Asp.Net – Introduction Asp.net is the new offering for Web developers form the Microsoft. It is not simply the next generation of ASP. Because it has evolved from Asp, Asp.Net looks very similar to its predecessor. But concepts like web forms, Web Services, or server controls gives Asp.Net the power to build real Web application. What is ASP.NET?
• • •

ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services Like ASP, ASP.NET is a server-side technology Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls. Web Forms are designed to make building web-based applications as easy as building Visual Basic applications

100

SUNSAT The Perfect Team

Microsoft .Net
Features of ASP.NET

Separation of Code from HTML To make a clean sweep, with ASP.NET you have the ability to completely separate layout and business logic. This makes it much easier for teams of programmers and designers to collaborate efficiently. This makes it much easier for teams of programmers and designers to collaborate efficiently. Support for compiled languages developer can use VB.NET and access features such as strong typing and object-oriented programming. Using compiled languages also means that ASP.NET pages do not suffer the performance penalties associated with interpreted code. ASP.NET pages are precompiled to byte-code and Just In Time (JIT) compiled when first requested. Subsequent requests are directed to the fully compiled code, which is cached until the source changes. Use services provided by the .NET Framework The .NET Framework provides class libraries that can be used by your application. Some of the key classes help you with input/output, access to operating system services, data access, or even debugging. We will go into more detail on some of them in this module. Graphical Development Environment Visual Studio .NET provides a very rich development environment for Web developers. You can drag and drop controls and set properties the way you do in Visual Basic 6. And you have full IntelliSense support, not only for your code, but also for HTML and XML. State management To refer to the problems mentioned before, ASP.NET provides solutions for session and application state management. State information can, for example, be kept in memory or stored in a database. It can be shared across Web farms, and state information can be recovered, even if the server fails or the connection breaks down Update files while the server is running Components of your application can be updated while the server is online and clients are connected. The Framework will use the new files as soon as they are copied to the application. Removed or old files that are still in use are kept in memory until the clients have finished. XML-Based Configuration Files Configuration settings in ASP.NET are stored in XML files that you can easily read and edit. You can also easily copy these to another server, along with the other files that comprise your application.

ASP.NET Page Life Cycle Overview When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the page life cycle, but the page raises more events for a control than are available for an ASP.NET page alone.)

101

SUNSAT The Perfect Team

Microsoft .Net
General Page Life-cycle Stages In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page. Stage Page request Description The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page. In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set. During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state. During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Start

Page initialization

Load Validation

Postback event If the request is a postback, any event handlers are called. handling Rendering Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property. Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Unload

Life-cycle Events Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code. Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true (or if it is not defined, since by default it is true), page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init

102

SUNSAT The Perfect Team

Microsoft .Net
The following table lists the page life-cycle events that you will use most frequently. There are more events than those listed; however, they are not used for most page processing scenarios. Instead, they are primarily used by server controls on the ASP.NET Web page to initialize and render themselves. If you want to write your own ASP.NET server controls, you need to understand more about these stages. Page Event PreInit

Typical Use Use this event for the following: Check the IsPostBack property to determine whether this is the first time the page is being processed. • Create or re-create dynamic controls. • Set a master page dynamically. • Set the Theme property dynamically. • Read or set profile property values.

Note If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event. Init InitComplete PreLoad Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties. Raised by the Page object. Use this event for processing tasks that require all initialization be complete. Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance. The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event. Note In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing. LoadComplete PreRender

Load

Control events

Use this event for tasks that require that all other controls on the page be loaded. Before this event occurs: The Page object calls EnsureChildControls for each control and for the

103

SUNSAT The Perfect Team

Microsoft .Net
page. Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls below. The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

SaveStateComplet Before this event occurs, ViewState has been saved for the page and for all e controls. Any changes to the page or controls at this point will be ignored. Use this event perform tasks that require view state to be saved, but that do not make any changes to controls. Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser. If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code. This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections. For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other requestspecific tasks. Note During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception. Structure of Asp.Net Directives You can use directives to specify optional settings used by the page compiler when processing ASP.NET files. For each directive you can set different attributes. One example is the language directive at the beginning of a page defining the default programming language. Code Declaration Blocks Code declaration blocks are lines of code enclosed in <script> tags. They contain the runat=server attribute, which tells ASP.NET that these controls can be accessed on the server and on the client. Optionally you can specify the language for the block. The code block itself consists of the definition of member variables and methods.

Unload

104

SUNSAT The Perfect Team

Microsoft .Net
Code Render Blocks Render blocks contain inline code or inline expressions enclosed by the character sequences shown here. The language used inside those blocks could be specified through a directive like the one shown before. HTML Control Syntax You can declare several standard HTML elements as HTML server controls. Use the element as you are familiar with in HTML and add the attribute runat=server. This causes the HTML element to be treated as a server control. It is now programmatically accessible by using a unique ID. HTML server controls must reside within a <form> section that also has the attribute runat=server. Custom Control Syntax There are two different kinds of custom controls. On the one hand there are the controls that ship with .NET, and on the other hand you can create your own custom controls. Using custom server controls is the best way to encapsulate common programmatic functionality.Just specify elements as you did with HTML elements, but add a tag prefix, which is an alias for the fully qualified namespace of the control. Again you must include the runat=server attribute. If you want to get programmatic access to the control, just add an Id attribute.You can include properties for each server control to characterize its behavior. For example, you can set the maximum length of a TextBox. Those properties might have sub properties; you know this principle from HTML. Now you have the ability to specify, for example, the size and type of the font you use .The last attribute is dedicated to event binding. This can be used to bind the control to a specific event Data Binding Expression You can create bindings between server controls and data sources. The data binding expression is enclosed by the character sequences <%# and %>. The data-binding model provided by ASP.NET is hierarchical. That means you can create bindings between server control properties and superior data sources. Server-side Object Tags If you need to create an instance of an object on the server, use server-side object tags. When the page is compiled, an instance of the specified object is created. To specify the object use the identifier attribute. You can declare .NET objects using class as the identifier, and COM objects using either progid or classid. Server-side Include Directives With server-side include directives you can include raw contents of a file anywhere in your ASP.NET file. Specify the type of the path to filename with the path type attribute. Use either File, when specifying a relative path, or Virtual, when using a full virtual path. Server-side Comments

105

SUNSAT The Perfect Team

Microsoft .Net
To prevent server code from executing, use these character sequences to comment it out. You can comment out full blocks - not just single lines. Asp.Net – Framework ASP.NET is based on the fundamental architecture of .NET Framework. Visual studio provides a uniform way to combine the various features of this Architecture. Architecture is explained form bottom to top in the following discussion.

At the bottom of the Architecture is Common Language Runtime. NET framework common language runtime resides on top of the operating system services. The common language runtime loads and executes code that targets the runtime. This code is therefore called managed code. The runtime gives you, for example, the ability for cross-language integration. 1..NET Framework provides a rich set of class libraries. These include base classes, like networking and input/output classes, a data class library for data access, and classes for use by programming tools, such as debugging services. All of them are brought together by the Services Framework, which sits on top of the common language runtime. 2. ADO.NET is Microsoft’s ActiveX Data Object (ADO) model for the .NET Framework. ADO.NET is not simply the migration of the popular ADO model to the managed environment but a completely new paradigm for data access and manipulation. ADO.NET is intended specifically for developing web applications. This is evident from its two major design principles: >>Disconnected Datasets—In ADO.NET, almost all data manipulation is done outside the context of an open database connection. >>Effortless Data Exchange with XML—Datasets can converse in the universal data format of the Web, namely XML.

106

SUNSAT The Perfect Team

Microsoft .Net
3. The 4th layer of the framework consists of the Windows application model and, in parallel, the Web application model. The Web application model-in the slide presented as ASP.NET-includes Web Forms and Web Services. ASP.NET comes with built-in Web Forms controls, which are responsible for generating the user interface. They mirror typical HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are free to create your own user controls. Web Services brings you a model to bind different applications over the Internet. This model is based on existing infrastructure and applications and is therefore standard-based, simple, and adaptable. Web Services are software solutions delivered via Internet to any device. Today, that means Web browsers on computers, for the most part, but the device-agnostic design of .NET will eliminate this limitation. 4. One of the obvious themes of .NET is unification and interoperability between various programming languages. In order to achieve this; certain rules must be laid and all the languages must follow these rules. In other words we can not have languages running around creating their own extensions and their own fancy new data types. CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET compatibility) must follow. 5.The CLR and the .NET Frameworks in general, however, are designed in such a way that code written in one language can not only seamlessly be used by another language. Hence ASP.NET can be programmed in any of the .NET compatible language whether it is VB.NET, C#, Managed C++ or JScript.NET.

Asp.Net – Controls Types of Controls: 1. Web Controls 2. Html Controls 3. Validation Controls 4. User Controls 1. Web Controls: Web Controls provide a more consistent object model and a higher level of abstraction than HtmlControls – Most HTML elements can also be represented as Web Controls on the server – Web Control versions typically have a more consistent interface (background color is always Back Color property whereas in HTML it may be a style attribute (span) or a property (table) ) – Web Controls also provide higher-level controls with more functionality than primitive HTML elements (like the Calendar control) – Web Controls may render themselves differently based on client browser capabilities Hierarchy of Web controls

107

SUNSAT The Perfect Team

Microsoft .Net
Web controls AdRotator DataGrid DataList Button Calendar CheckBox RadioButton HyperLink Textbox Listbutton RadioButtonList CheckBoxList DropDownList ListBox Panel Table TableRow TableCell Image ImageButton Label

A sample ASP.NET Page written with Webcontrols <%@ Page Language="C#" %> <html> <body> <form runat="Server"> <asp:RadioButton Text="Click me !" runat="server" ID="rb"/></br> <asp:CheckBox Text="Click me !" runat="server" ID="ck"/></br> <asp:Button Text="Click me !" runat="server" ID="btn"/></br> </form> </body> </html> AdRotator The AdRotator is a special control in ASP.NET that is used to display flashing banner ads. The control is capable of displaying ads randomly or sequentially as set by the user. Each time the page is refreshed or reloaded a new ad can be displayed to the user. Also, we can assign priorities in such a way that certain ads are displayed frequently than others. The class hierarchy for this

108

SUNSAT The Perfect Team

Microsoft .Net
control Object Control WebControl AdRotator Notable properties of the AdRotator control are as follows: AdvertisementFile KeywordFilter Target AdvertisementFile The AdvertisementFile property specifies the path to an Advertisement File. The Advertisement file is a well-formed XML document that contains information for the image that needs to be displayed and the page to which the user should be redirected when he clicks the ad. The syntax for the Advertisement file is as follows: <?xml version="1.0" encoding="utf-8" ?> <Advertisements> <Ad> <ImageUrl> URL of the image to be displayed </ImageUrl> <NavigateUrl> URL of the page to which the user should be taken </NavigateUrl> <AlternateText> Text to be displyed as tooltip </AlternateText> <Keyword> Keyword used to filter </Keyword> <Impressions> Weight of the ad </Impressions> </Ad> </Advertisements> The different elements of the Advertisement File: ImageUrl: Specifies the image URL that presents the image for the advertisement NavigateUrl: Specifies the URL of the page to which the user should be taken to when he clicks on the image AlternateText: An optional parameter that specifies the text when the user moves his mouse pointer over the image Keyword: Optional parameter that specifies the keyword (category) like books, programming, etc is as follows:

109

SUNSAT The Perfect Team

Microsoft .Net
Impressions: Optional parameter that provides a number that indicates the weight of the ad in the order of rotation with respect to other ads in the file KeywordFilter The KeywordFilter property specifies a keyword to filter for specific types of advertisements in the XML advertisement file. Each advertisement in the XML advertisement file can be assigned a category keyword. The KeywordFilter property filters the advertisements for the specified keyword. Only advertisements containing the keyword will be selected for the AdRotator control and it is not possible to specify more than one keyword in the KeywordFilter property, nor it is possible to declare multiple keywords in the advertisement file. Target The Target property specifies the name of the browser window or frame that displays the contents of the Web page linked to when the AdRotator control is clicked. This property can also take the following HTML frame-related keywords. _blank: displays the linked content in a new window without frames _parent: displays the linked content in the parent window of the window that contains the link _self: displays the linked content in the same window _top: displays the linked content in the topmost window

2.HTML Controls: HtmlControls are server-side representations of standard HTML elements – Any HTML element in an ASPX page marked with the runat=server attribute will become an HTML control on the server – All derive from HtmlControl class – HTML elements with no distinguished server-side functionality (like div, span, etc.) are all represented as HtmlGenericControl instances Html Controls Html Image HtmlInputFile HtmlInputHidden HtmlInputRadioButton HtmlInputText HtmlInputButton HtmlInputCheckButton HtmlInputImage A sample Code for HtmlControls HtmlForm HtmlButton HtmlSelect HtmlTable HtmlTableCell HtmlTableRow HtmlTextArea HtmlAnchor

110

SUNSAT The Perfect Team

Microsoft .Net
<%@ Page Language="C#" %> <html> <body> <form runat="Server"> <input type=radio runat="server">Clickme</input></br> <input type =text value = "type here!" runat="server"/></br> <input type= button Text="Click me !" runat="server"></br> </form> </body> </html> ASP.NET server controls are reusable components that can perform the same work as traditional HTML controls, but have the additional benefit of being "programmable objects". In other words, they can be programmatically accessed, just like any other .NET object or class, respond to events, get/set properties, and do all the other things objects do. ASP.NET server controls use a tag-like syntax for declaring the various controls used on a web page -- for example: <asp:button id="SampleButton" runat="server" text="I'm A Sample Button!"/> One of the unique qualities of ASP.NET server controls is that, even though their tag syntax is different from HTML's, every ASP.NET server control is rendered to standard HTML after being processed on the server, thus abstracting the functionality of the entire HTML control set. Additional ASP.NET server controls, provide the ability to render rich web content Asp.Net - Validation controls The validator controls are the main elements of the solution. A validator is a visual ASP.NET control that checks a specific validity condition of another control. It generally appears to the user as a piece of text that displays or hides depending on whether the control it is checking is in error. It can also be an image, or can even be invisible and still do useful work. There are six types of validator controls that perform different types of checks. Requiredfield validator: The RequiredFieldValidator control validates input by verifying that the corresponding field isn’t blank. It’s perfect for TextBoxes representing required fields in a form, because if any of those TextBoxes is blank, the RequiredFieldValidator won’t allow the form to be submitted to the server. Here’s an example that verifies a TextBox named “EMail” isn’t blank:

111

SUNSAT The Perfect Team

Microsoft .Net
<asp:TextBox ID="EMail" RunAt="server" /> <asp:RequiredFieldValidator ControlToValidate="EMail" ErrorMessage="Required field" Display="static" Color="red" RunAt="server" /> Because required fields are so common in Web forms, RequiredFieldValidator has the potential to see more use than all the other validation controls combined. It’s often used in conjunction with other validation controls because none of the others run their validation checks on blank fields. RangeValidator The RangeValidator control is the answer to the question “How do I ensure that an input value falls within a specified range?” Suppose you ask the user to type in a percentage, and that valid values range from 0 to 100, inclusive. Here’s how to reject any numbers that fall outside that range: <asp:TextBox ID="Percent" RunAt="server" /> <asp:RangeValidator ControlToValidate="Percent" MinimumValue="0" MaximumValue="100" Type="Integer" ErrorMessage="Value out of range" Display="static" Color="red" RunAt="server" /> The Type attribute tells a RangeValidator what type of data to use in the comparison. If you don’t specify a type, Type defaults to String. Type=“Integer” performs a numeric comparison involving integers. Other valid Type attributes include Currency, Date, and Double. The following example displays an error message if the date typed into a TextBox doesn’t fall in the fourth quarter of 2002: <asp:TextBox ID="MyDate" RunAt="server" /> <asp:RangeValidator ControlToValidate="MyDate" MinimumValue="10/01/2002" MaximumValue="12/31/2002" Type="Date" ErrorMessage="Date Display="static" Color="red" RunAt="server" />

out

of

range"

112

SUNSAT The Perfect Team

Microsoft .Net
In practice, a range-checking date with RangeValidator is of limited usefulness because welldesigned sites permit users to pick dates from a calendar. Manually entered dates are problematic because they’re culture-sensitive (many parts of the world put days before months, for example) and because RangeValidator understands a limited set of date formats. Compare Validator The CompareValidator control validates input by comparing it to a constant value specified with a ValueToCompare attribute or to a value in another control identified with a ControlToCompare attribute. ControlToCompare makes CompareValidator a valuable control for validating input based on other input. Suppose you invite the user to enter minimum and maximum values denoting both ends of a range. It doesn’t make sense to accept a maximum that’s less than the minimum, so you can use a CompareValidator to ensure the integrity of the input. In the following example, the validator signals an error if the maximum is less than the minimum. The Operator attribute specifies that the value entered in the TextBox named “Maximum” must be equal to or greater than the value entered into the TextBox named “Minimum.” The Type attribute identifies the type of data involved in the comparison: <asp:TextBox ID="Minimum" RunAt="server" /> <asp:TextBox ID="Maximum" RunAt="server" /> <asp:CompareValidator ControlToValidate="Maximum" ControlToCompare="Minimum" Type="Integer" Operator="GreaterThanEqual" ErrorMessage="Invalid maximum" Display="static" Color="red" RunAt="server" /> Other supported values for Operator are Equal, NotEqual, GreaterThan, LessThan, LessThanEqual, and DataTypeCheck. The last of these validates the type of data entered by verifying that it matches the type specified in the Type attribute. If you simply wanted to verify that the user input an integer, for example, you could set Type to Integer and Operator to DataTypeCheck. RegularExpressionValidator The most versatile validation control by far is the RegularExpressionValidator, which validates input by verifying that it conforms to a format specified in a regular expression. You can use RegularExpressionValidator to perform a variety of common validation chores, from verifying that an input value contains only numbers to ensuring that e-mail addresses, zip codes, and credit card numbers are well-formed. Here’s a very simple example—one that uses a RegularExpressionValidator to reject input containing non-numeric characters: <asp:TextBox ID="Quantity" RunAt="server" /> <asp:RegularExpressionValidator ControlToValidate="Quantity" ValidationExpression="^\d+$"

113

SUNSAT The Perfect Team

Microsoft .Net
ErrorMessage="Digits only" Display="static" Color="red" RunAt="server" /> In a regular expression, \d represents the digits 0-9 and + means “one or more of.” The expression \d+ means “one or more characters that are digits.” If the user tries to slip in a string with a letter in it, the validator will reject it. ValidationSummary ValidationSummary is a different sort of validation control. It doesn’t perform any validation of its own. It does, however, offer an alternative method for displaying other validators’ error messages by “batching them up” and displaying them as a group. The following example uses a ValidationSummary control to summarize all the validation errors encountered on the page. Note that the other validator controls’ Display attributes are set to None, which prevents them from displaying error messages on their own. Before the page is submitted to the server, the ValidationSummary control checks the other validators. If any of the validation checks failed, the ValidationSummary control displays the corresponding error messages in a bulleted list: <asp:TextBox ID="UserName" RunAt="server" /> <asp:RequiredFieldValidator ControlToValidate="UserName" ErrorMessage="The user name can't be blank" Display="none" RunAt="server" /> <asp:TextBox ID="Password" TextMode="Password" RunAt="server" /> <asp:RequiredFieldValidator ControlToValidate="Password" ErrorMessage="The password can't be blank" Display="none" RunAt="server" /> <asp:RegularExpressionValidator ControlToValidate="Password" ValidationExpression=".{8,}" Display="static" ErrorMessage="The password must contain at least 8 characters" RunAt="server" /> <asp:ValidationSummary DisplayMode="BulletList" HeaderText="This page contains the following errors" Display="static" RunAt="server" />

114

SUNSAT The Perfect Team

Microsoft .Net
The ValidationSummary control’s DisplayMode attribute can be set to BulletList, which displays error messages in a bulleted list; List, which displays error messages in a list without bullets; or SingleParagraph, which displays error messages without bullets or line breaks. HeaderText specifies the text, if any, that appears above the error messages. A ValidationSummary control’s ShowMessageBox and ShowSummary properties can be used to further customize the control’s output. By default, ShowMessageBox is false and ShowSummary is true, meaning that error messages are displayed in the Web page. However, setting ShowMessageBox to true and ShowSummary to false displays the error messages in a pop-up message box (what JavaScript programmers refer to as an alert box because of the JavaScript command used to display it: alert): <asp:ValidationSummary DisplayMode="BulletList" HeaderText="This page contains the following errors" ShowMessageBox="true" ShowSummary="false" RunAt="server" /> Setting both ShowMessageBox and ShowSummary to true causes the validation summary to appear in a message box and in the Web page. CustomValidator When none of the other validators fits the bill, CustomValidator will do the job that no others can. As its name implies, CustomValidator validates input using an algorithm that you supply. If you want CustomValidator to check input on the client side, you provide a JavaScript function to do the checking and identify the function with a ClientValidationFunction attribute. (You can use VBScript if you’d like, but realize that doing so sacrifices compatibility with browsers other than Internet Explorer.) If you want the input checked on the server as well, you provide the validation function and identify it with an OnServerValidate attribute. The following example uses CustomValidator to verify that an input value is an even multiple of 10: <asp:TextBox ID="Amount" RunAt="server" /> <asp:CustomValidator ControlToValidate="Amount" ClientValidationFunction="__validateAmount" OnServerValidate="ValidateAmount" ErrorMessage="Amount must be a multiple of 10" Display="static" Color="red" RunAt="server" /> . .. <script language="JavaScript"> <!-function __validateAmount (source, args) { args.IsValid = (args.Value % 10 == 0); }

115

SUNSAT The Perfect Team

Microsoft .Net
--> </script> <script language="C#" runat="server"> void ValidateAmount (Object sender, ServerValidateEventArgs e) { try { e.IsValid = (Convert.ToInt32 (e.Value) % 10 == 0); } catch (FormatException) { // In case a non-numeric value is entered e.IsValid = false; } } </script> The key is to set args.IsValid to true or false on the client side and e.IsValid to true or false on the server side to indicate whether the input is valid. CustomValidator can be used to apply any validation algorithm you want as long a you’re willing to write the code to back it up. Data Binding Data binding is binding controls to data from databases. With data binding we can bind a control to a particular column in a table from the database or we can bind the whole table to the data grid. Data binding provides simple, convenient, and powerful way to create a read/write link between the controls on a form and the data in their application. ArrayList The ArrayList object is a collection of items containing a single data value.Items are added to the ArrayList with the Add() method. The following code creates a new ArrayList object named mycountries and four items are added: if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") end if An ArrayList can also be sorted alphabetically or numerically with the Sort() method: if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort()

116

SUNSAT The Perfect Team

Microsoft .Net
end if To sort in reverse order, apply the Reverse() method after the Sort() method: if Not Page.IsPostBack then dim mycountries=New ArrayList mycountries.Add("Norway") mycountries.Add("Sweden") mycountries.Add("France") mycountries.Add("Italy") mycountries.TrimToSize() mycountries.Sort() mycountries.Reverse() end if Hashtable The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching through their keys.Items are added to the Hashtable with the Add() method.The following code creates a Hashtable named mycountries and four elements are added: if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if A Hashtable object may automatically generate the text and values to the following controls:
• • • •

asp:RadioButtonList asp:CheckBoxList asp:DropDownList asp:Listbox

if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if <script runat="server">

117

SUNSAT The Perfect Team

Microsoft .Net
sub Page_Load if Not Page.IsPostBack then dim mycountries=New Hashtable mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if end sub sub displayMessage(s as Object,e As EventArgs) lbl1.text="Your favorite country is: " & rb.SelectedItem.Text end sub </script> <html> <body> <form runat="server"> <asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" onSelectedIndexChanged="displayMessage" /> <p><asp:label id="lbl1" runat="server" /></p> </form> </body> </html> The SortedList Object The SortedList object contains items in key/value pairs. A SortedList object automatically sort the items in alphabetic or numeric order.Items are added to the SortedList with the Add() method. if Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") end if if Not Page.IsPostBack then dim mycountries=New SortedList mycountries.Add("N","Norway") mycountries.Add("S","Sweden") mycountries.Add("F","France") mycountries.Add("I","Italy") rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind() end if

118

SUNSAT The Perfect Team

Microsoft .Net
An XML File Here is an XML file named "countries.xml": <?xml version="1.0" encoding="ISO-8859-1"?> <countries> <country> <text>Norway</text> <value>N</value> </country> <country> <text>Sweden</text> <value>S</value> </country> <country> <text>France</text> <value>F</value> </country> <country> <text>Italy</text> <value>I</value> </country> </countries> if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) end if if Not Page.IsPostBack then dim mycountries=New DataSet mycountries.ReadXml(MapPath("countries.xml")) rb.DataSource=mycountries rb.DataValueField="value" rb.DataTextField="text" rb.DataBind() end if Page and Application Context When a Web application runs, ASP.NET maintains information about the current application, each user session, the current HTTP request, the requested page, and so on. ASP.NET contains a series of classes to encapsulate this context information. ASP.NET makes instances of these classes available as intrinsic objects that you can access from your code. The following table lists these intrinsic objects and the classes they are instances of. Object Name Description ASP.NET Class Response

119

SUNSAT The Perfect Team

Microsoft .Net
Provides access to the output stream for the current page. You can use this class to inject text into the page, to write cookies, and more. Request Provides access to the current page request, including the request headers, cookies, client certificate, query string, and so on. You can use this class to read what the browser has sent Context Provides access to the entire current context (including the request object). You can use this class to share information between pages. Server Exposes utility methods that you can use to transfer control between pages, get information about the most recent error, encode and decode HTML text, and more. Application Provides access to application-wide methods and events for all sessions. Also provides access to an application-wide cache you can use to store information. Session Provides information to the current user session. Also provides access to a session-wide cache you can use to store information, along with the means to control how the session is managed. Trace Provides a way to display both system and custom trace diagnostic messages in the HTTP page output. Cookies Overview Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. What Are Cookies? A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site. For example, if a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the user's browser gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk.

120

SUNSAT The Perfect Team

Microsoft .Net
Later, if user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user or check an expiration date. Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately. Cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining continuity in a Web application—that is, of performing state management. Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected. Each request a user makes to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize users when they request a page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed. Cookies are used for many purposes, all relating to helping the Web site remember users. For example, a site conducting a poll might use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials. You can add cookies to the Cookies collection in a number of ways. The following example shows two methods to write cookies: Visual Basic Response.Cookies("userName").Value = "patrick" Response.Cookies("userName").Expires = DateTime.Now.AddDays(1) Dim aCookie As New HttpCookie("lastVisit") aCookie.Value = DateTime.Now.ToString() aCookie.Expires = DateTime.Now.AddDays(1) Response.Cookies.Add(aCookie) C# Response.Cookies["userName"].Value = "patrick"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1); HttpCookie aCookie = new HttpCookie("lastVisit"); aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);

121

SUNSAT The Perfect Team

Microsoft .Net
The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first cookie, the values of the Cookies collection are set directly. Reading Cookies Visual Basic If Not Request.Cookies("userName") Is Nothing Then Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value) End If If Not Request.Cookies("userName") Is Nothing Then Dim aCookie As HttpCookie = Request.Cookies("userName") Label1.Text = Server.HtmlEncode(aCookie.Value) End If C# if(Request.Cookies["userName"] != null) Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value); if(Request.Cookies["userName"] != null) { HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); } Session State Overview ASP.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol, meaning that your Web server treats each HTTP request for a page as an independent request; the server retains no knowledge of variable values used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides the ability to persist variable values for the duration of that session. Session Variables Session variables are stored in a SessionStateItemCollection that is exposed through the System.Web.HttpContext.Session property. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by simply referring to the session variable by name. You do not need to declare a session variable or explicitly add it to the collection. For example, the following code example creates session variables for the first and last name of a user and sets them to values retrieved from TextBox controls. Visual Basic Session("FirstName") = FirstNameTextBox.Text Session("LastName") = LastNameTextBox.Text C# Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;

122

SUNSAT The Perfect Team

Microsoft .Net
By default, session variables can be any valid .NET type. For example, the following code example stores an ArrayList of values in a session variable named "StockPicks." Note that the value returned by the "StockPicks" session variable must be cast as the appropriate type upon retrieval from the SessionStateItemCollection. View State Overview A Web application is stateless. A new instance of the Web page class is created each time the page is requested from the server. This would ordinarily mean that all information associated with the page and its controls would be lost with each round trip. For example, if a user enters information into a text box on an HTML Web page, that information is sent to the server, but is not returned to the client. To overcome this inherent limitation of Web programming, the ASP.NET page framework includes several state-management features, one of which is view state, to preserve page and control values between round trips to the Web server. View state is the method that the ASP.NET page framework uses by default to preserve page and control values between round trips. When the HTML for the page is rendered, the current state of the page and values that need to be retained during postback are serialized into base64-encoded strings and output in the view state hidden field or fields. ADO .NET Most applications need data access at one point of time making it a crucial component when working with applications. Data access is making the application interact with a database, where all the data is stored. Different applications have different requirements for database access. ASP.NET uses ADO .NET (Active X Data Object) as it's data access and manipulation protocol which also enables us to work with data on the Internet. Advantages of ADO.Net
• • • • • •

ADO.NET Does Not Depend On Continuously Live Connections Database Interactions Are Performed Using Data Commands Data Can Be Cached in Datasets Datasets Are Independent of Data Sources Data Is Persisted as XML Schemas Define Data Structures

ADO.NET - Data Architecture Data Access in ADO.NET relies on two components: DataSet and Data Provider. DataSet The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database.

123

SUNSAT The Perfect Team

Microsoft .Net
Data Provider The Data Provider is responsible for providing and maintaining the connection to the database. A DataProvider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET Framework currently comes with two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like Access and Oracle. Each DataProvider consists of the following component classes: The Connection object which provides a connection to the database The Command object which is used to execute a command The DataReader object which provides a forward-only, read only, connected recordset The DataAdapter object which populates a disconnected DataSet with data and performs update Data access with ADO.NET can be summarized as follows: A connection object establishes the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated using the command object or the DataAdapter.

124

SUNSAT The Perfect Team

Microsoft .Net

Component classes that make up the Data Providers The Connection Object The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes: the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object, which can provide connections to a wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to the database. The Command Object

125

SUNSAT The Perfect Team

Microsoft .Net
The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand. Command objects are used to execute commands to a database across a data connection. The Command objects can be used to execute stored procedures on the database, SQL commands, or return complete tables directly. Command objects provide three methods that are used to execute commands on the database: ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE ExecuteScalar: Returns a single value from a database query ExecuteReader: Returns a result set by way of a DataReader object The DataReader Object The DataReader object provides a forward-only, read-only, connected stream recordset from a database. Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader is returned as the result of the Command object's ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can provide rows of data directly to application logic when you do not need to keep the data cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader. The DataAdapter Object The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially the middleman facilitating all communication between the database and a DataSet. The DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's Fill method. After the memory-resident data has been manipulated, the DataAdapter can commit the changes to the database by calling the Update method. The DataAdapter provides four properties that represent database commands: SelectCommand InsertCommand DeleteCommand UpdateCommand When the Update method is called, changes in the DataSet are copied back to the database and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed. Data Adapter Configuration Wizard The DataAdapter Configuration wizard let's you customize your data adapter as you want, like displaying the whole table or displaying selected columns from the table and so on. To start, open a new database in Access, name it as books, create a table, Table1 with some fields in it and save the database in the C: drive of your machine. To start creating your own DataAdapter, open a blank form and add a button (Button1) and a DataGrid control to it from the toolbox. Our intention here is to display the table or some columns in the table which we created in Access in the DataGrid control when Button1 is clicked. To do that, click on the Data tab in the toolbox and double-click OleDbDataAdapter object. We are using OleDbDataAdapter here as we are working

126

SUNSAT The Perfect Team

Microsoft .Net
with an OleDb data source. After you select OleDbDataAdapter from the data tab in the toolbox it gets added to the component tray beneath the Web Forms designer and opens the Data Adapter Configuration wizard dialog box which looks like the image below.

Click the Next> button in the Data Adapter Configuration wizard to select the data connection you want to use. The dialog box that opens up look like the image below.

Since we are working with our own table, select the New Connection button in that dialog box which opens up the Data Link properties dialog. The Data Link Properties dialog looks like the image below.

127

SUNSAT The Perfect Team

Microsoft .Net

In the Data Link properties dialog click the Provider tab and select "Microsoft Jet 4.0 OLE DB Provider" from the list of available providers. After selecting the provider from the Provider tab click Next> button to take you to the Connection tab. Click on the ellipse where it says "Select or enter a database name" and browse for the database on the local drive. Since we are working with our own database (Books.mdb) located on the C: drive, select that. Click on the "Test Connection" button to test the connection and if the connection succeeds, click OK. Clicking OK displays a dialog box like the image below.

It's here where we will generate the SQL Statement we use with this data adapter. Click next on this dialog box which takes you to another dialog like the image below.

128

SUNSAT The Perfect Team

Microsoft .Net

It's here where we build our SQL Queries. To build your query click the Query Builder button on this dialog. Once you click that button, the Query Builder dialog opens with a list that displays all the tables in the database with which we are working. In this case it displays only one table as we created only one table in the books database. The Query Builder dialog looks like the image below. Select Table1 in this dialog and click Add to add Table1 to the Query Builder dialog. You can select entire table to be displayed in the DataGrid or just some columns. To display entire table in the DataGrid select the checkbox named "All Columns" in the small dialog named "Table1" which automatically builds the SQL statement for us. If you want to display specific columns from the table in the DataGrid, check on the columns you want to display. Once you finish with that, click next.

129

SUNSAT The Perfect Team

Microsoft .Net
The dialog that opens when you click next looks like the image below.

This dialog lists the configuration of the data adapter and lists the results. Click finish to close the Data Adapter Configuration wizard. Accessing SQL-based Data An application typically needs to perform one or more select, insert, update, or delete queries to a SQL database. The following table shows an example of each of these queries. Query Simple Select Join Select Insert Update Delete Example SELECT * from Employees WHERE FirstName = 'Bradley'; SELECT * from Employees E, Managers M WHERE E.FirstName = M.FirstName; INSERT into Employees VALUES ('123-456789','Bradley','Millington','Program Manager'); UPDATE Employees SET Title = 'Development Lead' WHERE FirstName = 'Bradley'; DELETE from Employees WHERE Productivity < 10;

To give your page access to the classes you will need to perform SQL data access, you must import the System.Data and System.Data.SqlClient namespaces into your page. <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> To perform a select query to a SQL database, you create a SqlConnection to the database passing the connection string, and then construct a SqlDataAdapter object that contains your query

130

SUNSAT The Perfect Team

Microsoft .Net
statement. To populate a DataSet object with the results from the query, you call the command's Fill method. SqlConnection myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes"); SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection); DataSet ds = new DataSet(); myCommand.Fill(ds, "Authors"); The benefit of using a dataset is that it gives you a disconnected view of the database. You can operate on a dataset in your application, and then reconcile your changes with the actual database later. For long-running applications this is often the best approach. For Web applications, you are usually performing short operations with each request (commonly to simply display the data). You often don't need to hold a DataSet object over a series of several requests. For situations like these, you can use a SqlDataReader. A SqlDataReader provides a forward-only, read-only pointer over data retrieved from a SQL database. To use a SqlDataReader, you declare a SqlCommand instead of a SqlDataAdapter. The SqlCommand exposes an ExecuteReader method that returns a SqlDataReader. SqlConnection myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes"); SqlCommand myCommand = new SqlCommand("select * from Authors", myConnection); myConnection.Open(); SqlDataReader dr = myCommand.ExecuteReader(); ... myConnection.Close(); When performing commands that do not require data to be returned, such as inserts, updates, and deletes, you also use a SqlCommand. The command is issued by calling an ExecuteNonQuery method, which returns the number of rows affected. Note that the connection must be explicitly opened when you use the SqlCommand; the SqlDataAdapter automatically handles opening the connection for you. SqlConnection myConnection = new SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes"); SqlCommand myCommand = new SqlCommand( "UPDATE Authors SET phone='(800) 555-5555' WHERE au_id = '123-45-6789'", myConnection); myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close(); Performing a Parameterized Select

131

SUNSAT The Perfect Team

Microsoft .Net
The SqlDataAdapter maintains a Parameters collection that can be used to replace variable identifiers (denoted by an "@" in front of the name) with values. You add a new SqlParameter to this collection that specifies the name, type, and size of the parameter, and then set its Value property to the value of the select. myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2)); myCommand.SelectCommand.Parameters["@State"].Value = MySelect.Value; Writing and Using Stored Procedures In general, performing ad hoc queries comes at the expense of performance. Using stored procedures can reduce the cost of performing heavy database operations in an application. A stored procedure is easy to create, and can even be done using a SQL statement. The following code example creates a stored procedure that simply returns a table. CREATE Procedure GetAuthors AS SELECT * FROM Authors return GO You can create stored procedures that accept parameters as well. For example: CREATE Procedure LoadPersonalizationSettings (@UserId varchar(50)) AS SELECT * FROM Personalization WHERE UserID=@UserId return GO Using a stored procedure from an ASP.NET page is just an extension of what you've learned so far about the SqlCommand object. The CommandText is just the name of the stored procedure instead of the ad hoc query text. You indicate to the SqlCommand that the CommandText is a stored procedure by setting the CommandType property. myCommand.SelectCommand.CommandType = CommandType.StoredProcedure; Authentication Authentication is the means by which you obtain the Identity of the User by validating their credentials against a known Authority, ie: Active Directory, Database Store, Microsoft Passport Account etc. If the credentials can't be validated then the Authentication process fails and the User will assume the Identity of IUSR_Anonymous. Remember that the Web is anonymous by nature, so they only way to determine who a particular visitor is to authenticate them by having them provide user credentials (a username/password, usually). There are 4 types of authentications. 1.WINDOWS AUTHENTICATION 2.FORMS AUTHENTICATION 3.PASSPORT AUTHENTICATION 4.NONE/CUSTOM AUTHENTICATION The authentication option for the ASP.NET application is specified by using the tag in the Web.config file, as shown below:

132

SUNSAT The Perfect Team

Microsoft .Net
1. WINDOWS AUTHENTICATION Schemes I. Integrated Windows authentication II. Basic and basic with SSL authentication III. Digest authentication IV. Client Certificate authentication 2. FORMS AUTHENTICATION You, as a Web application developer, are supposed to develop the Web page and authenticate the user by checking the provided user ID and password against some user database 3.PASSPORT AUTHENTICATION A centralized service provided by Microsoft, offers a single logon point for clients. Unauthenticated users are redirected to the Passport site 4. NONE/CUSTOM AUTHENTICATION: If we don’t want ASP.NET to perform any authentication, we can set the authentication mode to “none”. The reason behind this decision could be: We don’t want to authenticate our users, and our Web site is open for all to use. We want to provide our own custom authentication Introduction to web services Webservices are services exposed over the internet. Typically, webservice is just like any other class library, written in any language. What make it a 'web service' is, it can be accessed across internet. Eventhough webservice is a new technology with a wide range of usage, it is a pretty simple concept. It doesn't require much additional knowledge to create webservices if you are already familiar with C# or VB.NET. (Web services are not specific to .NET. Even Java has web service applications, but here we are discussing only the .NET web services.) As we mentioned, web services are exposed over internet. To make this happen, it has to be hosted with a web site. Othen than hosted as part of a web site to make this visible across internet, web services have no web pages or UI. It is just a set of classes with public/private methods and properties. Web services are a group of [web] methods. Consumer applications can treat this as just another class library. Regular class libraries are located along with the same application and we can call any methods in the class libraries (assemblies). But in case of web services, the assembly is located in the internet server. The consumer application will not have direct access to the assembly. Consumer applications have to add a reference to the webservice URL and then call methods in it. The method call goes across the internet using SOAP protocal and results are returned across internet in the form of XML. The communication across internet happens transparently and the application need not know anything about this communication. Creating a simple web service

133

SUNSAT The Perfect Team

Microsoft .Net
If you are using VS.NET, it won't take more than 2-3 minutes to create your first webservice. Follow the steps below to create a web service: * Choose New Project from VS.NET and create a C# project of type 'ASP.NET Web Service' and give the name 'MyWebService' * The new project will have a default page 'Service1.asmx'. This is your first web service page. Web service pages have the extension .asmx (like ASP.NET pages have the extension .aspx) * The code behind file 'Service1.asmx.cs' have a class 'Service1'. This is like other regular classes with the only difference that it inherits the system class System.Web.Services.WebService. This is required for web service classes. * VS.NET creates a sample method for you. All you have to do is, uncomment the following method in Service1.asmx.cs [WebMethod] public string HelloWorld() { return "Hello World"; } Note that this method is pretty much same as any other regular method. The only difference is, it has an attribute [WebMethod]. This attribute make the method visible across internet. If you remove this attribute, your application will still compile, but the consumer applications cannot call this method across internet. Ok, thats all you have to do to create a simple webservice. Build your solution and your web service is ready to be called by other applications. Create a consumer application A wide range of applications can consume the web services, including web page, other web services, windows applications etc. let us create a sample windows application and call our web service. * Create a new C# Windows Application. * Right click on the 'References' in the Solution Explorer, under your project name. Choose 'Web References'. * Another window will open and will allow you to specify the URL of the web service to be referenced. Type the URL of your web service in the space provided for 'URL'. If you have created the web service in the local machine's default web site, the URL might be like this : http://localhost/MyWebService/Service1.asmx If you have given a different name fro the project or if you have changed the default service name, then your URL may differ. Type the URL and press enter. It will attempt to connect with the web service and if succeded it will retrieve the public web methods and display. Once you get this success screen, press the 'Add Reference' button on the screen to add the web reference to your application. There is a space to specify the 'web reference name', which will have the default value 'localhost'. Leave it as it is. Now you are ready to make calls to the webservice. Just use the following code in your application: localhost.Service1 service = new localhost.Service1();

134

SUNSAT The Perfect Team

Microsoft .Net
string result = service.HelloWorld(); MessageBox.Show( result ); Let us analyze our code. The first line creates an instance of the Service1 class, just like any regular class. Only thing is it uses the namespace 'localhost'. This is same as the 'web reference name' we specified while adding the web reference. We can use any web reference name when we add the reference and have to use the same name as namespace while making calls to the web service class. In the second line, we are actually calling the web method 'HelloWorld()' and it returns the result as a string. Note this is just like any other method call. So, your application makes the call to web service as if it is calling any local class library calls!! The communication with web service, wrapping your calls in SOAP/XML, retrieve results from web service, unwrap the SOAP/XML to get the actual result etc are done behind the scene by the framework and you need not do any additional work to make all this work. Now you can go back to your web service, add more methods with different parameters and play around with that. You will be able to call methods in the web service just like you use any local class. Note that when you make any changes to the method name or parameters, or if you add new methods, you will need to refresh your web reference to get access to the updated web service methods. To do this, go to the Server Explorer, right click on the web reference name 'localhost' under the 'Web References'. Then choose 'Refresh'. This will communicate with the web service again and retrieve the latest web service data. How does all this work? To make calls to any classes, your application need to know the details of the class. To successfully compile your code, it has to have information about the class, what are the public methods and properties etc. But in your sample code which calls the web service, the actual Service1 class resides in the web (in your case, in your local web server). So how does the application compile without having the 'Service1' class in your application? This is where the framework help you. When you add a 'web reference' to the web service URL, VS.NET actually creates local proxy in your application. A local proxy is a minimal version of the actual class. The proxy has just the sufficient information about the 'real class', which is required for your application to successfully compile. The proxy class has the list of all public web methods in the real web service class and it knows the parameters and their data types of each method. The most important thing is, your application is actually using this proxy class and not the real web service class. localhost.Service1 service = new localhost.Service1(); string result = service.HelloWorld(); MessageBox.Show( result ); In the above code, localhost.Service1 is actually the proxy class (a representative of a real class), which is created automatically by VS.NET when you added the web reference. You are creating an instance of the proxy class and calling the 'HelloWorld()' method of this proxy. Since the proxy class knows that it is 'only a proxy of the real class', it redirects all calls to the 'real web service class'. The method 'HelloWorld()' in the proxy class takes care of converting the call to a

135

SUNSAT The Perfect Team

Microsoft .Net
web request using SOAP/XML. After retrieving the result of the web request to the real web service class, this proxy class takes the responsibility of parsing the SOAP/XML response and returning only the result string to the calling applicationn. So the proxy class does all the dirty job for you. The proxy class has no implementaion of the functionality. It just redirects the call to the web service. So, if you make any changes to the implementation in the web service, still you will get the 'updated result' when you make calls to web service. But, if you change the method name, or change the parameter types in the web service and do not 'refresh the web reference', then your application will compile with the old proxy. But when the proxy redirect the call to the web service, it will find that the parameters or method names do not match and it will fail. So, if there is any change in the method names or parameters, you must refresh your web reference.

136

SUNSAT The Perfect Team

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.