192-1-SY-BSC-CS-SEM-IV-.Net-technology-INNER-PAGES-munotes

Page 1

1 1 THE .NET FRAMEWORK Unit Structure : 1.0 Introduction 1.1 Objectives of .net framework 1.2 Components of .NET framework 1.3 .Net Framework Design Principle 1.4 .NET Languages 1.5 Common Language Runtime (CLR) 1.6 .NET class library 1.7 Summary 1.8 References 1.8 Questions 1.0 INTRODUCTION The .NET Framework .NET framework is an integral windows component that helps in building and executing the next generation of applications and XML web services. It is a set of Microsoft software technologies for connecting your world of information, people, systems, and devices. 1.1 OBJECTIVES OF .NET FRAMEWORK • To provide a very high degree of language interoperability • To provide a runtime environment that completely manages code execution • To provide high-level code security through code access security and strong type checking • To facilitate application communication by using industry standards such as SOAP and XML. • To simplify Web application development • To provide a consistent object-oriented programming environment whether object code is stored and executed locally, executed locally but Internet-distributed, or executed remotely. • To provide a code-execution environment that minimizes software deployment and versioning conflicts. munotes.in

Page 2


2 .Net technology • To provide a code-execution environment that promotes safe execution of code, including code created by an unknown or semi-trusted third party. • To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments. • To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications. • To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code. 1.2 COMPONENTS OF .NET FRAMEWORK
Fig. 1.1 Components of .NET framework • The .Net framework allows infrastructural services to all the applications developed in .Net compliant language. • It is an engine that provides runtime services using its component like Common Runtime Language. • The .Net framework provides tools and technologies to develop windows and web applications. • The .Net framework mainly contains two components : 1. Common Language Runtime(CLR) 2. .Net Framework Class Library (FCL) 1. Common Language Runtime (CLR) • .Net Framework provides runtime environment called Common Language Runtime (CLR).
munotes.in

Page 3


3
The .Net Framework • It runs all the .Net programs. • CLR provides memory management and thread management. • It allocates the memory for scope and deallocates the memory. • The code which runs under the CLR is called as Managed Code. • Programmers need not to worry on managing the memory if the programs are running under the CLR. (memory management and thread management) • Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft Intermediate Language(MSIL) intern this will be converted to Native Code by CLR. • There are currently over 15 language compilers being built by Microsoft and other companies also producing the code that will execute under CLR. 2. .Net Framework Class Library (FCL) • It accesses the library classes and methods. • It is also called as Base Class Library. • It is common for all types of application. Following are the applications in .Net Class Library: 1. XML web services 2. Windows services 3. Windows application 4. Web applications 5. Console application 1.3 .NET FRAMEWORK DESIGN PRINCIPLE Interoperability – The .Net framework provides a lot of backward support. Suppose you had an application built on an older version of the .Net framework, say 2.0. And if you tried to run the same application on a machine that had the higher version of the .Net framework, say 3.5. The application would still work. This is because Microsoft ensures that older framework versions gel well with the latest version. Portability – Applications built on the .Net framework can be made to work on any Windows platform. And now in recent times, Microsoft is also envisioning making Microsoft products work on other platforms, such as iOS and Linux. Security – The .NET Framework has a good security mechanism. The inbuilt security mechanism helps in both the validation and verification of munotes.in

Page 4


4 .Net technology applications. Every application can explicitly define its security mechanisms. Each security mechanism is used to grant the user access to the code or to the running program. Memory management – The Common Language runtime does all the work or memory management. The .Net framework has all the capability to see those resources, which are not used by a running program. It would then release those resources accordingly. This is done via a program called the “Garbage Collector” which runs as part of the .Net framework. The garbage collector runs at regular intervals and keeps on checking which system resources are not utilized, and frees them accordingly. Simplified deployment – The .Net framework also has tools, which can be used to package applications built on the .Net framework. These packages can then be distributed to client machines. The packages would then automatically install the application. 1.4 .NET LANGUAGES .NET Languages are computer programming languages that are used to produce programs that execute within the Microsoft .NET Framework. Microsoft provides several such languages, including C#, Visual Basic .NET, and C++/CLI. Regardless of which .NET language is used, the output of the language compiler is a representation of the same logic in an intermediate language named Common Intermediate Language. Before the program is executed, CIL is compiled to object code appropriate for the machine on which the program is executing. This last compilation step is usually performed by the Common Language Runtime component of the framework at the moment the program is invoked, though it can be manually performed at an earlier stage. While there are currently more than 40 languages with compilers for the .NET Framework, only a small number of them are widely used and supported by Microsoft. The rest is composed of languages developed by third party vendors. The types of applications that can be built in the .Net framework are classified broadly into the following categories. WinForms – This is used for developing Forms-based applications, which would run on an end-user machine. Notepad is an example of a client-based application. ASP.Net – This is used for developing web-based applications, which are made to run on any browser such as Internet Explorer, Chrome, or Firefox. The Web application would be processed on a server, which would have Internet Information Services Installed. Internet Information Services or IIS is a Microsoft component that is used to execute an Asp.Net application. The result of the execution is then sent to the client machines, and the output is shown in the browser. munotes.in

Page 5


5
The .Net Framework ADO.Net – This technology is used to develop applications to interact with Databases such as Oracle or Microsoft SQL Server. Microsoft always ensures that .Net frameworks are in compliance with all the supported Windows operating systems. Few examples of Microsoft .NET languages C# - Microsoft's flagship .NET Framework language which bears similarities to the C++ and Java languages. Visual Basic .NET - A completely redesigned version of the Visual Basic language for the .NET Framework. This also includes Visual Basic 2005 (v8.0). VBx, a dynamic version of Visual Basic .NET that runs on top of the Dynamic Language Runtime. C++/CLI and the deprecated Managed C++ - A managed version of the C++ language. J# - A Java and J++ .NET transitional language. JScript .NET - A compiled version of the JScript language. Windows PowerShell - An interactive command line shell/scripting language that provides full access to the .NET Framework. IronPython - A .NET implementation of the Python programming language developed by Jim Hugunin at Microsoft. IronRuby - A dynamically compiled version of the Ruby programming language targeting the .NET Framework. F#, a member of the ML programming language family. 1.5 COMMON LANGUAGE RUNTIME (CLR)
fig 1.2 CLR
munotes.in

Page 6


6 .Net technology As part of Microsoft's .NET Framework, the Common Language Runtime (CLR) is programming that manages the execution of programs written in any of several supported languages, allowing them to share common object-oriented classes written in any of the languages. Benefits of CLR :  Performance improvements.  The ability to easily use components developed in other languages.  Extensible types provided by a class library.  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.  Support for custom attributes.  Garbage collection.  Use of delegates(a class that can hold a reference to a method) instead of function pointers for increased type safety and security. .NET CLR is a runtime environment that manages and executes the code written in any .NET programming language. CLR is the virtual machine component of the .NET framework. Language's compiler compiles the source code of applications developed using .NET compliant languages into CLR's intermediate language called MSIL, i.e., Microsoft intermediate language code. This code is platform-independent. It is comparable to byte code in java. Metadata is also generated during compilation and MSIL code and stored in a file known as the Manifest file. This metadata is generally about members and types required by CLR to execute MSIL code. A just-in-time compiler component of CLR converts MSIL code into the native code of the machine. This code is platform-dependent. CLR manages memory, threads, exceptions, code execution, code safety, verification, and compilation. fig 1.3 conversion process of source code to native code Main components of CLR • Common type system • Common language speciation
munotes.in

Page 7


7
The .Net Framework • Garbage Collector • Just in Time Compiler • Metadata and Assemblies
fig 1.4 .NET application processing Common type system (CTS) CTS provides guidelines for declaring, using and managing data types at runtime. It offers cross-language communication. For example, VB.NET has an integer data type, and C# has an int data type for managing integers. After compilation, Int32 is used by both data types. So, CTS provides the data types using managed code. A common type system helps in writing language-independent code. Common Language Specification (CLS) Common Language Specification (CLS) contains a set of rules to be followed by all NET-supported languages. The common rules make it easy to implement language integration and help in cross-language inheritance and debugging. Each language supported by NET Framework has its own syntax rules. But CLS ensures interoperability among applications developed using NET languages. Garbage Collection Garbage Collector is a component of CLR that works as an automatic memory manager. It helps manage memory by automatically allocating memory according to the requirement. It allocates heap memory to objects. When objects are not in use, it reclaims the memory allocated to them for future use. It also ensures the safety of objects by not allowing one object to use the content of another object. Just in Time (JIT) Compiler JIT Compiler is an important component of CLR. It converts the MSIL code into native code (i.e., machine-specific code). The .NET program is compiled either explicitly or implicitly. The developer or programmer calls
munotes.in

Page 8


8 .Net technology a particular compiler to compile the program in the explicit compilation. In implicit compilation, the program is compiled twice. The source code is compiled into Microsoft Intermediate Language (MSIL) during the first compilation process. The MSIL code is converted into native code in the second compilation process. This process is called JIT compilation. Metadata Metadata is binary information about the program, either stored in a CLR Portable Executable file (PE) along with MSIL code or in the memory. During the execution of MSIL, metadata is also loaded into memory for proper interpretation of classes and related. Information used in code. So, metadata helps implement code in a language-neutral manner or achieve language interoperability. Assemblies An assembly is a fundamental unit of physical code grouping. It consists of the assembly manifest, metadata, MSIL code, and a set of resources like image files. It is also considered a basic deployment unit, version control, reuse, security permissions, etc. Functions of CLR Following are the functions of the CLR. • It converts the program into native code. • Handles Exceptions • Provides type-safety • Memory management • Provides security • Improved performance • Language independent • Platform independent • Garbage collection • Provides language features such as inheritance, interfaces, and overloading for object-oriented programs. 1.6 .NET CLASS LIBRARY .NET Framework Class Library is the collection of classes, namespaces, interfaces, and value types that are used for .NET applications. It contains thousands of classes that support the following functions. • Base and user-defined data types • Support for exceptions handling • input/output and stream operations munotes.in

Page 9


9
The .Net Framework • Communications with the underlying system • Access to data • Ability to create Windows-based GUI applications • Ability to create web client and server applications • Support for creating web services The .NET Framework provides a large and very rich library of classes to be used and extended by application developers. Reuse and extension of these classes will allow developers to be more productive and to develop more robust and feature-rich applications in a shorter time frame because the class library provides many features that previously had to be built from scratch. .NET class library is divided into namespaces so that it can be easy to work with and understand. The System namespace is considered the root namespace which acts as a container for all the base data type classes used by application developers to build frameworks and applications. The .NET class library is common to all languages of .NET. In other words, the way one access files in C# will be exactly the same in VB.NET and for all other languages of .NET. The .NET Framework class library contains classes that allow the development of the following type of applications: • Console applications • Window applications • Windows services • ASP .NET Web applications • Web services • Windows communication foundation applications • Windows presentation foundation applications • Window workflow foundation applications The library’s classes are organized using a hierarchy of namespace. For example, all the classes performing I/O operations are located in the System.IO namespaces, and classes that manipulate regular expressions are located in the System.Text.RegularExpressions namespace. Class libraries are the shared library concept for .NET. They enable you to componentize useful functionality into modules that can be used by multiple applications. They can also be used as a means of loading functionality that is not needed or not known at application startup. Class libraries are described using the .NET Assembly file format. munotes.in

Page 10


10 .Net technology There are three types of class libraries:- Platform-specific class libraries: They have access to all the APIs in a given platform (for example, .NET Framework on Windows, Xamarin iOS), but can only be used by apps and libraries that target that platform. Portable class libraries: They have access to a subset of APIs, and can be used by apps and libraries that target multiple platforms. .NET Standard class libraries: They are a merger of the platform-specific and portable library concepts into a single model that provides the best of both. 1.7 SUMMARY This chapter briefs about role of .NET framework while designing an application. Also, it gives you idea about components and design principles of .NET framework. It also states various languages used in .NET for designing any windows or web application. The CLR which is main component of .NET framework is discussed in this chapter and class library which provides various in built functions and support to execute the application smoothly is also discussed. 1.8 REFERENCES 1. Beginning ASP.NET 4.5 in C#, Matthew MacDonald, Apress(2012) 2. The Complete Reference ASP .NET, MacDonald, Tata McGraw Hill 3. Beginning ASP.NET 4 in C# and VB Imar Spanajaars, WROX 1.9 QUESTIONS 1. Write a note on .NET framework. 2. What are the various components of .NET framework? 3. Write a note on CLR. 4. Explain the use of .NET class library. 5. Explain the terms CTS, CLS, and JIT.  munotes.in

Page 11

11 2 C# LANGUAGE BASICS Unit Structure : 2.0 Introduction 2.1 Comments 2.2 Variable 2.3 Data types 2.4 Variable operations 2.5 Object based manipulation 2.6 Call by Value and Call by Reference 2.7 C# Constructors 2.8 Casting Objects 2.9 Summary 2.10 References 2.11 Questions 2.0 INTRODUCTION C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web apps, desktop apps, mobile apps, games, and much more. C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class. 2.1 COMMENTS Comments are used in a program to help us in understanding a piece of code. Comments are completely ignored by the compiler. In C#, there are 2 types of comments: • Single Line Comments ( // ) • Multi Line Comments (/* */) Single Line Comments Single line comments start with a double slash //. The compiler ignores everything after // to the end of the line. For example, int a = 7 + 9; // Adding 7 and 9 munotes.in

Page 12


12 .Net technology Multi Line Comments Multi line comments start with /* and ends with */. Multi line comments can span over multiple lines. /* This is a first Program in C#. This basic program prints Hello World. */ using System; namespace HelloWorld { class Program { public static void Main(string[] args) { // Prints Hello World Console.WriteLine("Hello World!"); } } } 2.2 VARIABLE A variable is the name of a memory location. It is used to store data. Its value can be changed and it can be reused many times. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory, and the set of operations that can be applied to the variable. Rules for defining variables • A variable can have alphabets, digits, and underscore. • A variable name can start with the alphabet and underscore only. It can't start with a digit. • No white space is allowed within the variable name. • A variable name must not be any reserved word or keyword e.g. char, float etc. Defining Variables int i, j, k; char c, ch; float f, salary; double d; You can initialize a variable at the time of definition as − int i = 100; munotes.in

Page 13


13
C# language basics Valid variable names: int s; int _s; int s05; Invalid variable names: int 5; int x y; int double; Example using System; namespace VariableDefinition { class Program { static void Main(string[] args) { short a; int b ; double c; a = 10; b = 20; c = a + b; Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c); Console.ReadLine(); } } } 2.3 DATA TYPES A data type specifies the type of data that a variable can store such as integer, floating, character etc. The variables in C#, are categorized into the following types −  Value types  Reference types  Pointer types munotes.in

Page 14


14 .Net technology
Fig. 2.1 classification of data types Value Type - Value type variables can be assigned a value directly. The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value. Type Represents bool Boolean value byte unsigned integer ushort 16-bit unsigned integer uint 32-bit unsigned integer ulong 64-bit unsigned integer char unicode character decimal Decimal values double Double precision floating point float Single precision floating point sbyte 8-bit Signed integer short 16-bit signed integer int 32-bit Signed integer long 64-bit Signed integer Reference Type The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.
munotes.in

Page 15


15
C# language basics Object Type The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. When a value type is converted to an object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. Dynamic Type We can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time. String Type The String Type allows us to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted. Pointer Type Pointer type variables store the memory address of another type. 2.4 VARIABLE OPERATIONS Operators are symbols that are used to perform operations on operands. Operands may be variables and/or constants. For example, in 2+3, + is an operator that is used to carry out addition operation, while 2 and 3 are operands. Operators are used to manipulate variables and values in a program. C# supports a number of operators that are classified based on the type of operations they perform. There are following types of operators to perform different types of operations in C# language. • Arithmetic Operators • Relational Operators • Logical Operators • Bitwise Operators • Assignment Operators • Unary Operators munotes.in

Page 16


16 .Net technology • Ternary Operators • Misc Operators
fig 2.2 types of operators Arithmetic Operators Arithmetic operators are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. C# Arithmetic Operators Operato r Operator Name Example + Addition Operator 6 + 3 evaluates to 9 - Subtraction Operator 10 - 6 evaluates to 4 * Multiplication Operator 4 * 2 evaluates to 8 / Division Operator 10 / 5 evaluates to 2 % Modulo Operator (Remainder) 16 % 3 evaluates to 1 Relational Operators Relational operators are used to check the relationship between two operands. If the relationship is true the result will be true, otherwise, it will result in false. C# Relational Operators Operator Operator Name Example == Equal to 6 == 4 evaluates to false > Greater than 3 > -1 evaluates to true < Less than 5 < 3 evaluates to false >= Greater than or equal to 4 >= 4 evaluates to true <= Less than or equal to 5 <= 3 evaluates to false != Not equal to 10 != 2 evaluates to true
munotes.in

Page 17


17
C# language basics Logical Operators Logical operators are used to perform logical operations such as and, or, not. Logical operators operate on boolean expressions (true and false) and return boolean values. C# Logical operators Operand 1 Operand 2 OR (||) AND (&&) NOT(!) operand 1 true true true true false true false true false false false true true false true false false false false true Bitwise Operators Bitwise and bit shift operators are used to perform bit level operations on integer (int, long, etc) and boolean data. These operators are not commonly used in real life situations. p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Operator Description Example & Binary AND
Copies a bit if it exists in both operands A = 14, B = 11
(A & B) = 10 | Binary OOOR
Copies a bit if it exists in wither
operand A = 14, B = 11
(A | B) = 15 ^ Binary XOR
Copies a bit if it is set in one operand
but not in both A = 14, B = 11
(A ^ B) = 5 ~ Binary ones complement
Flipping bits A = 26
(~A) = 229 << Binary left shift A = 42 munotes.in

Page 18


18 .Net technology Left operands value is moved left by
number of bits specified by right
operand A << 1 = 84
A << 2 = 168 >> Binary right shift
Left operands value is moved right by
number of bits specified by right
operand A = 42
A >> 1 = 21
A << 2 = 10 Assignment Operators Operator Description Example = Assignment
Assigns value from right to left side C = A + B += Add AND assignment
Adds right operand to left operand and
assign result to left operand C += A
C = C + A -= Subtract AND assignment
Subtracts right operand from left
operand and assign result to left
operand C -= A
C = C - A *= Multiply AND assignment
Multiplies right operand with left
operand and assign result to left
operand C *= A
C = C * A /= Divide AND assignment
Divides left operand with right
operand and assign result to left
operand C /= A
C = C / A Unary operator The unary operators operates on a single operand. C# unary operators Operator Operator Name Description + Unary Plus Leaves the sign of operand as it is - Unary Minus Inverts the sign of operand ++ Increment Increment value by 1 -- Decrement Decrement value by 1 ! Logical Negation (Not) Inverts the value of a boolean munotes.in

Page 19


19
C# language basics Ternary Operator The ternary operator ? : operates on three operands. It is a shorthand for if-then-else statement. Ternary operator can be used as follows: variable = Condition? Expression1 : Expression2; If the expression stated by Condition is true, the result of Expression1 is assigned to variable. If it is false, the result of Expression2 is assigned to variable. int number = 10; string result; result = (number % 2 == 0)? "Even Number" : "Odd Number"; Console.WriteLine("{0} is {1}", number, result); Miscellaneous Operators sizeof() Returns size of a data type sizeof(int) typeof() Returns type of a class typeof(StreamReader) & Returns address of an variable &a * Pointer to a variable *a ?: Conditional expression if condition is true ? Then
x : else y is Determines whether an object
is of a certain type if(Ford is Car)
checks if ford is an object
of the car class as Cast without raising an
exception if the cast fails object obj = new
StringReader(“Hello”)
StringReader r = obj as
StringReader 2.5 OBJECT BASED MANIPULATION  A C# program consists of the following parts: – Namespace declaration – A class – Class methods – Class attributes – A Main method – Statements and Expressions – Comments munotes.in

Page 20


20 .Net technology
• The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements. • The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld. • The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main. • The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. • The next line /*...*/ is ignored by the compiler and it is put to add comments in the program. • The Main method specifies its behavior with the statement Console.WriteLine("Hello World"); • WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen. • The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.
munotes.in

Page 21


21
C# language basics Conditional logic Ans. Decision making structures requires the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. C# provides following types of decision making statements. if statement An if statement consists of a boolean expression
followed by one or more statements. if...else
statement An if statement can be followed by an optional else
statement, which executes when the boolean
expression is false. nested if
statements You can use one if or else if statement inside
another if or else if statement(s). switch statemen t A switch statement allows a variable to be tested for
equality against a list of values. • if Statement An if statement consists of a boolean expression followed by one or more statements. Syntax if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } If the boolean expression evaluates to true, then the block of code inside the if statement is executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) is executed. munotes.in

Page 22


22 .Net technology Flow Diagram
fig. 2.3 if - flow chart
o/p :- a is less than 20; value of a is : 10 • if...else Statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. Syntax
munotes.in

Page 23


23
C# language basics
fig 2.4 if…else – flow chart

munotes.in

Page 24


24 .Net technology O/p a is not less than 20; value of a is : 100 • Nested if Statements you can use one if or else if statement inside another if or else if statement(s). Syntax
Example

munotes.in

Page 25


25
C# language basics  O/p :- Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 • Switch Statement A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Syntax
Flow Diagram
fig. 2.5 switch
munotes.in

Page 26


26 .Net technology
O/P :- Well done Your grade is B Loops A loop statement allows us to execute a statement or a group of statements multiple times. Types of loop statements • while loop :- It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body. • for loop :- It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. • do...while loop :- It is similar to a while statement, except that it tests the condition at the end of the loop body
munotes.in

Page 27


27
C# language basics While Loop A while loop statement in C# repeatedly executes a target statement as long as a given condition is true. Syntax Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. Flow Diagram
fig 2.6 while condition
munotes.in

Page 28


28 .Net technology
O/P
For Loop A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Syntax
munotes.in

Page 29


29
C# language basics  The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.  Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.  After the body of the for loop executes, the flow of control jumps back up to the increment statement.  The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates. Flow diagram
fig 2.7 for loop

munotes.in

Page 30


30 .Net technology
Do…while loop A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. Syntax The conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false. Flow Diagram
fig 2.8 do…while loop flow chart
munotes.in

Page 31


31
C# language basics

Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C# provides the following control statements. break
statement Terminates the loop or switch statement and transfers
execution to the statement immediately followi ng the loop or
switch. continue
statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating. Break Statement  When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.  If we are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
munotes.in

Page 32


32 .Net technology Flow Diagram
fig 2.8 break statement flow chart Example

munotes.in

Page 33


33
C# language basics
Continue Statement It forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. The while and do...while loops, continue statement causes the program control passes to the conditional tests. Flow Diagram
fig 2.9 continue statement flow chart
munotes.in

Page 34


34 .Net technology Example

Methods A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.
munotes.in

Page 35


35
C# language basics Defining Methods in C# Syntax (Parameter List) { Method Body }  Access Specifier − Determines the visibility of a variable or a method from another class.  Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.  Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.  Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.  Method body − It contains the set of instructions needed to complete the required activity. Calling Methods in C# namespace CalculatorApplication { class NumberManipulator { public intFindMax(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } munotes.in

Page 36


36 .Net technology static void Main(string[] args) { int a = 100; int b = 200; int ret; NumberManipulator n = new NumberManipulator(); ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Max value is : 200 Classes Class is a blueprint for a data type. It does not actually define any data, but it defines what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class. Defining a Class A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. class class_name { // member variables variable1; variable2; // member methods munotes.in

Page 37


37
C# language basics method1(parameter_list) { // method body } }  Access specifiers specify the access rules for the members as well as the class itself.  Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any. namespace BoxApplication { class Box { public double length; // Length of a box public double breadth; // Breadth of a box public double height; // Height of a box } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box double volume = 0.0; // Store the volume of a box here Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; volume = Box1.height * Box1.length * Box1.breadth; Console.WriteLine("Volume of Box1 : {0}", volume); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 munotes.in

Page 38


38 .Net technology 2.6 CALL BY VALUE AND CALL BY REFERENCE Two ways of passing parameters to methods are call by value and call by reference Call by Value Call by value method copies the value of an argument into the formal parameter of that function. Therefore, changes made to the parameter of the main function do not affect the argument. In this parameter passing method, values of actual parameters are copied to the function’s formal parameters, and the parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller. using System; class Test { static void Change(int a) { a = 5; Console.WriteLine(a); } static void Main(string[] args) { int n = 10; Change(n); Console.WriteLine(n); } } Call by Reference Call by reference method copies the address of an argument into the formal parameter. In this method, the address is used to access the actual argument used in the function call. It means that changes made in the parameter alter the passing argument. In this method, the memory allocation is the same as the actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameter, and the modified value will be stored at the same address. using System; class Test { static void Change(ref int a) munotes.in

Page 39


39
C# language basics { a = 5; Console.WriteLine(a); } static void Main(string[] args) { int n = 10; Change(ref n); Console.WriteLine(n); } } 2.7 C# CONSTRUCTORS A special member function of a class that is executed whenever we create new objects of that class. A constructor has exactly the same name as that of class and it does not have any return type.

munotes.in

Page 40


40 .Net technology Polymorphism(Function Overloading) Multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. We cannot overload function declarations that differ only by return type.

Namespace A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
munotes.in

Page 41


41
C# language basics Defining a Namespace namespace namespace_name { // code declarations } Example:- namespace first_space { class namespace_cl { public void func() { Console.WriteLine("Inside first_space"); } } } namespace second_space { class namespace_cl { public void func() { Console.WriteLine("Inside second_space"); } } } class TestClass { static void Main(string[] args) { first_space.namespace_cl fc = new first_space.namespace_cl(); second_space.namespace_clsc = new second_space.namespace_cl(); fc.func(); sc.func(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result − Inside first_space Inside second_space munotes.in

Page 42


42 .Net technology Assemblies An Assembly is a basic building block of .Net Framework applications. It is basically a compiled code that can be executed by the CLR. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An Assembly can be a DLL or exe depending upon the project that we choose. An assembly is a file that is automatically generated by the compiler upon a successful compilation of every .NET application. It is generated only once for an application and upon each subsequent compilation, the assembly gets updated. An Assembly contains Intermediate Language (IL) code, which is similar to Java byte code. In the .NET language, it consists of metadata. Metadata enumerates the features of every “type” inside the assembly or the binary. In addition to metadata, assemblies also have a special file called Manifest. It contains information about the current version of the assembly and other related information. Assemblies are basically the following two types: • Private Assembly • Shared Assembly Private Assembly It is an assembly that is being used by a single application only. Suppose we have a project in which we refer to a DLL so when we build that project that DLL will be copied to the bin folder of our project. That DLL becomes a private assembly within our project. Generally, the DLLs that are meant for a specific project are private assemblies. Shared Assembly Assemblies that can be used in more than one project are known to be shared assembly. Shared assemblies are generally installed in the GAC. Assemblies that are installed in the GAC are made available to all the .Net applications on that machine. Inheritance Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the baseclass, and the new class is referred to as the derived class. A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces. munotes.in

Page 43


43
C# language basics Consider a base class Shape and its derived class Rectangle − namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Derived class class Rectangle: Shape { public intgetArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); Console.WriteLine("Total area: {0}", Rect.getArea()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Total area: 35 munotes.in

Page 44


44 .Net technology Static members When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member. The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition. namespace StaticVarApplication { class StaticVar { public static intnum; public void count() { num++; } public intgetNum() { return num; } } class StaticTester { static void Main(string[] args) { StaticVar s1 = new StaticVar(); StaticVar s2 = new StaticVar(); s1.count(); s1.count(); s1.count(); s2.count(); s2.count(); s2.count(); Console.WriteLine("Variable num for s1: {0}", s1.getNum()); Console.WriteLine("Variable num for s2: {0}", s2.getNum()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Variable num for s1: 6 Variable num for s2: 6 munotes.in

Page 45


45
C# language basics 2.8 CASTING OBJECTS Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms − • Implicit type conversion –It supports conversions from derived classes to base classes. Implicit conversion : It is done automatically by compiler; no data will be lost; includes conversion of a smaller data type to a larger data types; safe type conversion. Ex:- int smallnum = 654667; long bigNum = smallnum; • Explicit type conversion − These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator. Conversion of larger data type to smaller data type; information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion. long bigNum = 654667; int smallnum = (int)bigNum; Partial Classes A partial class splits the definition of a class over two or more source files. We can create a class definition in multiple files but it will be compiled as one class. Suppose we have a "Person" class. That definition is divided into the two source files "Person1.cs" and "Person2.cs". Then these two files have a class that is a partial class. We compile the source code then create a single class.
fig. 2.10 partial class Advantages of a partial class
munotes.in

Page 46


46 .Net technology We can separate User Interface design code and business logic code so that it is easy to read and understand. 1. When working with automatically generated source, the code can be added to the class without having to recreate the source file. 2. More than one developer can simultaneously write the code for the class. 3. We can maintain our application better by compacting large classes. Suppose we have a class that has multiple interfaces so we can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class. publicinterface IRegister { //Register realted function } publicinterface ILogin { //Login related function } //UserRegister.cs file publicpartial classUser : IRegister, ILogin { //implements IRegister interface } //UserLogin.cs file publicpartial classUser { //implements ILogin interface } 2.9 SUMMARY This chapter briefs about basics of C# while developing a web application. This chapter discusses variable declaration, various operators used in C#, conditional logics and looping concepts in C#. It also focuses on implementation of OOPs concept with respect to C#. This chapter tell you about data types supported by asp.net web applications. 2.10 REFERENCES 1. Beginning ASP.NET 4.5 in C#, Matthew MacDonald, Apress(2012) 2. The Complete Reference ASP .NET, MacDonald, Tata McGraw Hill 3. Beginning ASP.NET 4 in C# and VB Imar Spanajaars, WROX munotes.in

Page 47


47
C# language basics 2.11 QUESTIONS 1. What are the data types supported by C#? 2. Describe various decision making statements in C#. 3. Explain in brief Loop Control Statements 4. How to define and call a method in C#? 5. Write a note on C# classes. 6. What do you mean by namespace? Explain it with an example. 7. What are the advantages of inheritance? Explain it with suitable example. 8. What is the use of static members? Explain it with an example. 9. How can be object casting or data casting is possible in C#? 10. What is partial class? State its advantages.  munotes.in

Page 48


48 .Net technology 3 ASP.NET Unit Structure : 3.0 Introduction 3.1 Creating Websites 3.2 Anatomy of a web form 3.3 Understanding Page Elements 3.4 The Page directive 3.5 Adding event handlers 3.6 Anatomy of an ASP.NET application 3.7 Advantages of ASP.NET Application Folders 3.8 Summary 3.9 References 3.9 Questions 3.0 INTRODUCTION ASP.NET is an open source web framework, created by Microsoft, for building modern web apps and services with .NET. ASP.NET is cross platform and runs on Windows, Linux, macOS, and Docker. ASP.NET is a web framework designed and developed by Microsoft. It is used to develop websites, web applications and web services. It provides fantastic integration of HTML, CSS and JavaScript. It was first released in January 2002. It is built on the Common Language Runtime (CLR) and allows programmers to write code using any supported .NET language. 3.1 CREATING WEBSITES 1- Start -> All Programs -> Visual Studio 2008 2- Now go to File Menu -> New -> Web Site 3- Under Visual Studio Installed Template-> Choose ASP.NET WEB SITE -> Choose File System from the location combo box -> Set the path by the browse button - > Choose the language from the Language ComboBox (Visual C# , Visual Basic , J #) Choose Visual C# 4 - Click on the OK Button 5- Tab named Design in the bottom of this page. munotes.in

Page 49


49
ASP.Net Click on this tab and you will see a blank web page where you can drag any control from the toolbox (which is in the left side of this window). 6- If you are not able to see the Toolbox window just go to View -> Choose Toolbox. 7 - Drag a button on the blank page and now click on the Source tab. <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %> Untitled Page

8- Now you can drag any control from the toolbox to the blank web page and you can set the properties of these controls from the property window 9- If You are not able to see the property window just go to View - > Select Properties Window. A new window will open on the right side of this page… 10-Select the control for which you want to set the properties Go to properties window and set the properties like Button Name 11- If you want to change the Button name which you have added in your web site then select the button and right click on the button select properties and the select the — Text Property from the property window and give any name which you want it will change the button name. 3.2 ANATOMY OF A WEB FORM ASP.NET applications are generally divided into multiple Web pages. Every Web page in an ASP.NET application shares a common set of resources and configuration settings. munotes.in

Page 50


50 .Net technology Each ASP.NET application is executed inside a separate application domain. These application domains ensure that even if a Web application causes a fatal error, it does not affect other applications that are currently running on the same computer. Each Web application is a separate entity that has its own set of data. It can be described as a combination of files, pages, handlers, modules, and executable code that can be invoked from a virtual directory on a Web server. The following listing shows an example of a relatively simple Web Forms page. HelloSimple.aspx <%-- Example of the @ Page directive --%> <%@ Page Language="c#" ClassName="Hello" %> 3.3 UNDERSTANDING PAGE ELEMENTS HelloSimple.aspx shows examples of many of the elements that you can use in an ASP.NET Web Form, including server-side comments, the @ Page directive, static HTML, a server-side munotes.in

Page 69


69
HTML Server Controls 4.5 WEB.CONFIG Behavior of an ASP.NET application is affected by different settings in the configuration files: • machine.config • web.config machine.config file contains default and machine-specific value for all supported settings. Machine settings are controlled by the system administrator and applications are generally not given access to this file. Every web application includes a web.config file that configures fundamental settings—everything from the way error messages are shown to the security settings that lock out unwanted visitors. ASP.NET stores settings in a human-readable XML format using configuration files such as machines.config and web.config. An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file. If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner. Any web.config file can locally extend, restrict or override any settings defined on the upper level. Visual Studio generates a default web.config file for each project. An application can run without a web.config file, however, we cannot debug an application without a web.config file. The XML based web.config file is used to specify the application wide settings for the entire application. The web.config file is present in the root of the application's directory, although we can also have multiple web.config files, one for each subdirectory. In a Web.config file, sections can appear in the settings area that have not been declared in the declaration area if they are declared in a .config file at a higher level in the configuration hierarchy. 4.6 SUMMARY This chapter briefs about use of html server controls while developing a web application. This chapter discusses various aspects of html server controls such as html control classes, events, html container control class, html input control class. It also focuses on role of page class, global.asax file and web.config file helps while developing web applications. 4.7 REFERENCES 1. Beginning ASP.NET 4.5 in C#, Matthew MacDonald, Apress(2012) 2. The Complete Reference ASP .NET, MacDonald, Tata McGraw Hill 3. Beginning ASP.NET 4 in C# and VB Imar Spanajaars, WROX munotes.in

Page 70


70 .Net technology 4.8 QUESTIONS 1. Write a note on view state. 2. Write a note on HtmlControl class. 3. What is a page class? Explain the use of its properties. 4. What is the use of global.asax file? 5. Write a note on web.config file?  munotes.in

Page 71

71 5 WEB CONTROLS Unit Structure : 5.0 Objectives 5.1 Introduction 5.2 Web Control Classes 5.3 WebControl Base Class 5.4 List Controls 5.5 Table Controls 5.6 Web Control Events and AutoPostBack 5.7 Page Life Cycle 5.8 Summary 5.9 Reference 5.10 Questions In this chapter, you’ll explore the basic web controls and their class hierarchy. You’ll also delve deeper into ASP.NET’s event handling and learn the details of the web page life cycle. 5.0 OBJECTIVES In this chapter,  you’ll explore the basic web controls and their class hierarchy.  you’ll also delve deeper into ASP.NET’s event handling and learn the details of the web page life cycle. 5.1 INTRODUCTION Web Controls are small building blocks of the GUI(Graphical User Interface), which include labels, text box, buttons, etc which provide rich functionality in your pages. You need web controls because HTML control corresponds directly to a single HTML element. Web controls, on the other hand, have no such restriction—they can switch from one element to another depending on how you’re using them, or they can render themselves by using a complex combination of multiple elements. Advantages of using Web Controls:  They provide a rich user interface  They provide a consistent object model  They tailor their output automatically  They provide high-level features munotes.in

Page 72


72 .Net technology 5.2 WEB CONTROL CLASSES  Web control classes are defined in the System.Web.UI.WebControls namespace. They follow a slightly more tangled object hierarchy than HTML server controls.  Figure shows most, but not all, of the web controls that ASP.NET provides.
Figure 5.1: The web control hierarchy (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 5.3 WEBCONTROL BASE CLASS  Web controls provides the properties, methods, and events that are common to all Web server controls.  Most web controls begin by inheriting from the WebControl base class. This class defines the essential functionality for tasks such as data binding and includes some basic properties that you can use with almost any web control, as described in Table
munotes.in

Page 73


73
Web Controls Properties of webcontrol classes Property Description AccessKey This property is used to set focus on web control. BackColor Sets the colors used for the background ForeColor Sets the colors used for the foreground. In most
controls, the foreground color sets the text color. BorderColor Sets the colors used for the Border BorderWidth Specifies the size of the control border. BorderStyle One of the values from the BorderStyle
enumeration, i ncluding Dashed, Dotted, Double,
Groove, Ridge, Inset, Outset, Solid, and None. Enabled When set to false, the control will be visible, but it
will not be able to receive user
input or focus. EnableViewState This property state whether the view state of the
control is maintained or not. Set this to false to
disable the automatic state management for this
control. Font Specifies the font used to render any text in the
control Height and Width Specifies the width and height of the control. ID Specifies the name that you use to interact with the
control in your code Page Provides a reference to the web page that contains
this control as a System.Web.UI.Page object. Parent This property is used to set Parent for web control. TabIndex A number that allows you to control the tab order.
The control with a TabIndex of 0 has the focus
when the page first loads. ToolTip Gets or sets the text displayed when the mouse
pointer hovers over the Web server control. Visible When set to false, the control will be hidden and
will not be rendered to the final HTML page that is
sent to the client. Table 5.1: Properties of webcontrol classes (Ref: Beginning ASP.NET in C# by Matthew MacDonald) munotes.in

Page 74


74 .Net technology Methods of web control classes: Method Description AddAttributesToRender( HtmlTextWriter) To add HTML attributes
and styles in our web page
that need to be rendered to
the specified
HtmlTextWriterTag ClearChildState() This method is used to
deletes the view -state and
control -state details of
child controls of web
control. ClearChildViewState() This method is used to
delete the view -state
information for all the child
controls of web controls CreateChildControls() This method is used in
creating child controls. DataBind() This method is used to
binds a data source to the
web control and all its
child controls. Dispose() Enables a server control to
perform final clean up
before it is released from
memory. Focus() Sets input focus to a
control. GetType() Gets the Type of the
current instance. OnLoad(EventArgs) Raises the Load event. OnPreRender(EventArgs) Raises the PreRender
event. OnUnload(EventArgs) Raises the Unload event. ToString() Returns a string that
represents the current
object. Table 5.2: Methods of web control classes (Ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.webcontrol?view=netframework-4.8.1) munotes.in

Page 75


75
Web Controls Events of Web Controls: Name Description DataBinding Occurs when the server control binds to a data
source. Disposed This event occurs when a web control is
released from memory Init Occurs when the server control is initialized Load Occurs when the server control is loaded into
the Page object PreRender Occurs after the control object is loaded but
prior to rendering. Unload Event Occurs when the server control is
unloaded from memory. Table 5.3: Events of Web Controls (Ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.webcontrol?view=netframework-4.8.1) 5.4 LIST CONTROLS  The list controls include the  ListBox,  DropDownList,  CheckBoxList,  RadioButtonList, and  BulletedList.  They all work in essentially the same way but are rendered differently in the browser.  The ListBox is a rectangular list that displays several entries, while the DropDownList shows only the selected item.  The CheckBoxList and RadioButtonList are similar to the ListBox, but every item is rendered as a check box or option button, respectively.  BulletedList is the only list control that isn’t selectable. Instead, it renders itself as a sequence of numbered or bulleted items.  All the selectable list controls provide a SelectedIndex property that indicates the selected row as a zero-based index.  For example, if the first item in the list is selected, the SelectedIndex will be 0. munotes.in

Page 76


76 .Net technology  Selectable list controls also provide an additional SelectedItem property, which allows your code to retrieve the ListItem object that represents the selected item.  The ListItem object provides three important properties:  Text (the displayed content),  Value (the hidden value from the HTML markup), and  Selected (true or false depending on whether the item is selected). 5.4.1 ListBox  This represents a list box control that allows single or multiple item selection.  ListBox control has SelectionMode property that enables you to select multiple items from ListBox control. By default SelectionMode property is set as single.  If you want to select multiple items from the ListBox, then set SelectionMode property value as Multiple and press Ctrl or Shift key when clicking more than one list item. Example : Item 1 Item 2 Item 3 Common Properties of ListBox Property Description Items Gets the collection of items in the list control. SelectionMode This property will set t he selection mode as single
selection or multiple selection Rows This will determine the number of items shows in the
list box. SelectedIndex Gets or sets the lowest ordinal index of the selected
items in the list. SelectedValue Gets the value of the selected item in the list control,
or selects the item in the list control that contains the
specified value. Table 5.4: Properties of ListBox (Ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listbox?view=netframework-4.8.1) munotes.in

Page 77


77
Web Controls 5.4.2 DropDownList  This control permit user to select item from predefined list.  It does not support for selecting multiple items at same time. Example : Please Select item1 item2 item3 item4 DropDownList carry same property like ListBox. 5.4.3 CheckBoxList  CheckBoxList is generally used, when you want to select one or more options from given several choices.  We can select more than one item from CheckBoxList control.  The CheckBoxList control is easier for use, when you have set of options of checkboxes. Example : Item 1 Item 2 Item 3 Common properties: Property Description Repeat Layout Gets or sets a value that specifies whether the list
will be rendered by using a table element, or list
element. RepeatColumns Gets or sets t he number of columns to display in
the CheckBoxList control. RepeatDirection Gets or sets a value that indicates whether the
control displays vertically or horizontally. Table 5.5: Common properties of CheckBoxList (Ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.checkboxlist?view=netframework-4.8.1) munotes.in

Page 78


78 .Net technology 5.4.4 RadioButtonList  RadioButtonList Control is same as DropDownList but it displays a list of radio buttons that can be arranged either horizontally or vertically.  You can select only one item from the given RadioButtonList of options. Example : Item 1 Item 2 Item 3 Common properties: Property Description Repeat Layout Determines whether the radio buttons display in
an HTML table. RepeatColumns It displays th e number of columns of radio
buttons. RepeatDirection The direction that the radio buttons repeat. By
default RepeatDirection value is vertical.
Possible values are Horizontal and Vertical. Table 5.6: Common properties of RadioButtonList (Ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.radiobuttonlist?view=netframework-4.8.1) 5.4.5 BulletedList  BulletedList control is very rich in displaying the items in different styles. It dispalys the list either in unordered or ordered list.  The default value of BulletStyle property is NotSet and rendered as in list of bulleted items.  Possible values are as follows: Circle, CustomImage, Disc, LowerAlpha, LowerRoman, NotSet, Numbered, Square, UpperAlpha, UpperRoman  BulletedList control also supports the DisplayMode property that is used to modify the appearance of list items.  Possible values are as follows: HyperLink, LinkButton, Text munotes.in

Page 79


79
Web Controls Example: Common property: Property Description BulletStyle To set the style and looks of the bullet list this
property is used. FirstBulletNumber In an ordered list, this sets the first value. Ex.
If you set FirstBulletNumber to 3, the list
might read 3,4,5 for Numbered. DisplayMode Determines whether the text of each item is
rendered as text or a hyperlink. Table 5.7: Common Property of BulletedList (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 5.5 TABLE CONTROLS  Table class is used to build an HTML table.  Table class is included in System.Web.UI.Controls namespace.  Essentially, the Table control is built out of a hierarchy of objects. Each Table object contains one or more  TableRow objects. In turn, each TableRow object contains one or more TableCell objects.
Figure 5.2: Table object (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 80


80 .Net technology  Each TableCell object contains other ASP.NET controls or HTML content that displays information.  We can create Table control in run-time as well as at design-time using the Visual studio. Table control containment Properties of Table class Property Description Runat This property state that the web control is a
server control. For this purpose, we have to
set value of runat to “server” Rows This property state group of rows in the
table Caption This property is used to set title to table CaptionAlign This pro perty is used to set alignment of the
caption text. CellPadding This property is used to state the space
between the cell walls and controls in table. CellSpacing This property is used to determines distance
between cell of tables. GridLines This property is used to set gridline format
in the table. HorizontalAlign Gets or sets the horiz ontal alignment of
the Table control on the page. Table 5.8: Table class Properties (Ref: https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.table?view=netframework-4.8.1) Example : Creating table at Design time Row 0, Col 0 Row 0, Col 1 munotes.in

Page 81


81
Web Controls Row 1, Col 0 Row 1, Col 1 5.6 WEB CONTROL EVENTS AND AUTOPOSTBACK  The previous chapter explained that one of the main limitations of HTML server controls is their limited set of useful events—they have exactly two.  HTML controls that trigger a postback, such as buttons, raise a ServerClick event. Input controls provide a ServerChange event that doesn’t actually fire until the page is posted back.  Following Figure illustrates the order of events in page processing.
Figure 5.3: The page-processing sequence (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 82


82 .Net technology The page-processing sequence  When event occurs on client side some events such as Click event of a button take place immediately, because when clicked, the button post back the page.  However, other actions do cause events but don’t trigger a postback.  For example, when user chooses a new item in a list or changes the text in text box.  In these cases, without postback your code has no way to run. ASP.NET handles this by giving you two options: 1. Wait until the next postback to react to the event. Like to react to SelectedIndexChanged event in a list, when user selects an item in a list, nothing happens immediately. But if user clicks a button to post back the page, two events fire: ButtonClick followed by ListBox.SelectedIndexChanged.. 2. To use the automatic postback feature to force a control to post back the page immediately when it detects a specific user action. In this, when the user clicks a new item in the list, the page is posted back, your code executes, and a new version of the page is returned. Event Web Controls That Provide It Always
Posts Back Click Button, ImageButton True TextChanged TextBox (fires only after the user
changes the focus to another
control) False CheckedChanged CheckBox, RadioButton False SelectedIndexChanged DropDownList, ListBox,
CheckBoxList, RadioButtonList False Table 5.9: Web Control Events (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  If you want to capture a change event (such as TextChanged, CheckedChanged, or SelectedIndexChanged) immediately, you need to set the control’s AutoPostBack property to true.  This way, the page will be submitted automatically when the user interacts with the control for example, picks a selection in the list, clicks a radio button or a check box, or changes the text in a text box and then moves to a new control).  When the page is posted back, ASP.NET will examine the page, load all the current information, and then allow your code to perform some munotes.in

Page 83


83
Web Controls extra processing before returning the page back to the user shown in following figure.  Depending on the result you want, you could have a page that has some controls that post back automatically and others that don’t.
Figure 5.4: The postback processing sequence (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 5.7 PAGE LIFE CYCLE To understand how web control events work, you need to have a solid understanding of the page life cycle. Consider what happens when a user changes a control that has the AutoPostBack property set to true: 1. On the client side, the JavaScript __doPostBack function is invoked, and the page is resubmitted to the server.
munotes.in

Page 84


84 .Net technology 2. ASP.NET re-creates the Page object by using the .aspx file. 3. ASP.NET retrieves state information from the hidden view state field and updates the controls accordingly. 4. The Page.Load event is fired. 5. The appropriate change event is fired for the control. (If more than one control has been changed, the order of change events is undetermined.) 6. The Page.PreRender event fires, and the page is rendered (transformed from a set of objects to an HTML page). 7. Finally, the Page.Unload event is fired. 8. The new page is sent to the client. 5.8 SUMMARY This chapter introduced you to one of ASP.NET’s richest features: web controls, and their object interface. 5.9 REFERENCE  Beginning ASP.NET in C# by Matthew MacDonald  https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols?view=netframework-4.8.1 5.10 QUESTIONS 1. Write a shot note on WebControls. 2. State the page life cycle with diagram. 3. Write and explain basic properties for table class. 4. Write and explain list control. 5. Write basic properties for webcontrol classes.  munotes.in

Page 85

85 6 STATE MANAGEMENT Unit Structure : 6.0 Objectives 6.1 Introduction 6.2 ViewState 6.3 Cross-Page Posting 6.4 Query String 6.5 Cookies 6.6 Session State 6.7 Configuring Session State 6.8 Application State 6.9 Summary 6.10 Reference 6.11 Questions In this chapter, you’ll understand the use of State management in Web programming. Also, you will get to know about ViewState and Application State. 6.0 OBJECTIVES  State management is a preserve state control and object in an application because web applications are stateless, which means a new web page object is re-created each time to serve request of client.  This issue can be resoled by using State Management. 6.1 INTRODUCTION  The most significant difference between programming for the Web and programming for the desktop is state management—how you store information over the lifetime of your application.  This information can be as simple as a user’s name or as complex as a stuffed-full shopping cart for an e-commerce store.  Understanding these state limitations is the key to creating efficient web applications. In this chapter, you’ll see how you can use ASP.NET’s state management features to store information carefully and consistently. munotes.in

Page 86


86 .Net technology 6.2 VIEWSTATE  ViewState is a important client side state management technique. ViewState is used to store user data on page at the time of post back of web page.  ViewState does not hold the controls, it holds the values of controls.  It does not restore the value to control after page post back.  ViewState can hold the value on single web page, if we go to other page using response.redirect then ViewState will be null.  When we require value of page variable to be maintained during page postback, we can use View state to store those value.  “EnableViewState” property is used for both Page Level and Server contact level to manage the view state.  Code for View state is like this,  This single hidden field contains all the view state values for all the page controls. Example : <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> ViewState



munotes.in

Page 87


87
State Management Name retrieved from ViewState: And the CodeBehind: using System; using System.Data; using System.Web; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(ViewState["NameOfUser"] != null) NameLabel.Text = ViewState["NameOfUser"].ToString(); else NameLabel.Text = "Not set yet..."; } protected void SubmitForm_Click(object sender, EventArgs e) { ViewState["NameOfUser"] = NameField.Text; NameLabel.Text = NameField.Text; } }  Try running the project, enter your name in the textbox and press the first button.  The name will be saved in the ViewState and set to the Label as well.  No magic here at all. Now press the second button.  This one does nothing at all actually, it just posts back to the server.  As you will notice, the NameLabel still contains the name, but so does the textbox.  The first thing is because of us, while the textbox is maintained by ASP.NET it self. Try deleting the value and pressing the second button again.  You will see that the textbox is now cleared, but our name label keeps the name, because the value we saved to the ViewState is still there! munotes.in

Page 88


88 .Net technology Limitation of view state 1. Viewstate can be used only with single page. 2. It is storing the information of an hidden field, so it can be seen in source code in browser, hence it is not secure way. 6.3 CROSS-PAGE POSTING  It’s a technique that extends the postback mechanism, that one page can send the user to another page, complete with all the information for that page.  “PostBackUrl” is the property name that provides the cross-page postback, which is defined by the IButtonControl interface and turns up in button controls such as ImageButton, LinkButton, and Button.  To use cross-posting, we have to set PostBackUrl to the name of another web form.  When the user clicks the button, the page will be posted to that new URL with the values from all the input controls on the current page. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CrossPage1.aspx.cs" Inherits="CrossPage1" %> CrossPage1

First Name:
Last Name:


munotes.in

Page 89


89
State Management
Figure 6.1: The starting point of a cross-page postback (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 6.4 QUERY STRING • Another common approach is to pass information by using a query string in the URL. • This approach is commonly found in search engines. • For example, if you perform a search on the Google website, you’ll be redirected to a new URL that incorporates your search parameters. • Here’s an example: http://www.google.ca/search?q=organic+gardening • The query string is the portion of the URL after the question mark. • In this case, it defines a single variable named q, which contains the string organic+gardening. • There is a limitation of length of query string. So query string cannot be used to send very large data. • Query string are visible to the user, so it should not be used to send sensitive information such as username, password without encryption. • Request object of QueryString property is used to retrieve the query string. Example: • When the user chooses an item by clicking the appropriate item in the list, the user is forwarded to a new page. • This page displays the received ID number. • This provides a quick and simple query string test with two pages.
munotes.in

Page 90


90 .Net technology
Figure 6.2: A query string sender (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Here’s the code for the first page: public partial class QueryStringSender : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { if (!this.IsPostBack) { // Add sample values. lstItems.Items.Add("Econo Sofa"); lstItems.Items.Add("Supreme Leather Drapery"); lstItems.Items.Add("Threadbare Carpet"); lstItems.Items.Add("Antique Lamp"); lstItems.Items.Add("Retro-Finish Jacuzzi"); } } protected void cmdGo_Click(Object sender, EventArgs e) { if (lstItems.SelectedIndex == -1) { lblError.Text = "You must select an item."; } else
munotes.in

Page 91


91
State Management { // Forward the user to the information page, // with the query string data. string url = "QueryStringRecipient.aspx?"; url += "Item=" + lstItems.SelectedItem.Text + "&"; url += "Mode=" + chkDetails.Checked.ToString(); Response.Redirect(url); } } } Here’s the code for the recipient page
Figure 6.3: A query string recipient (Ref: Beginning ASP.NET in C# by Matthew MacDonald) public partial class QueryStringRecipient : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { lblInfo.Text = "Item: " + Request.QueryString["Item"]; lblInfo.Text+="Show Full Record: "; lblInfo.Text += Request.QueryString["Mode"]; } } 6.5 COOKIES • Cookies provide another way to store information for later use. • Cookies are small files that are created in the web browser’s memory or on the client’s hard drive. • Cookies works transparently.
munotes.in

Page 92


92 .Net technology • To import cookies we should import the System.Net namespace so we can easily work with the appropriate types: using System.Net; • Both the Request and Response objects provide a Cookies collection. // Create the cookie object. HttpCookie cookie = new HttpCookie("Preferences"); // Set a value in it. cookie["LanguagePref"] = "English"; // Add another value. cookie["Country"] = "US"; // Add it to the current web response. Response.Cookies.Add(cookie); • A cookie added in this way will persist until the user closes the browser and will be sent with every request. To create a longer-lived cookie, you can set an expiration date: // This cookie lives for one year. cookie.Expires = DateTime.Now.AddYears(1); • You retrieve cookies by cookie name, using the Request.Cookies collection. Here’s how you retrieve the preceding cookie, which is named Preferences: HttpCookie cookie = Request.Cookies["Preferences"]; Example: The next example shows a typical use of cookies to store a customer name. To try this example, begin by running the page, entering a name, and clicking the Create Cookie button. Then close the browser, and request the page again. The second time, the page will find the cookie, read the name, and display a welcome message.
Figure 6.4: Displaying information from a custom cookie (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 93


93
State Management Here’s the code for this page: public partial class CookieExample : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["Preferences"]; if (cookie == null) { lblWelcome.Text = "Unknown Customer"; } else { lblWelcome.Text = "Cookie Found."; lblWelcome.Text += "Welcome, " + cookie["Name"]; } } protected void cmdStore_Click(Object sender, EventArgs e) { // Check for a cookie, and create a new one only if // one doesn’t already exist. HttpCookie cookie = Request.Cookies["Preferences"]; if (cookie == null) { cookie = new HttpCookie("Preferences"); } cookie["Name"] = txtName.Text; cookie.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(cookie); lblWelcome.Text = "Cookie Created.
"; lblWelcome.Text += "New Customer: " + cookie["Name"]; } } 6.6 SESSION STATE • Session-state management is one of ASP.NET’s premiere features. It allows you to store any type of data in memory on the server. • The information is protected, because it is never transmitted to the client, and it’s uniquely bound to a specific session. • Every client that accesses the application has a different session and a distinct collection of information. munotes.in

Page 94


94 .Net technology • Session state is ideal for storing information such as the items in the current user’s shopping basket when the user browses from one page to another. 6.6.1 Session Tracking • ASP.NET tracks each session by using a unique 120-bit identifier. • ASP.NET uses a proprietary algorithm to generate this value, thereby guaranteeing that the number is unique. • This ID is the only piece of session-related information that is transmitted between the web server and the client. • When the client presents the session ID, ASP.NET looks up the corresponding session, retrieves the objects you stored previously, and places them into a special collection so they can be accessed in your code. This process takes place automatically. • We can do this in two ways: 1. Using cookies 2. Using modified URLs 6.6.2 Using Session State • You can interact with session state by using the System.Web.SessionState.HttpSessionState class, which is provided in an ASP.NET web page as the built-in Session object. • For example, you might store a DataSet in session memory like this: Session["InfoDataSet"] = dsInfo; • You can then retrieve it with an appropriate conversion operation: dsInfo = (DataSet)Session["InfoDataSet"]; 6.6.3 HttpSessionState Members Member Description Count Provides the number of items in the current
session collection IsCookieless Identifies whether the session is tracked with a
cookie or modified URLs. IsNewSession Identifies whether the session was created only
for the current request. If no information is in
session state, ASP.NET won’t bother t o track
the session or create a session cookie. Instead,
the session will be re -created with every
request. munotes.in

Page 95


95
State Management Keys Gets a collection of all the session keys that are
currently being used to store items in the
session -state collection. Mode Provides an enumerated value that explains
how ASP.NET stores session -state
information. This storage mode is determined
based on the web.config settings discussed in
the “Configuring Session State” section later in
this chapter SessionID Provides a strin g with the unique session
identifier for the current client Timeout Determines the number of minutes that will
elapse before the current session is abandoned,
provided that no more requests are received
from the client. This value can be changed
programma tically, letting you make the session
collection longer when needed. Abandon() Cancels the current session immediately and
releases all the memory it occupied. This is a
useful technique in a logoff page to ensure that
server memory is reclaimed as quickl y as
possible. Clear() Removes all the session items but doesn’t
change the current session identifier. Table 6.1: HttpSessionState Members (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 6.6.4 A Session-State Example public class Furniture { public string Name; public string Description; public decimal Cost; public Furniture(string name, string description, decimal cost) { Name = name; Description = description; Cost = cost; } } munotes.in

Page 96


96 .Net technology • Three Furniture objects are created the first time the page is loaded, and they’re stored in session state. • The user can then choose from a list of furniture-piece names. • When a selection is made, the corresponding object will be retrieved, and its information will be displayed.
Figure 6.5: A session-state example with data objects (Ref: Beginning ASP.NET in C# by Matthew MacDonald) public partial class SessionStateExample : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { if (!this.IsPostBack) { // Create Furniture objects. Furniture piece1 = new Furniture("Econo Sofa", "Acme Inc.", 74.99M); Furniture piece2 = new Furniture("Pioneer Table", "Heritage Unit", 866.75M); Furniture piece3 = new Furniture("Retro Cabinet", "Sixties Ltd.", 300.11M); // Add objects to session state.
munotes.in

Page 97


97
State Management Session["Furniture1"] = piece1; Session["Furniture2"] = piece2; Session["Furniture3"] = piece3; // Add rows to list control. lstItems.Items.Add(piece1.Name); lstItems.Items.Add(piece2.Name); lstItems.Items.Add(piece3.Name); } // Display some basic information about the session. // This is useful for testing configuration settings. lblSession.Text = "Session ID: " + Session.SessionID; lblSession.Text+="
Number of Objects: "; lblSession.Text += Session.Count.ToString(); lblSession.Text+="
Mode: " + Session.Mode.ToString(); lblSession.Text+="
Is Cookieless: "; lblSession.Text += Session.IsCookieless.ToString(); lblSession.Text+="
Is New: "; lblSession.Text += Session.IsNewSession.ToString(); lblSession.Text+="
Timeout (minutes): "; lblSession.Text += Session.Timeout.ToString(); } protected void cmdMoreInfo_Click(Object sender, EventArgs e) { if (lstItems.SelectedIndex == -1) { lblRecord.Text = "No item selected."; } else { // Construct the right key name based on the index. string key = "Furniture" + (lstItems.SelectedIndex + 1).ToString(); // Retrieve the Furniture object from session state. Furniture piece = (Furniture)Session[key]; // Display the information for this object. munotes.in

Page 98


98 .Net technology lblRecord.Text = "Name: " + piece.Name; lblRecord.Text+="
Manufacturer: "; lblRecord.Text += piece.Description; lblRecord.Text+="Cost: " + piece.Cost.ToString("c"); } } } 6.7 CONFIGURING SESSION STATE • You configure session state through the web.config file for your current application. • The configuration file allows you to set advanced options such as the timeout and the session-state mode. • The following listing shows the most important options that you can set for the element. ... ... munotes.in

Page 99


99
State Management 6.8 APPLICATION STATE  Application state allows you to store global objects that can be accessed by any client.  Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.  Application state is similar to session state.  It supports the same type of objects, retains information on the server, and uses the same dictionary-based syntax. Example : protected void Page_Load(Object sender, EventArgs e) { // Retrieve the current counter value. int count = 0; if (Application["HitCounterForOrderPage"] != null) { count = (int)Application["HitCounterForOrderPage"]; } // Increment the counter. count++; // Store the current counter value. Application["HitCounterForOrderPage"] = count; lblCounter.Text = count.ToString(); }  Once again, application-state items are stored as objects, so you need to cast them when you retrieve them from the collection.  Items in application state never time out.  They last until the application or server is restarted or the application domain refreshes itself 6.9 SUMMARY  State management is the art of retaining information between requests.  Usually, this information is user-specific (such as a list of items in a shopping cart, a username, or an access level), but sometimes it’s global to the whole application (such as usage statistics that track site activity). munotes.in

Page 100


100 .Net technology  Because ASP.NET uses a disconnected architecture, you need to explicitly store and retrieve state information with each request.  The approach you choose to store this data affects the performance, scalability, and security of your application 6.10 REFERANCE • Beginning ASP.NET in C# by Matthew MacDonald 6.11 QUESTIONS 1. Write and explain ViewState. 2. What is Cross-page posting. 3. What is Query string. 4. What is Cookies explain with example. 5. Explain Application state.  munotes.in

Page 101

101 7 VALIDATION Unit Structure : 7.0 Objectives 7.1 Introduction 7.2 Validation Controls 7.3 Server-Side Validation 7.4 Client-Side Validation 7.5 HTML5 Validation 7.6 Manual Validation 7.7 Validation with Regular Expressions 7.8 Summary 7.9 Reference 7.10 Questions 7.0 OBJECTIVES This chapter presents some of the most useful controls that are included in ASP.NET: the validation controls. These controls take a potentially time-consuming and complicated task—verifying user input and reporting errors—and automate it. Each validation control, or validator, has its own built-in logic. Some check for missing data, others verify that numbers fall in a predefined range, and so on. In many cases, the validation controls allow you to verify user input without writing a line of code. 7.1 INTRODUCTION As any seasoned developer knows, the people using your website will occasionally make mistakes. What’s particularly daunting is the range of possible mistakes that users can make. Here are some common examples: •A user might ignore an important field and leave it blank. • If you disallow blank values, a user might type in semi-random nonsense to circumvent your checks. •A user might make an honest mistake, such as entering a typing error, entering a nonnumeric character in a number field, or submitting the wrong type of information munotes.in

Page 102


102 .Net technology •A malicious user might try to exploit a weakness in your code by entering carefully structured wrong values. For example, an attacker might attempt to cause a specific error that will reveal sensitive information. ASP.NET aims to save you this trouble and provide you with a reusable framework of validation controls that manages validation details by checking fields and reporting on errors automatically. These controls can even use client-side JavaScript to provide a more dynamic and responsive interface while still providing ordinary validation for older browsers 7.2 VALIDATION CONTROLS ASP.NET provides five validator controls, which are described in Table. Four are targeted at specific types of validation, while the fifth allows you to apply custom validation routines Control Class Description RequiredFieldValidator Validation succeeds as long as the input
control doesn’t contain an empty string. RangeValidator Validation succeeds if the input control
contains a value within a specific
numeric, alphabetic, or date range. CompareValidator Validation succeeds if the input control
contains a value that matches the value in
another input control, o r a fixed value
that you specify. RegularExpressionValidator Validation succeeds if the value in an
input control matches a specified regular
expression CustomValidator Validation is performed by a user -
defined function. Table 7.1: Validator Controls (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 7.3 SERVER-SIDE VALIDATION If we have a client-side validation, after execution of client-side validation this validation is get executed. munotes.in

Page 103


103
Validation Server-side validation compulsory because a user or hacker can send the data through different channels. Server-side validation is done after the user submits the data to server or data post back to server. Server-side validation uses several languages like ASP.Net, PHP etc. After finishing validation process on the Server Side, the feedback is sent to the client by server using a new dynamically created web page. Its better to validate user input on Server Side because we need to protect the data from unauthorised users or hackers. It is more secure than client-side validation. 7.4 CLIENT-SIDE VALIDATION In modern browsers, ASP.NET automatically adds JavaScript code for client-side validation. In this case, when the user clicks a CausesValidation button, the same error messages will appear without the page needing to be submitted and returned from the server. This increases the responsiveness of your web page. However, even if the page validates successfully on the client side, ASP.NET still revalidates it when it’s received at the server. This is because it’s easy for an experienced user to manipulate client-side validation. For example, a malicious user might delete the block of JavaScript validation code and continue working with the page. By performing the validation at both ends, ASP.NET makes sure your application can be as responsive as possible while also remaining secure. 7.5 HTML5 VALIDATION HTML language, adds new client-side validation features that can help catch errors. The problem is that HTML5 validation is inconsistent—it works differently in different browsers, and many browsers offer only partial support. 7.5.1 The Validation Controls The validation controls are found in the System.Web.UI.WebControls namespace and inherit from the BaseValidator class. munotes.in

Page 104


104 .Net technology This class defines the basic functionality for a validation control. Properties of the BaseValidator Class Property Description ControlToValidate Identifies the control that this validator will
check. Each validator can verify the value in
one input control. ErrorMessage and
ForeColor If validation fails, the validator control can
display a text message Display Allows you to configure whether this error
message will be inserted into the page
dynamically when it’s needed or whether an
appropriate space will be reserved for the
message. IsValid After validation is performed, this returns
true or false depending on whether it
succeeded or failed Enabled When set to false, automatic validation will
not be performed for this control when the
page is submitted. EnableClientScript If set to true, ASP.NET will add JavaScript
and DHTML code to allow client -side
validati on on browsers that support it. Table 7.2: Properties of the BaseValidator Class (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Validator-Specific Properties Validator Added Members RequiredFieldValidator None required RangeValidator MaximumValue, MinimumValue, Type CompareValidator ControlToCompare, Operator, Type,
ValueToCompare RegularExpressionValidator ValidationExpression CustomValidator ClientValidationFunction,
ValidateEmptyText, ServerValidate
event Table 7.3: Validator-Specific Properties (Ref: Beginning ASP.NET in C# by Matthew MacDonald) munotes.in

Page 105


105
Validation Validation Example This test uses a single Button web control, two TextBox controls, and a RangeValidator control that validates the first text box. If validation fails, the RangeValidator control displays an error message, so you should place this control immediately next to the TextBox it’s validating. The second text box does not use any validation.

Not validated:



Finally, here is the code that responds to the button click: protected void cmdOK_Click(Object sender, EventArgs e) { lblMessage.Text = "cmdOK_Click event handler executed."; }
Figure 7.1: Failed validation (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 106


106 .Net technology 7.6 MANUAL VALIDATION You can create manual validation in one of three ways: 1. Use your own code to verify values. In this case, you won’t use any of the ASP.NET validation controls. 2. Disable the EnableClientScript property for each validation control. This allows an invalid page to be submitted, after which you can decide what to do with it depending on the problems that may exist. 3. Add a button with CausesValidation set to false. When this button is clicked, manually validate the page by calling the Page.Validate() method. Then examine the IsValid property and decide what to do. The next example uses the second approach. After the page is submitted, it examines all the validation controls on the page by looping through the Page.Validators collection. This technique adds a feature that wouldn’t be available with automatic validation, which uses the ErrorMessage property. protected void cmdOK_Click(Object sender, EventArgs e) { string errorMessage = "Mistakes found:"; // Search through the validation controls. foreach (BaseValidator ctrl in this.Validators) { if (!ctrl.IsValid) { errorMessage += ctrl.ErrorMessage +"
"; // Find the corresponding input control, and change the // generic Control variable into a TextBox variable. // This allows access to the Text property. TextBox ctrlInput = (TextBox)this.FindControl(ctrl.ControlToValidate); errorMessage += " * Problem is with this input: "; errorMessage += ctrlInput.Text + "
"; } } lblMessage.Text = errorMessage; } munotes.in

Page 107


107
Validation 7.7 VALIDATION WITH REGULAR EXPRESSIONS One of ASP.NET’s most powerful validation controls is the RegularExpressionValidator, which validates text by determining whether it matches a specific pattern. For example, e-mail addresses, phone numbers, and file names are all examples of text that has specific constraints. A phone number must be a set number of digits, an e-mail address must include exactly one @ character (with text on either side), and a file name can’t include certain special characters such as \ and ?. One way to define patterns like these is with regular expressions. Character Description * Zero or more occurrences of the previous character or
subexpression. For example, 7*8 matches 7778 or just 8. + One or more occurrences of the previous character or
subexpression. For example, 7+8 matches 7778 but not 8. ( ) Groups a subexpression that will be treated as a single
element. For example, (78)+ matches 78 and 787878. {m,n} The previous character (or subexpression) can occur from
m to n times. For example, A{1,3} matches A, AA, or
AAA. | Either of two matches. For example, 8|6 matches 8 or 6 [ ] Matches one character in a range of valid characters. For
example, [A -C] matches A, B, or C. [^] Matches one character in a range of valid characters. For
example, [A -C] matches A, B, or C. . Any character except a newline. For example, .here
matches where and there. \s Any whitespace character (such as a tab or space). \S Any nonwhitespace character \d Any digit character \D Any character that isn’t a digit. \w Any “word” character (letter, number, or underscore). \W Any character that isn’t a “word” character (letter,
number, or underscore). Table 7.4: Common (and useful) regular expressions. (Ref: Beginning ASP.NET in C# by Matthew MacDonald) munotes.in

Page 108


108 .Net technology Commonly Used Regular Expressions Content Regular Expression Description E-mail address* \S+@ \S+\.\S+ Check for an at (@) sign and dot
(.) and allow nonwhitespace
characters only. Password \w+ Any sequence of one or more
word characters (letter, space, or
underscore). Specific -length
password \w{4,10} A password that must be at least
four characters long but no
longer than ten characters. Advanced
password [a-zA-Z]\w{3,9} As with the specific -length
password, this regular
expression will allow four to ten
total characters. The twist is that
the first character must fall in
the range of a –z or A –Z Another
advanced
password [a-zA-Z]\w*\d+\w* This password starts with a letter
character, followed by zero or
more word characters, one or
more digits, and then zero or
more word characters Limited -length
field \S{4,10} Like the password example, this
allows four to ten characters, but
it allows special characters US Social
Security number \d{3} -\d{2} -\d{4} A sequence of three, two, and
then four digits, with each group
separated by a dash. You could
use a similar pattern when
requiring a phone number . Table 7.5: Commonly Used Regular Expressions (Ref: Beginning ASP.NET in C# by Matthew MacDonald) munotes.in

Page 109


109
Validation Example :
Figure 7.2: A sample customer form (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Several types of validation are taking place on the customer form: Three RequiredFieldValidator controls make sure the user enters a username, a password, and a password confirmation. A CompareValidator ensures that the two versions of the masked password match. A RegularExpressionValidator checks that the e-mail address contains an at (@) symbol. A RangeValidator ensures the age is a number from 0 to 120. A CustomValidator performs a special validation on the server of a “referrer code.” This code verifies that the first three characters make up a number that is divisible by 7. The tags for the validator controls are as follows: munotes.in

Page 110


110 .Net technology ErrorMessage="Your password does not match." ControlToCompare="txtPassword" ControlToValidate="txtRetype" /> The form provides two validation buttons—one that requires validation and one that allows the user to cancel the task gracefully: Here’s the event-handling code for the buttons: protected void cmdSubmit_Click(Object sender, EventArgs e) { if (Page.IsValid) { lblMessage.Text = "This is a valid form."; } munotes.in

Page 111


111
Validation } protected void cmdCancel_Click(Object sender, EventArgs e) { lblMessage.Text = "No attempt was made to validate this form."; } The only form-level code that is required for validation is the custom validation code. The validation takes place in the event handler for the CustomValidator.ServerValidate event. protected void vldCode_ServerValidate(Object source, ServerValidateEventArgs e) { try { // Check whether the first three digits are divisible by seven. int val = Int32.Parse(e.Value.Substring(0, 3)); if (val % 7 == 0) { e.IsValid = true; } else { e.IsValid = false; } } catch { // An error occurred in the conversion. // The value is not valid. e.IsValid = false; } } munotes.in

Page 112


112 .Net technology 7.8 SUMMARY In this chapter, you learned how to use one of ASP.NET’s most practical features: validation. You saw how ASP. NET combines server-side and client-side validation to ensure bulletproof security without sacrificing the usability of your web pages. You also looked at the types of validation provided by the various validation controls, and even brushed up on the powerful pattern-matching syntax used for regular expressions 7.9 REFERANCE • Beginning ASP.NET in C# by Matthew MacDonald 7.10 QUESTIONS 1. Write and explain Validation control. 2. Explain Server-side validation 3. Explain Client-side validation 4. Explain Manual validation 5. Explain validation with Regular expression.  munotes.in

Page 113

113 8 RICH CONTROLS Unit Structure : 8.0 Objectives 8.1 Introduction 8.2 Calendar Control 8.2.1 Formatting the Calendar 8.2.2 CalendarDay Properties 8.3 AdRotator Control 8.3.1 The Advertisement File 8.3.2 The AdRotator Class 8.4 MultiView Control 8.4.1 Creating Views 8.5 Summary 8.6 Reference 8.7 Questions 8.0 OBJECTIVES  Rich controls are web controls that model complex user interface elements.  Although no strict definition exists for what is and what isn’t a rich control, the term commonly describes a web control that has an object model that’s distinctly separate from the HTML it generates. 8.1 INTRODUCTION  Rich control provides object model that has complex HTML representation and also client-side JavaScript  Rich controls are web controls that model complex user interface elements.  A typical rich control can be programmed as a single object but renders itself using a complex sequence of HTML elements.  Rich controls can also react to user actions (such as a mouse click on a specific region of the control) and raise more-meaningful events that your code can respond to on the web server.  In other words, rich controls give you a way to create advanced user interfaces in your web pages without writing lines of convoluted HTML. munotes.in

Page 114


114 .Net technology 8.2 CALENDAR CONTROL  The Calendar control presents a miniature calendar that you can place in any web page.  The Calendar control presents a single-month view  The user can navigate from month to month by using the navigational arrows, at which point the page is posted back and ASP.NET automatically provides a new page with the correct month values
Figure 8.1: The default Calendar (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  Depending on the value you choose, you can allow users to select days (Day), entire weeks (DayWeek), whole months (DayWeekMonth), or render the control as a static calendar that doesn’t allow selection (None).  You may also want to set the Calendar.FirstDayOfWeek property to configure how a week is shown.  For example, set FirstDayOfWeek to the enumerated value Sunday, and weeks will be selected from Sunday to Saturday.  The following code demonstrates this technique: lblDates.Text = "You selected these dates:
"; foreach (DateTime dt in MyCalendar.SelectedDates) { lblDates.Text += dt.ToLongDateString() + "
"; }
munotes.in

Page 115


115
Rich Controls
Figure 8.2: Selecting multiple dates (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 8.2.1 Formatting the Calendar  The Calendar control provides a whole host of formatting-related properties. Member Description DayHeaderStyle The style for the section of the Calendar that
displays the days of the week (as column
headers). DayStyle The default style for the dates in the current
month NextPrevStyle The style for the navigation controls in the title
section that move from month to month. OtherMonthDayStyle The style for the dates that aren’t in the
currently displayed month. These dates are
used to “fill in” the calendar grid. For
example, the first few cells in the topmost row
may display the last few days from the
previous month.
munotes.in

Page 116


116 .Net technology Member Description SelectedDayStyle The style for the selected dates on the calendar SelectorStyle The style for the week and month date
selection contro ls. TitleStyle The style for the title section. TodayDayStyle The style for the date designated as today
(represented by the TodaysDate property of
the Calendar control). WeekendDayStyle The style for dates that fall on the weekend. Table 8.1: Properties for Calendar Styles (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  You can adjust each style by using the Properties window.  For a quick shortcut, you can set an entire related color scheme by using the Calendar’s Auto Format feature.  To do so, start by selecting the Calendar on the design surface of a web form. Then click the arrow icon that appears next to its top-right corner to show the Calendar’s smart tag, and click the Auto Format link.  You’ll be presented with a list of predefined formats that set the style properties
Figure 8.3: Calendar Styles (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 117


117
Rich Controls 8.2.2 CalendarDay Properties Property Description Date The DateTime object that represents this date. IsWeekend True if this date falls on a Saturday or Sunday. IsToday True if this value matches the
Calendar.TodaysDate property, which is set to the
current day by default. IsOtherMonth True if this date doesn’t belong to the current
month but is displaye d to fill in the first or last row. IsSelectable Allows you to configure whether the user can
select this day. Table 8.2: CalendarDay Properties (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Members of the Calendar control class. Member Description Caption and
CaptionAlign Gives you an easy way to add a title to the
calendar. By default, the caption appears at the
top of the title area, just above the month
heading. CellPadding ASP.NET creates a date in a separate cell of an
invisible t able. CellPadding is the space, in
pixels, between the border of each cell and its
contents. CellSpacing The space, in pixels, between cells in the same
table. DayNameFormat Determines how days are displayed in the
calendar header. Valid values are Full (as in
Sunday), FirstLetter (S), FirstTwoLetters (Su),
and Short (Sun), which is the default. FirstDayOfWeek Determines which day is displayed in the first
column of the calendar. The values are any day
name from the FirstDayOfWeek enumeration
(such as Sunday). By default, this is Sunday. TitleFormat Configures how the month is displayed in the
title area. Valid values include Month and
MonthYear TodaysDate Sets which day should be recognized as the
current date and formatted with the
TodayDayStyle. This defaults to the current day
on the web server. munotes.in

Page 118


118 .Net technology Member Description VisibleDate Gets or sets the date that specifies what month
will be displayed in the calendar. This allows
you to change the calendar display without
modifying the current date selection. ShowDayHeader ,
ShowGridLines,
ShowNextPrevMonth,
and ShowTitle These Boolean properties allow you to configure
whether various parts of the calendar are shown,
including the day titles, gridlines between every
day, the previous/next month navigation links,
and the titl e section. Note that hiding the title
section also hides the next and previous month
navigation controls. Table 8.3: Calendar Members (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 8.3 ADROTATOR CONTROL  The basic purpose of the AdRotator is to provide a graphic on a page that is chosen randomly from a group of possible images.  In other words, every time the page is requested, an image is selected at random and displayed, which is the rotation indicated by the name AdRotator.  One use of the AdRotator is to show banner-style advertisements on a page, but you can use it anytime you want to vary an image randomly. 8.3.1 The Advertisement File  The AdRotator stores its list of image files in an XML file. This file uses the format shown here: prosetech.jpg http://www.prosetech.com ProseTech Site 1 Computer  This example shows a single possible advertisement, which the AdRotator control picks at random from the list of advertisements. munotes.in

Page 119


119
Rich Controls  To add more advertisements, you would create multiple elements and place them all inside the root element:  Each element has a number of other important properties that configure the link, the image, and the frequency. Element Description ImageUrl The image that will be displayed. This can be a relative
link (a file in the current directory) or a fully qualified
Internet URL. NavigateUrl The link that will be followed if the user clicks the
banner. This can be a relative or fully qualified URL. AlternateText The text that will be displayed instead of the picture if it
cannot be displayed. This text will also be used as a
tooltip in some newer browsers. Impressions A number that sets how often an advertisement will
appear. This number is relative to the numbers specified
for other ads. For example, a banner with the value 10
will be shown twice as often (on average) as the banner
with the value 5. Keyword A keyword that identifies a group of advertisements.
You can use this for filtering. For exa mple, you could
create ten advertisements and give half of them the
keyword Retail and the other half the keyword
Computer. Table 8.4: Advertisement File Elements (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 8.3.2 The AdRotator Class  The actual AdRotator class provides a limited set of properties.  You specify both the appropriate advertisement file in the AdvertisementFile property and the type of window that the link should follow (the Target window). The target can name a specific frame munotes.in

Page 120


120 .Net technology Target Description _blank The link opens a new unframed window. _parent The link opens in the parent of the current frame. _self The link opens in the current frame. _top The link opens in the topmost frame of the current
window Table 8.5: Advertisement File Elements (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  Optionally, you can set the KeywordFilter property so that the banner will be chosen from a specific keyword group. This is a fully configured AdRotator tag:  The event-handling code for this example simply configures a HyperLink control named lnkBanner based on the randomly selected advertisement: protected void Ads_AdCreated(Object sender, AdCreatedEventArgs e) { // Synchronize the Hyperlink control. lnkBanner.NavigateUrl = e.NavigateUrl; // Syncrhonize the text of the link. lnkBanner.Text = “Click here for information about our sponsor: “; lnkBanner.Text += e.AlternateText; } 8.4 MULTIVIEW CONTROL  The MultiView is the simpler of the two multiple-view controls.  The MultiView gives you a way to declare multiple views and show only one at a time.  Creating a MultiView is suitably straightforward. You add the tag to your .aspx page file and then add one tag inside it for each separate view: ... ... ... munotes.in

Page 121


121
Rich Controls 8.4.1 Creating Views  Full markup for a MultiView that splits the greeting card controls into three views named View1, View2, and View3: Choose a foreground (text) color:


Choose a background color:
Choose a border style:

Choose a font name:


Specify a font size:


Enter the greeting text below:
munotes.in

Page 122


122 .Net technology
Figure 8.4: Designing multiple views (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 8.4.2 Showing a View  If you run this example, you won’t see what you expect.  The MultiView will appear empty on the page, and all the controls in all your views will be hidden.  The reason this happens is that the MultiView.ActiveViewIndex property is, by default, set to –1. The ActiveViewIndex property determines which view will be shown.  If you set the ActiveViewIndex to 0, however, you’ll see the first view. Similarly, you can set it to 1 to show the second view, and so on.  You can set this property by using the Properties window or using code: // Show the first view. MultiView1.ActiveViewIndex = 0;  This example shows the first view (View1) and hides whatever view is currently being displayed, if any.
munotes.in

Page 123


123
Rich Controls  You can also use the SetActiveView() method, which accepts any one of the view objects you’ve created, rather than the view name. MultiView1.SetActiveView(View1);  Following table shows lists all the recognized command names. Each command name also has a corresponding static field in the MultiView class. Command Name MultiView Field Description PrevView PreviousViewCommandName Moves to the
previous view. NextView NextViewCommandName Moves to the next
view. SwitchViewByID SwitchViewByIDCommandNam
e Moves to the view
with a specific ID
(string name). The
ID is taken from
the
CommandArgum
ent property of the
button control. SwitchViewByInd
ex SwitchViewByIndexCommandN
ame Moves to the view
with a specific
numeric index.
The index is taken
from the
CommandArgum
ent property of the
button control. Table 8.6: Recognized Command Names for the MultiView (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 8.5 SUMMARY  This chapter showed you how the rich Calendar, AdRotator, MultiView, and Wizard controls can go far beyond the limitations of ordinary HTML elements.  When you’re working with these controls, you don’t need to think about HTML at all. Instead, you can focus on the object model that’s defined by the control. munotes.in

Page 124


124 .Net technology 8.6 REFERENCE • Beginning ASP.NET in C# by Matthew MacDonald 8.7 QUESTIONS 1. Explain Calendar control. 2. Write and explain formatting properties for calendar. 3. Write and explain members of the calender control. 4. Explain AdRotator control. 5. Explain multiview control.  munotes.in

Page 125


125
Themes and Master Pages 9 THEMES AND MASTER PAGES Unit Structure: 9.0 Objectives 9.1 Introduction 9.2 How Themes Work 9.3 Applying a Simple Theme 9.4 Handling Theme Conflicts 9.5 Simple Master Page and Content Page 9.6 Connecting Master pages and Content Pages 9.7 Master Page with Multiple Content Regions 9.8 Master Pages and Relative Paths 9.9 Summary 9.10 Reference 9.11 Questions 9.0 OBJECTIVES Using the techniques, you’ve learned so far, you can create polished web pages and let users surf from one page to another. However, to integrate your web pages into a unified, consistent website, you need a few more tools. In this chapter, you’ll consider three of the most important tools that you can use: styles, themes, and master pages. 9.1 INTRODUCTION ASP. NET includes themes feature, which plays a similar role as styles but works exclusively with server controls. Best feature for standardizing websites is master pages. Essentially, a master page is a blueprint for part of your website. Using a master page, you can define web page layout, complete with the usual details such as headers, menu bars, and ad banners. Once you’ve perfected a master page, you can use it to create content pages. Each content page automatically acquires the layout and the content of the linked master page. By using themes, and master pages, you can ensure that all the pages on your website share a standardized look and layout. munotes.in

Page 126


126 .Net technology 9.2 HOW THEMES WORK All themes are application specific. To use a theme in a web application, you need to create a folder that defines it. This folder needs to be placed in the App_Themes folder, which must be placed inside the top-level directory for your web application. To use theme, you need to create at least one skin file in the theme folder. A skin file is a text file with the .skin extension
Figure 9.1: Themes and skins (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 9.3 APPLYING A SIMPLE THEME: To add a theme to your project, select Website➤ Add New Item, and choose Skin File. Visual Studio will warn you that skin files need to be placed in a subfolder of the App_Themes folder and ask you whether that’s what you intended. If you choose Yes, Visual Studio will create a folder with the same name as your theme file. You can then rename the folder and the file to whatever you’d like to use.
Figure 9.2: A theme in the Solution Explorer (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 127


127
Themes and Master Pages Here’s a sample skin file that sets background and foreground colors for several common controls: To apply the theme in a web page, you need to set the Theme attribute of the Page directive to the folder name for your theme. <%@ Page Language="C#" AutoEventWireup ="true" ... Theme="FunkyTheme" %>
Figure 9.3: A simple page after theming (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 9.4 HANDLING THEME CONFLICTS: When properties conflict between your controls and your theme, the theme wins. However, in some cases you might want to change this behavior so that your controls can fine-tune a theme by specifically overriding certain details. ASP.NET gives you this option, but it’s an all-or-nothing setting that applies to all the controls on the entire page. To make this change, just use the StyleSheetTheme attribute instead of the Theme attribute in the Page directive. <%@ Page Language="C#" AutoEventWireup ="true" ... StyleSheetTheme="FunkyTheme" %>
munotes.in

Page 128


128 .Net technology Now the custom yellow background of the ListBox control takes precedence over the background color specified by the theme. Figure shows the result—and a potential problem. Because the foreground color has been changed to white, the lettering in the large text box is now impossible to see. Overlapping formatting specifications can cause glitches like this, which is why it’s often better to let your themes take complete control by using the Theme attribute.
Figure 9.4: Giving the control tag precedence over the theme (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 9.5 SIMPLE MASTER PAGE AND CONTENT PAGE: Master pages are similar to ordinary ASP.NET pages. Like ordinary pages, master pages are text files that can contain HTML, web controls, and code. However, master pages have a different file extension (.master instead of .aspx), and they can’t be viewed directly by a browser. Instead, master pages must be used by other pages, which are known as content pages. Essentially, the master page defines the page structure and the common ingredients. A single master page might define the layout for the entire site. Every page would use that master page, and as a result, every page would have the same basic organization and the same title, footer, and so on.
munotes.in

Page 129


129
Themes and Master Pages However, each page would also insert its specific information, such as product descriptions, book reviews, or search results, into this template To create a master page in Visual Studio, select Website➤Add New Item from the menu. Select Master Page, give it a file name (such as SiteTemplate.master, used in the next example), and click Add. The ContentPlaceHolder is the portion of the master page that a content page can change. Or, to look at it another way, everything else that’s set in the master page is unchangeable in a content page. If you add a header, that header appears in every content page. If you want to give the content page the opportunity to supply content in a specific section of the page, you need to add a ContentPlaceHolder.
Figure 9.5: A new master page (Ref: Beginning ASP.NET in C# by Matthew MacDonald) When you first create a master page, you’ll start with two ContentPlaceHolder controls. One is defined in thesection, which gives content pages the add page metadata, such as search keywords and style sheet links. The second, more important ContentPlaceHolder is defined in the section, and represents the displayed content of the page. It appears on the page as a faintly outlined box. If you click inside it or hover over it, the name of ContentPlaceHolder appears in a tooltip.
munotes.in

Page 130


130 .Net technology Now you’re ready to create a content page based on this master page. To take this step, select Website➤ Add New Item from the menu. Select Web Form, and choose to select a master page. Click Add. When you’re prompted to choose a master page, use the one you created with the header and footer.
Figure 9.6: Creating a content page (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Your content page will have all the elements of the master page 9.6 CONNECTING MASTER PAGES AND CONTENT PAGES: When you create a master page, you’re building something that looks much like an ordinary ASP.NET web form. The key difference is that, although web forms start with the Page directive, a master page starts with a Master directive that specifies the same information. Here’s the Master directive for the simple master page shown in the previous example: <%@ Master Language="C#" AutoEventWireup ="true" CodeFile="SiteTemplate.master.cs" Inherits="SiteTemplate" %> The ContentPlaceHolder is less interesting. You declare it like any ordinary control. Here’s the complete code for the simple master page: <%@ Master Language="C#" AutoEventWireup ="true" CodeFile="SiteTemplate.master.cs" Inherits="SiteTemplate" %>
munotes.in

Page 131


131
Themes and Master Pages Untitled Page


This is a simple footer.
When you create a content page, ASP.NET links your page to the master page by adding an attribute to the Page directive. This attribute, named MasterPageFile, indicates the associated master page. Here’s what it looks like: <%@ Page Language="C#" MasterPageFile ="~/SiteTemplate.master" AutoEventWireup="true" CodeFile="SimpleContentPage.aspx.cs" Inherits="SimpleContentPage" Title="Untitled Page" %> Notice that the MasterPageFile attribute begins with the path ~/ to specify the root website folder. 9.7 MASTER PAGE WITH MULTIPLE CONTENT REGIONS Master pages aren’t limited to one ContentPlaceHolder. Instead, you can insert as many as you need to give the client the ability to intersperse content in various places. All you need to do is add multiple ContentPlaceHolder controls and arrange them appropriately. Example: <%@ Master Language="C#" AutoEventWireup ="true" CodeFile="MultipleContent.master.cs" Inherits="MultipleContent" %> Untitled Page munotes.in

Page 132


132 .Net technology


OTHER LINKS
This is a simple footer.
When you create a new content page based on this master page, Visual Studio will start you with one Content control for each ContentPlaceHolder in the master page, making your life easy. All you need to do is insert the appropriate information. Here’s a slightly shortened example, with some of the text replaced with an ellipsis (. . .) to save space: <%@ Page Language="C#" MasterPageFile ="~/MultipleContent.master" AutoEventWireup="true" CodeFile="MultipleContentPage.aspx.cs" Inherits="MultipleContentPage" Title="Content Page" %> This is the generic content for this page. Here you might provide some site specific text ... Here’s alink.
...
munotes.in

Page 133


133
Themes and Master Pages 9.8 MASTER PAGES AND RELATIVE PATHS: One quirk that can catch unsuspecting developers is the way that master pages handle relative paths. If all you’re using is static text, this issue won’t affect you. However, if you addError! Filename not specified.tags or any other HTML tag that points to another resource, problems can occur. The problem shows up if you place the master page in a different directory from the content page that uses it. This is a recommended best practice for large websites. In fact, Microsoft encourages you to use a dedicated folder for storing all your master pages. However, if you’re not suitably careful, this can cause problems when you use relative paths. For example, imagine you put a master page in a subfolder named MasterPages and add the followingError! Filename not specified.tag to the master page: Assuming the file \MasterPages\banner.jpg exists, this appears to work fine. The image will even appear in the Visual Studio design environment. However, if you create a content page in another subfolder, the image path is interpreted relative to that folder. If the file doesn’t exist there, you’ll get a broken link instead of your graphic. Even worse, you could conceivably get the wrong graphic if another image has the same file name. To solve your problem, you could try to think ahead and write your URL relative to the content page where you want to use it. But this creates confusion and limits where your master page can be used. A better fix is to turn yourError! Filename not specified.tag into a server-side control, in which case ASP.NET will fix the mistake: 9.9 SUMMARY Building a professional web application involves much more than designing individual web pages. You also need the tools to integrate munotes.in

Page 134


134 .Net technology your web pages in a complete, unified website. In this chapter, you considered best ways to do exactly that. ASP.NET themes feature, which lets you effortlessly apply a group of property settings to a control. Finally, you learned to use master pages, which allow you to standardize the layout of your website. All these features make it easy to bring your pages together into a well-integrated, consistent web application. 9.10 REFERANCE • Beginning ASP.NET in C# by Matthew MacDonald 9.11 QUESTIONS 1. Explain themes and master pages in detail. 2. What is concept of master pages and content pages and how connect them? 3. Explain how themes works. 4. Explain how to handle theme conflicts.  munotes.in

Page 135


135
Website Navigation 10 WEBSITE NAVIGATION Unit Structure : 10.0 Objectives 10.1 Introduction 10.2 Site Maps 10.3 URL Mapping and Routing 10.4 SiteMapPath Control 10.5 TreeView Control 10.6 Menu Control 10.7 Summary 10.8 Reference 10.9 Questions 10.0 OBJECTIVES  Website navigation is an essential part of web design because it contributes to the user experience.  Understanding website navigation can help you allow users to access the information they want as quickly as possible by presenting an enjoyable, intuitive layout while increasing ease of use. 10.1 INTRODUCTION  ASP.NET provides various site-navigation features which gives a consistent way for visitors to navigate the site.  These features are Site Maps. URL Mapping and Routing, SiteMapPath. 10.2 SITE MAPS  If your website has more than a handful of pages, you’ll probably want some sort of navigation system to let users move from one page to the next.  As with all the best ASP.NET features, ASP.NET navigation is flexible, configurable, and pluggable. It consists of three components: 1. A way to define the navigation structure of your website. This part is the XML site map, which is (by default) stored in a file. munotes.in

Page 136


136 .Net technology 2. A convenient way to read the information in the site map file and convert it to an object model. The SiteMapDataSource control and the XmlSiteMapProvider perform this part. 3. A way to use the site map information to display the user’s current position and give the user the ability to easily move from one place to another. This part takes place through the navigation controls you bind to the SiteMapDataSource control, which can include breadcrumb links, lists, menus, and trees.
Figure 10.1: ASP.NET navigation with site maps (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  You can create a site map by using a text editor such as Notepad, or you can create it in Visual Studio by choosing Website ➤ Add New Item and then choosing the Site Map option.  Either way, it’s up to you to enter all the site map information by hand.  The only difference is that if you create it in Visual Studio, the site map will start with a basic structure that consists of three siteMap nodes. Rule 1: Site Maps Begin with the Element • Every Web.sitemap file begins by declaring the element and ends by closing that element. You place the actual site map information between the start and end tags (where the three dots are shown here): ... • The xmlns attribute is required, and must be entered exactly as shown here. This tells ASP.NET that the XML file uses the ASP.NET site map standard.
munotes.in

Page 137


137
Website Navigation Rule 2: Each Page Is Represented by a Element • Essentially, every site map defines an organization of web pages. • To insert a page into the site map, you add the element with some basic information. • Namely, you need to supply the title of the page, a description and the URL. • You add these three pieces of information by using three attributes—named title, description, and url, as shown here: • Notice that this element ends with the characters />. • This indicates it’s an empty element that represents a start tag and an end tag in one. • Empty elements never contain other nodes. • Here’s a complete, valid site map file that uses this page to define a website with exactly one page: Rule 3: A Element Can Contain Other Elements • Site maps don’t consist of simple lists of pages. Instead, they divide pages into groups. • To represent this in a site map file, you place one inside another. • Instead of using the empty element syntax shown previously, you’ll need to split your element into a start tag and an end tag: ... • Now you can slip more nodes inside. Here’s an example of a Home group that contains two more pages:

Page 138


138 .Net technology url="~/products.aspx" />
Figure 10.2: Three nodes in a site map (Ref: Beginning ASP.NET in C# by Matthew MacDonald) • In this case, all three nodes are links. This means the user could surf to one of three pages. • However, when you start to create more-complex groups and subgroups, you might want to create nodes that serve only to organize other nodes but aren’t links themselves. • In this case, just omit the url attribute, as shown here with the Products node: Rule 4: Every Site Map Begins with a Single • Another rule applies to all site maps. • A site map must always have a single root node.
munotes.in

Page 139


139
Website Navigation • All the other nodes must be contained inside this root-level node. • That means the following is not a valid site map, because it contains two top-level nodes: • The following site map is valid, because it has a single top-level node (Home), which contains two more nodes: Rule 5: Duplicate URLs Are Not Allowed • You cannot create two site map nodes with the same URL. • This might seem to present a bit of a problem when you want to have the same link in more than one place—and it does. • However, it’s a requirement because the default SiteMapProvider included with ASP.NET stores nodes in a collection, with each item indexed by its unique URL. • This limitation doesn’t prevent you from creating more than one URL with minor differences pointing to the same page. For example, consider the following portion of a site map. • These two nodes are acceptable, even though they lead to the same page (products.aspx), because the two URLs have different query string arguments at the end. munotes.in

Page 140


140 .Net technology 10.3 URL MAPPING AND ROUTING URL Mapping  In some situations, you might want to have several URLs lead to the same page.  This might be the case for a number of reasons—maybe you want to implement your logic in one page and use query string arguments but still provide shorter and easier-to-remember URLs to your website users.  The basic idea behind ASP.NET URL mapping is that you map a request URL to a different URL.  The mapping rules are stored in the web.config file, and they’re applied before any other processing takes place.  Of course, for ASP.NET to apply the remapping, it must be processing the request, which means the request URL must use a file type extension that’s mapped to ASP.NET.  We can define URL mapping in the section of the web.config file. You supply two pieces of information—the request URL (as the url attribute) and the new destination URL (mappedUrl). Here’s an example: ...  In order for ASP.NET to make a match, the URL that the browser submits must match the URL specified in the web.config file almost exactly.  When you use URL mapping, the redirection takes place in the same way as the Server.Transfer() method, which means no round-trip happens and the URL in the browser will still show the original request URL, not the new page. munotes.in

Page 141


141
Website Navigation URL ROUTING  URL routing was originally designed as a core part of ASP.NET MVC, an alternative framework for building web pages.  Unlike URL mapping, URL routing doesn’t take place in the web.config file. Instead, it’s implemented using code.  Typically, you’ll use the Application_Start() method in the global.asax file to register all the routes for your application.  To register a route, you use the RouteTable class from the System.Web.Routing namespace. To make life easier, you can start by importing that namespace: using System.Web.Routing;  The RouteTable class provides a static property named Routes, which holds a collection of Route objects that are defined for your application.  Initially, this collection is empty, but you can create custom routes by calling the MapPageRoute() method, which takes three arguments: • routeName: This is a name that uniquely identifies the route. It can be whatever you want. • routeUrl: This specifies the URL format that browsers will use. Typically, a route URL consists of one or more pieces of variable information, separated by slashes, which are extracted and provided to your code. For example, you might request a product page by using a URL such as /products/4312. • physicalFile: This is the target web form—the place where users will be redirected when they use the route. The information from the original routeUrl will be parsed and made available to this page as a collection through the Page.RouteData property.  Here’s an example that adds two routes to a web application when it first starts: protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapPageRoute("product-details", "product/{productID}", "~/productInfo.aspx"); RouteTable.Routes.MapPageRoute("products-in-category", "products/category/{categoryID}", "~/products.aspx"); } munotes.in

Page 142


142 .Net technology 10.4 SITEMAPPATH CONTROL  The TreeView shows the available pages, but it doesn’t indicate where you’re currently positioned. To solve this problem, it’s common to use the TreeView in conjunction with the SiteMapPath control.  The SiteMapPath provides breadcrumb navigation, which means it shows the user’s current location and allows the user to navigate up the hierarchy to a higher level by using links.  Using the SiteMapPath control, the user can return to the default.aspx page.
Figure 10.3: Breadcrumb navigation with SiteMapPath (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Lists some of its most commonly configured properties. Property Description ShowToolTips Set this to false if you don’t want the
description text to appear when the user
hovers over a part of the site map path. ParentLevelsDisplayed This sets the maximum number of levels
above the current page that will be shown
at once. By defa ult, this setting is –1, which
means all levels will be shown. RenderCurrentNodeAsLink If true, the portion of the page that
indicates the current page is turned into a
clickable link. By default, this is false
because the user is already at the current
page.
munotes.in

Page 143


143
Website Navigation PathDirection You have two choices: RootToCurrent (the
default) and CurrentToRoot (which
reverses the order of levels in the path). PathSeparator This indicates the characters that will be
placed between each level in the path. The
default is the greater -than symbol (>).
Another common path separator is the
colon (:). Table 10.1: SiteMapPath Appearance-Related Properties (Ref: Beginning ASP.NET in C# by Matthew MacDonald) Using SiteMapPath Styles and Templates Style Template Applies To NodeStyle NodeTemplate All parts of the path
except the root and
current node. CurrentNodeStyle CurrentNodeTemplate The node representing
the current page. RootNodeStyle RootNodeTemplate The node representing
the root. If the root node
is the same as th e current
node, the current node
template or styles are
used. PathSeparatorStyle PathSeparatorTemplate The separator between
each node Table 10.2: SiteMapPath Styles and Templates (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 10.5 TREEVIEW CONTROL  The TreeView has a slew of properties that let you change how it’s displayed on the page. One of the most important properties is ImageSet, which lets you choose a predefined set of node icons.  The TreeView offers 16 possible ImageSet values, which are represented by the TreeViewImageSet enumeration.  For example, following Figure shows the same RevoStock navigation page you considered earlier, but this time with an ImageSet value of TreeViewImageSet.Faq. munotes.in

Page 144


144 .Net technology
Figure 10.4: A TreeView with fancy node icons (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  Here’s the complete TreeView markup: 10.5.1 Useful TreeView Properties Property Description MaxDataBindDepth Determines how many levels the TreeView will
show. By default, MaxDataBindDepth is –1, and
you’ll see the entire tree. ExpandDepth Lets you specify how many levels of nodes will be
visible at first. If you use 0, the TreeView begins
completely closed. NodeIndent Sets the number of pixels between each level of
nodes in the TreeView. Set this to 0 to create a
nonindented TreeView, which saves space. ImageSet Lets you use a predefined collection of node
images for collapsed, expanded, and
nonexpandable nodes. ShowLines Adds lines that connect every node when set to
true. NodeWrap Lets a node text -wrap over more than one line
when set to true. ShowCheckBoxes Shows a check box next to every node when set to
true. This isn’t terribly useful for site maps, but it
is useful with other types of trees. Table 10.3: Useful TreeView Properties (Ref: Beginning ASP.NET in C# by Matthew MacDonald)
munotes.in

Page 145


145
Website Navigation 10.5.2 TreeView Styles  Styles are represented by the TreeNodeStyle class, which derives from the more conventional Style class.  As with other rich controls, the styles give you options to set background and foreground colors, fonts, and borders. TreeNodeStyle-Added Properties Property Description ImageUrl The URL for the image shown next to the node. NodeSpacing The space (in pixels) between the current node and
the node above and below. VerticalPadding The space (in pixels) between the top and bottom
of the node text and border around the text. HorizontalPadding The space (in pixels) between the left and right of
the node text and border around the text. ChildNodesPadding The space (in pixels) between the last child node of
an expanded par ent node and the following node. Table 10.4: TreeNodeStyle-Added Properties (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 10.6 MENU CONTROL  The Menu control is another rich control that supports hierarchical data. Like the TreeView, you can bind the Menu control to a data source, or you can use MenuItem objects to fill it by hand. munotes.in

Page 146


146 .Net technology
Figure 10.5: Navigating through the menu (Ref: Beginning ASP.NET in C# by Matthew MacDonald)  Overall, the Menu and TreeView controls expose strikingly similar programming models, even though they render themselves quite differently.  They also have a similar style-based formatting model. But a few noteworthy differences exist: • The Menu displays a single submenu. The TreeView can expand an arbitrary number of node branches at a time. • The Menu displays a root level of links in the page. All other items are displayed using fly-out menus that appear over any other content on the page. The TreeView shows all its items inline in the page. • The Menu supports templates. The TreeView does not. (Menu templates are discussed later in this section.) • The TreeView supports check boxes for any node. The Menu does not.
munotes.in

Page 147


147
Website Navigation • The Menu supports horizontal and vertical layouts, depending on the Orientation property. The TreeView supports only vertical layout. Menu Styles Static Style Dynamic Style Description StaticMenuStyle DynamicMenuStyle Sets the appearance of
the overall “box” in
which all the menu
items appear. In the
case of
StaticMenuStyle, this
box appears on the
page, and with
DynamicMenuStyle,
it appears as a pop -up. StaticMenuItemStyle DynamicMenuItemStyle Sets the appearance of
individual menu
items. StaticSelectedStyle DynamicSelectedStyle Sets the appearance of
the selected item.
Note that the selected
item isn’t the item
that’s currently being
hovered over; it’s the
item that was
previously clicked StaticHoverStyle DynamicHoverStyle Sets the appearance of
the item that the user
is hovering over with
the mouse. Table 10.5: Menu Styles (Ref: Beginning ASP.NET in C# by Matthew MacDonald) 10.7 SUMMARY  In this chapter, you explored the new navigation model and learned how to define site maps and bind the navigation data.  You then considered three controls that are specifically designed for navigation data: the SiteMapPath, TreeView, and Menu.  Using these controls, you can add remarkably rich site maps to your websites with very little coding. munotes.in

Page 148


148 .Net technology  But before you begin, make sure you’ve finalized the structure of your website.  Only then will you be able to create the perfect site map and choose the best ways to present the site map information in the navigation controls. 10.8 REFERANCE • Beginning ASP.NET in C# by Matthew MacDonald 10.9 QUESTIONS 1. Explain SiteMapPath control in detail. 2. Write note on menu control. 3. Write note on TreeView control. 4. Write and explain Menu style. 5. Write and explain TreeView properties.  munotes.in

Page 149

149 11 ADO.NET Unit Structure : 11.0 Objective 11.1 Introduction 11.2 Data Provider Model 11.3 Direct Data Access 11.4 Creating a Connection 11.5 Select Command 11.6 DataReader 11.7 Disconnected Data Access 11.8 Summary 11.9 Reference for further reading 11.10 Unit End Exercises 11.0 OBJECTIVE 1. To understand the basic and advanced concepts of ADO.NET. 2. To learn how to establish connection between application and data sources. 3. To study the different components of ADO.NET that are used for accessing and manipulating data are the .NET Framework data provider and the DataSet. 4. To learn how to prevent SQL injection attacks and how to use transactions. 11.1 INTRODUCTION ● ADO.NET consists of managed classes that allow .NET applications to connect to data sources (relational databases), execute commands, and manage disconnected data. ● The small miracle of ADO.NET is that it enables you to write more or less the same data access code in web applications that you write for client-server desktop applications, or even single-user applications that connect to a local database. ● This shows the implementation of the architecture of ADO.NET and the ADO.NET data providers. ● ADO.NET describes such as opening a connection, executing a SQL statement or stored procedure, and retrieving the results of a query. munotes.in

Page 150


150 .Net technology 11.2 DATA PROVIDER MODEL ● ADO.NET uses a multilayered architecture that revolves around a few key concepts, such as Connection, Command, and DataSet objects. ● One of the key differences between ADO.NET and some other database technologies is how it deals with the challenge of different data sources. ● In many past database technologies, such as classic ADO, programmers use a generic set of objects no matter what the underlying data source is. For example, if you want to retrieve a record from an Oracle database using ADO code, we use the same Connection class you would use to tackle the task with SQL Server. ● ADO.NET Data Providers A data provider is a set of ADO.NET classes that allows you to access a specific database, execute SQL commands, and retrieve data. ● A data provider is a bridge between your application and a data source. The classes that make up a data provider include the following: ○ Connection: You use this object to establish a connection to a data source. ○ Command: You use this object to execute SQL commands and stored procedures. ○ DataReader: This object provides fast read-only, forward-only access to the data retrieved from a query. ○ DataAdapter: This object performs two tasks. First, you can use it to fill a DataSet with information extracted from a data source. Second, you can use it to apply changes to a data source, according to the modifications made in a DataSet. ● ADO.NET doesn’t include generic data provider objects. Instead, it includes different data providers specifically designed for different types of data sources. Each data provider has a specific implementation of the Connection, Command, DataReader, and DataAdapter classes that’s optimized for a specific RDBMS. For example, if you need to create a connection to a SQL Server database, use a connection class named SqlConnection. ● Developers can create their own providers for proprietary data sources. In fact, numerous proof-of-concept examples are available that show how you can easily create custom ADO.NET providers to wrap non relational data stores, such as the file system or a directory service. Some third-party vendors also sell custom providers for .NET munotes.in

Page 151


151
ADO.Net ● The .NET Framework is bundled with a small set of four providers: ○ SQL Server provider: Provides optimized access to a SQL Server database ○ OLE DB provider: Provides access to any data source that has an OLE DB driver. ○ Oracle provider: Provides optimized access to an Oracle database ○ ODBC provider: Provides access to any data source that has an ODBC driver. Figure 1 shows the layers of the ADO.NET provider model.
Figure 1 The ADO.NET architecture 11.3 DIRECT DATA ACCESS ● ADO.NET does not provide a single set of objects that communicate with multiple database management systems (DBMSs). ● ADO.NET supports multiple data providers, each of which is optimized to interact with a specific DBMS. ● The first benefit of this approach is that you can program a specific data provider to access any unique features of a particular DBMS. ● The second benefit is that a specific data provider can connect directly to the underlying engine of the DBMS in question without an intermediate mapping layer standing between the tiers to communicate with a specific type of data source. ● Following Table 1 shows documents of some of the core common types, their base class and the key interfaces they implement.
munotes.in

Page 152


152 .Net technology Type of
Object Base Class Relevant
Interfaces Meaning in Life Connection DbConnection IDbConnection Provides the ability
to connect to and
disconnect from the
data store.
Connection objects
also provide access
to a related
transaction object. Command DbCommand IDbCommand Represents a SQL
query or a stored
procedure.
Command objects
also provide access
to the provider’s
data reader object. DataReader DbDataReader IDataReader,
IDataRecord Provides forward -
only, read -only
access to data using
a server -side cursor. DataAdapter DbDataAdapter
IDataAdapter,
IDbDataAdapter Transfers DataSets
between the caller
and the data store.
Data adapters
contain a connection
and a set of four
internal command
objects used to
select, insert,
update, and delete
information from
the data store. Parameter DbParameter
IDataParameter,
IDbDataParameter Represents a named
parameter within a
parameterized
query. Transaction DbTransaction IDbTransaction Encapsulates a
database transaction Table 1 Core Common Types ● Figure 2 shows the ADO.NET data providers. munotes.in

Page 153


153
ADO.Net ● A data provider will supply with other types beyond the objects shown in Figure 2 however, these core objects define a common baseline across all data providers.
Figure 2. ADO.NET data providers provide access to a given DBMS ADO.NET Data Providers ● A .NET Framework data provider is used for connecting to a database, executing commands, and retrieving results. ● Those results are either processed directly, placed in a DataSet in order to be exposed to the user as needed, combined with data from multiple sources, or remoted between tiers. .NET Framework data providers are lightweight, creating a minimal layer between the data source and code, increasing performance without sacrificing functionality. The following table 2 lists the data providers that are included in the .NET Framework. .NET Framework
data provider Description .NET Framework
Data Provider for
SQL Server Provides data access for Microsoft SQL Server.
Uses the System.Data.SqlClient name space. .NET Framework
Data Provider for
OLE DB For data sources exposed by using OLE DB. Uses
the System.Data.OleDb namespace.
munotes.in

Page 154


154 .Net technology .NET Framework
data provider Description .NET Framework
Data Provider for
ODBC For data sources exposed by using ODBC. Uses
the System.Data.Odbc namespace. .NET Framework
Data Provider for
Oracle For Oracle data sources. The .NET Framework
Data Provider for Oracle supports Oracle client
software version 8.1.7 and later, and uses the
System.Data.OracleClient namespace. EntityClient Provider Provides data access for Entity Data Model (EDM)
applications. Uses the System.Data.EntityClient
namespace. .NET Framework
Data Provider for
SQL Server Compact
4.0. Provides data access for Micro soft SQL Server
Compact 4.0. Uses the System.Data.SqlServerCe
namespace. Table 2 lists of data providers Core Objects of .NET Framework Data Providers The following table 3 outlines the four core objects that make up a .NET Framework data provider. Object Description Connection Establishes a connection to a specific data source. The base
class for all Connection objects is the DbConnection class. Command Executes a command against a data source. Exposes
Parameters and can execute in the scope of a Transaction
from a Connection. The base class for all Command objects
is the DbCommand class. DataReader Reads a forward -only, read -only stream of data from a data
source. The base class for all DataReader objects is the
DbDataReader class. DataAdapter Populates a DataSet and resolves updates with the data
source. The base class for all DataAdapter objects i s the
DbDataAdapter class. Table 3 Core objects munotes.in

Page 155


155
ADO.Net A .NET Framework data provider also contains the classes listed in the following table 4. Object Description Transaction Enlists commands in transactions at the data
source. The base class for all Transaction
objects is the DbTransaction class. ADO.NET
also provides support for transactions using
classes in the System.Transactions namespace. CommandBuilder A helper object t hat automatically generates
command properties of a DataAdapter or
derives parameter information from a stored
procedure and populates the Parameters
collection of a Command object. The base class
for all CommandBuilder objects is the
DbCommandBuilder clas s. ConnectionStringBuilder A helper object that provides a simple way to
create and manage the contents of connection
strings used by the Connection objects. The
base class for all ConnectionStringBuilder
objects is the DbConnectionStringBuilder
class. Parameter Defines input, output, and return value
parameters for commands and stored
procedures. The base class for all Parameter
objects is the DbParameter class. Exception Returned when an error is encountered at the
data source. For an error encountered at the
client, .NET Framework data providers throw a
.NET Framework exception. The base class for
all Exception objects is the DbException class. Error Exposes the informat ion from a warning or
error returned by a data source. ClientPermission Provided for .NET Framework data provider
code access security attributes. The base class
for all ClientPermission objects is the
DBDataPermission class. Table 4 Data Providers Classes NET Framework Data Provider for SQL Server (SqlClient) ● The .NET Framework Data Provider for SQL Server (SqlClient) uses its own protocol to communicate with SQL Server. munotes.in

Page 156


156 .Net technology ● It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. ● The following figure 3 shows the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. ● The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB provider for the data source. Figure 3 Comparison of the .NET Framework Data Provider for SQL Server and the .NET Framework Data Provider for OLE DB ● The .NET Framework Data Provider for SQL Server classes are located in the System.Data.SqlClient namespace. ● The .NET Framework Data Provider for SQL Server supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for SQL Server, by default, automatically enlists in a transaction and obtains transaction details from Windows Component Services or System.Transactions. For more information, see Transactions and Concurrency. The following code example 1 shows how to include the System.Data.SqlClient namespace in your applications. using System.Data.SqlClient; Example 1 System.Data.SqlClient .NET Framework Data Provider for OLE DB ● The .NET Framework Data Provider for OLE DB (OleDb) uses native OLE DB through COM interop to enable data access. ● The .NET Framework Data Provider for OLE DB supports both local and distributed transactions. ● For distributed transactions, the .NET Framework Data Provider for OLE DB, by default, automatically enlists in a transaction and obtains transaction details from Windows Component Services. For more information, see Transactions and Concurrency.
munotes.in

Page 157


157
ADO.Net The following Table 5 shows the providers that have been tested with ADO.NET. Driver Provider SQLOLEDB Microsoft OLE DB provider for SQL Server MSDAORA Microsoft OLE DB provider for Oracle Microsoft.Jet.OLEDB.4.0 OLE DB provider for Microsoft Jet Table 5 Data Provider for OLE DB .NET Framework Data Provider for ODBC ● The .NET Framework Data Provider for ODBC (Odbc) uses the native ODBC Driver Manager (DM) to enable data access. ● The ODBC data provider supports both local and distributed transactions. For distributed transactions, the ODBC data provider, by default, automatically enlists in a transaction and obtains transaction details from Windows Component Services. The following Table 6 shows the ODBC drivers tested with ADO.NET. Driver SQL Server Microsoft ODBC for Oracle Microsoft Access Driver (*.mdb) Table 6 ODBC Drivbers .NET Framework Data Provider for Oracle ● The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. ● The data provider supports Oracle client software version 8.1.7 or a later version. The data provider supports both local and distributed transactions. ● The .NET Framework Data Provider for Oracle requires Oracle client software (version 8.1.7 or a later version) on the system before you can connect to an Oracle data source. ● .NET Framework Data Providers for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You must reference both the System.Data.dll and the System.Data.OracleClient.dll when you compile an application that uses the data provider. The following code example 2 shows how to include the System.Data.OracleClient namespace in your applications. munotes.in

Page 158


158 .Net technology Example 2 System.Data.OracleClient using System.Data;
using System.Data.OracleClient; 11.4 CREATING A CONNECTION ● To connect to Microsoft SQL Server, use the SqlConnection object of the .NET Framework Data Provider for SQL Server. ● To connect to an OLE DB data source, use the OleDbConnection object of the .NET Framework Data Provider for OLE DB. ● To connect to an ODBC data source, use the OdbcConnection object of the .NET Framework Data Provider for ODBC. ● To connect to an Oracle data source, use the OracleConnection object of the .NET Framework Data Provider for Oracle. Choosing a .NET Framework Data Provider ● Depending on the design and data source for your application, .NET Framework data provider can improve the performance, capability, and integrity of your application. ● The following Table 7 discusses the advantages and limitations of each .NET Framework data provider. Table 7 .NET Framework data provider Provider Notes .NET Framework
Data Provider for
SQL Server Recommended for middle -tier applications that use
Microsoft SQL Server.
Recommended for single -tier applications that use
Microsoft Database Engine (MSDE) or SQL Server.
Recommended over use of the OLE DB provider for
SQL Server (SQLOLEDB) with the .NET Framework
Data Provider for OLE DB. .NET Framework
Data Provider for
OLE DB For SQL Server, the .NET Framework Data Provider
for SQL Server is recommended instead of this
provider.
Recommended for single -tier applications that use
Microsoft Access databases. Use of an Access
database for a middle -tier application is not
recommended. .NET Framework Recommended for middle and single -tier applications munotes.in

Page 159


159
ADO.Net Data Provider for
ODBC that use ODBC data sources. .NET Framework
Data Provider for
Oracle Recommended for middle and single -tier applications
that use Oracle data sources. 11.5 SELECT COMMAND The command object is one of the basic components of ADO .NET. 1. The Command Object uses the connection object to execute SQL queries. 2. The queries can be in the Form of Inline text, Stored Procedures or direct Table access. 3. An important feature of Command object is that it can be used to execute queries and Stored Procedures with Parameters. 4. If a select query is issued, the result set it returns is usually stored in either a DataSet or a DataReader object. The properties associated with the SqlCommand class are shown in the Table 8 below. Property Type of
Access Description Connection Read/Write The SqlConnection object that is used
by the command object to execute SQL
queries or Stored Procedure. CommandText Read/Write Represents the T -SQL Statement or the
name of the Stored Procedure. CommandType Read/Write This property indicates how the
CommandText property should be
interpreted. The possible values are:
1. Text (T -SQL Statement)
2. StoredProcedure (Stored Procedure
Name)
3. TableDirect CommandTimeout Read/Write This property indicates the time to wait
when executing a particular command.
Default Time for Execution of
Command is 30 Seconds.
The Command is aborted after it times
out and an exception is thrown. munotes.in

Page 160


160 .Net technology Table 8 Properties of SqlCommand class ● Various Execute Methods that can be called from a Command Object. Shown in the following Table 9. Property Description ExecuteNonQuery This method executes the command specified and
returns the number of rows affected. ExecuteReader The ExecuteReader method executes the command
specified and returns an instance of SqlDataReader
class. ExecuteScalar This method executes the command specified and
returns the first column of the first row of the result
set. The remaining rows and columns are ignored. ExecuteXMLReader This method executes the command specified and
returns an instance of XmlReader class. This
method can be used to return the result set in the
form of an XML document Table 9 Properties of execute methods ExecuteNonQuery 1. The ExecuteNonQuery method is used to execute the command and return the number of rows affected. 2. The ExecuteNonQuery method cannot be used to return the result set. (Shown in example 3) Example 3 public void CallExecuteNonQuery()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
ConfigurationManager.ConnectionStrings["connString"].ConnectionStrin
g;
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM EMP WHERE DEPTNO = munotes.in

Page 161


161
ADO.Net 40";
cmd.CommandType = CommandType.Text;
conn.Open();
Int32 RowsAffected = cmd.ExecuteNonQuery();
MessageBox.Show(RowsAffected + " rows affected", "Message");
cmd.Dispose();
conn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} 11.6 DATAREADER ● A data reader provides an easy way for the programmer to read data from a database as if it were coming from a stream. ● The DataReader is the solution for forward streaming data through ADO.NET. ● The data reader is also called a firehose cursor or forward read-only cursor because it moves forward through the data. ● The data reader not only allows you to move forward through each record of the database, but it also enables you to parse the data from each column. ● The DataReader class represents a data reader in ADO.NET. ● Similar to other ADO.NET objects, each data provider has a data reader class for example; OleDbDataReader is the data reader class for OleDb data providers. Similarly, SqlDataReader and ODBC DataReader are data reader classes for SQL and ODBC data providers, respectively. ● The IDataReader interface defines the function of a data reader and works as the base class for all data provider-specific data reader classes such as OleDataReader. SqlDataReader, and OdbcDataReader. Figure 4 shows some of the classes that implement IDbDataReader. munotes.in

Page 162


162 .Net technology
Figure 4. Data Provider-specific classes implementing IdbDataReader Initializing DataReader ● call the ExecuteReader method of the Command object, which returns an instance of the DataReader. ● For example 4, use the following line of code: Example 4: SqlCommand cmd = new SqlCommand(SQL, conn);
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.E xecuteReader();
Once you're done with the data reader, call the Close method to close a
data reader:
reader.Close(); DataReader Properties(Shown in Table 10) Property Description Depth Indicates the depth of nesting for row FieldCount Returns number of columns in a row IsClosed Indicates whether a data reader is closed Item Gets the value of a column in native format RecordsAffected Number of row affected after a transaction Table 10 DataReader Properties
munotes.in

Page 163


163
ADO.Net The DataReader methods (Shown in Table 11) Method Description Close Closes a DataRaeder object. Read Reads next record in the data reader. NextResult Advances the data reader to the next result during batch
transactions. Getxxx There are dozens of Getxxx methods. These methods
read a specific data type value from a column. For
example. GetChar will return a column value as a
character and GetString as a string. Table 11 DataReader methods Reading with the DataReader ● The OleDbDataReader is initialized, utilizing its various methods to read data records. ● Read method, which, when called repeatedly, continues to read each row of data into the DataReader object. ● The DataReader also provides a simple indexer that enables to pull each column of data from the row. Example 5: create a connection object, create a command object, called the ExecuteReader method, called the DataReader's Read method until the end of the data, and then display the data. At the last, released the data reader and connection objects. using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace CommandTyp eEnumeration
{
class Program
{
static void Main(string[] args)
{
// Create a connection string
string ConnectionString = "Integrated Security = SSPI; " +
"Initial Catalog= Northwin d; " + " Data source = localhost; ";
string SQL = "SELECT * FROM Customers"; munotes.in

Page 164


164 .Net technology
// create a connection object
SqlConnection conn = new SqlConnection(ConnectionString);

// Create a command object
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();

// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("customer ID, Contact Name, " + "Contact
Title, Address ");
Console.WriteLine("=============================");
while (reader.Read())
{
Console.Write(reader["CustomerID"].ToS tring() + ", ");
Console.Write(reader["ContactName"].ToString() + ", ");
Console.Write(reader["ContactTitle"].ToString() + ", ");
Console.WriteLine(reader["Address"].ToString() + ", ");
}

//Release resources
reader.Close();
conn.Close();
}
}
}

munotes.in

Page 165


165
ADO.Net 11.7 DISCONNECTED DATA ACCESS ● The ADO.NET Framework supports two models of Data Access Architecture, Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. ● The ADO.NET Disconnected Data Access Architecture is far more flexible and powerful than ADOs Connection Oriented Data Access. ● In Connection Oriented Data Access Architecture the application makes a connection to the Data Source and then interacts with it through SQL requests using the same connection. ● The application stays connected to the database system even when it is not using any Database Operations. ● The DataSet is the central component in the ADO.NET Disconnected Data Access Architecture. ● A DataSet is an in-memory data store that can hold multiple tables at the same time. DataSet ds = new DataSet(); 11.8 SUMMARY 1. ADO.NET consists of managed classes that allow .NET applications to connect to data sources (relational databases), execute commands, and manage disconnected data. 2. ADO.NET uses a multilayered architecture that revolves around a few key concepts, such as Connection, Command, and DataSet objects. 3. The .NET Framework Data Provider for SQL Server (SqlClient) uses its own protocol to communicate with SQL Server. 4. A data reader provides an easy way for the programmer to read data from a database as if it were coming from a stream. 5. The ADO.NET Framework supports two models of Data Access Architecture, Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. munotes.in

Page 166


166 .Net technology 11.9 REFERENCE FOR FURTHER READING 1. Beginning ASP.NET 4.5 in C#, Matthew MacDonald, Apress(2012) 2. The Complete Reference ASP .NET, MacDonald, Tata McGraw Hill 3. Beginning ASP.NET 4 in C# and VB Imar Spanajaars, WROX 11.10 UNIT END EXERCISES 1. What is ADO.NET? Explain the Data Provider Model? 2. Explain the ADO.NET Direct Data Access, with an example? 3. Write a short note on: a. Creating a Connection b. Select Command c. DataReader d. Disconnected Data Access  munotes.in

Page 167

167 12 DATA BINDING Unit Structure : 12.0 Objective 12.1 Introduction 12.2 Single-Value Data Binding, 12.3 Repeated-Value Data Binding, 12.4 Data Source Controls – SqlDataSource 12.5 Summary 12.6 Reference for further reading 12.7 Unit End Exercises 12.0 OBJECTIVE 1. To learn how data binding and the data source controls work. 2. To understand the single and repeated value data binding. 3. To study the SqlDataSource controls. 12.1 INTRODUCTION ● Data binding is an aspect that allows us to associate a data source with a control and have that control automatically display data. ● The main characteristic of data binding is that it’s declarative, not programmatic. That means data binding is defined outside program, alongside the controls in the .aspx page. ● The benefit is that it helps us achieve a cleaner separation between controls and program in a web page. ● In ASP.NET, most web controls (including TextBox, LinkButton, Image, and many more) support single-value data binding. With single-value binding, we can bind a control property to a data source, but the control can display only a single value. ● The property we bind doesn’t need to represent something directly visible on the page. ● For example, not only can we bind the text of a hyperlink by setting the Hyperlink.Text property, but we can also bind the NavigateUrl property to specify the target destination of the link. To use single-value binding, we create data binding expressions. munotes.in

Page 168


168 .Net technology ● Numerous web controls support repeated value binding, which means they can provide a set of items. ● Repeated value controls often create lists and grids (e.g. the ListBox and GridView are two examples). ● If a control supports repeated-value binding, it always uncovers a DataSource property, which accepts a data object. ● After setting the DataSource property, create the logical link from the server control to the data object that contains the data to render. ● The control’s DataBind() method, which loops through the data source, extracts its data, and provides it to the page. Repeated-value binding is by far the more poful type of data binding. 12.2 SINGLE-VALUE DATA BINDING ● The controls that support single-value data binding allow us to bind some of their properties to a data binding expression. ● This expression is entered in the .aspx markup portion of the page (not the program- behind file) and enclosed between the <%# and %> delimiters. Here’s an syntax: <%# expression_goes_here %> ● This looks like a script block, but it isn’t. While coding inside this tag, error will get The only thing we can add is valid data binding expressions. For example, if we have a public, protected, or internal variable in page class named EmployeeName, we could write the following: <%# EmployeeName %> ● To evaluate a data binding expression, you must call the Page.DataBind() method in program. ● While calling DataBind(), ASP.NET will examine all the expressions on page and replace them with the corresponding value. ● If we forget to call the DataBind() method, the data binding expression won’t be filled in instead, it just gets thrown away when page is rendered to HTML. ● The source for single-value data binding can include the value of a ○ property, ○ member variable, ○ return value of a function (as long as the property, member variable, or function has an accessibility of protected, public, or internal). munotes.in

Page 169


169
Data Binding ● It can also be any other expression that can be evaluated at runtime, such as a reference to another control’s property, a calculation using operators and literal values, and so on. ● The valid data binding expressions: <%# GetUserName() %> <%# 3 + (3 * 40) %> <%# "amit " + "raju" %> <%# Request.Browser.Browser %> ● Add data binding expressions just about anywhere on the page, then assign a data binding expression to a property in the control tag. ● Example 1 page that uses several data binding expressions:











NavigateUrl='<%# LogoPath.Value %>' Font-Bold="True" Text="Show
logo" />



<%# FilePath %>




Example 1 Data binding expressions ● We bind the Text property of a Label and a TextBox & use other properties such as the ImageUrl of an Image, the NavigateUrl property of a HyperLink, and the src attribute of a static HTML tag. ● After we put the binding expression elsewhere in the page without binding to any property or attribute. For example, the previous web page has a binding expression between the and tags. munotes.in

Page 170


170 .Net technology ● While it’s executing, the resulting text will be rendered on the page and rendered in bold type. Then place the expression outside the

section, as long as you don't try to insert a server-side control on a page. ● The expressions in this sample page refer to a FilePath property, a GetFilePath() function, and the Value property of a server-side hidden field that’s declared on the same page. To complete this page, need to define these ingredients in script blocks or in the program-behind class: (Shown in Example 2) protected string GetFilePath()
{
return "rose.gi f";
}
protected string FilePath
{
get { return "rose.gif"; }
} Example 2 FilePath property In this program, the property and function return only a hard-program string. However, we can also add just about any C# program to generate the value for the data binding expression dynamically. 12.3 REPEATED-VALUE DATA BINDING, ● Repeated-value binding allows to bind an entire list of information to a control. This list of information is represented by a data object that wraps a collection of items. This could be a collection of convention objects (e.g., an ordinary ArrayList or Hashtable) or a collection of rows (for e.g., with a DataReader or DataSet). ASP.NET includes several basic list controls that support repeated-value binding: ○ All controls that render themselves using the runat="server" onclick="ClearErr orState()" />





Globalizing the Date and Time That Are Displayed in the Browser ● The following example 5 shows how to set the EnableScriptGlobalization property so that the client script can display a culture-specific date and time in the browser. ● In the code, the Culture attribute of the @ Page directive is set to auto. As a result, the first language that is specified in the current browser settings determines the culture and UI culture for the page. Example 5: <%@ Page Language="C#" Culture="auto" %>
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


Globalization Example munotes.in

Page 242


242 .Net technology


EnableScriptGlobalization="true" runat="server">


ChildrenAsTriggers="False" UpdateMode="Conditional">











17.3 PARTIAL REFRESHES ● Perhaps the most visible feature of the ASP.NET AJAX Extensions is the ability to do a partial or incremental page update without doing a full postback to the server, with no code changes and minimal markup changes. ● The advantages are extensive: the state of your multimedia (such as Adobe Flash or Windows Media) is unchanged, bandwidth costs are munotes.in

Page 243


243
ASP.NET AJAX reduced, and the client does not experience the flicker usually associated with a postback. ● The ability to integrate partial page rendering is integrated into ASP.NET with minimum changes into your project. ● One of the most fascinating controls in the ASP.NET AJAX framework is the UpdatePanel. This new control replaces the need for a page to refresh during a postback. Only portions of a page, designated by the UpdatePanel, are updated. ● This technique is known as partial-page rendering and can be highly effective in improving the user experience. 17.4 PROGRESS NOTIFICATION 1. Showing a Simulated Progress Bar • When adding the UpdateProgress control to a page, we get the ability to specify some content that will appear as soon as an asynchronous request is started and disappear as soon as the request is finished. ● This content can include a fixed message, but many people prefer to use an animated GIF, because it more clearly suggests that the page is still at work. ● The top figure shows the page as it first appears, with a straightforward UpdatePanel control containing a button. When the button is clicked, the asynchronous callback process begins. At this point, the contents of the UpdateProgress control appear underneath. ● The markup for this page defines an UpdatePanel followed by an UpdateProgress example 6 shown below: Example 6:


Bold="True">



Text="Start the Refresh Proc ess" />




munotes.in

Page 244


244 .Net technology


Contacting Server ... Waiting...


● Depending on the layout we want, we can place our UpdateProgress control somewhere inside our UpdatePanel control. ● The UpdateProgress control only shows its content while the asynchronous callback is under way, it only makes sense to use it with an operation that takes time. Otherwise, the UpdateProgress will only show its ProgressTemplate for a few fractions of a second. ● To simulate a slow process, add a line to delay your code 10 seconds, as example 7 shown below: Example 7: Protected Sub cmdRefreshTime_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles cmdRefreshTime.Click

System.Threading.Thread.Sleep(TimeSpan.FromS econds(10))
lblTime.Text = DateTime.Now.ToLongTimeString()
End Sub 2. Cancellation ● The UpdateProgress control supports one other detail: a cancel button. When the user clicks a cancel button, the asynchronous callback will be cancelled immediately, the UpdateProgress content will disappear, and the page will revert to its original state. ● Adding a cancel button is a two-step process. First you need to add a fairly intimidating block of JavaScript code, which you can copy verbatim. You should place this code at the end of your page, after all your content but just before the end tag. Here’s the example 8 shows the need, in its rightful place: Example 8: <%@ Page Language="VB" AutoEventWireup="false"
CodeFile="WaitIndicator.aspx.vb"
Inherits="WaitIndicator" %>
munotes.in

Page 245


245
ASP.NET AJAX
...



...



● Once you’ve added this code, you can use JavaScript code to call its AbortPostBack() function at any time and cancel the callback. ● The easiest way to do this is to connect a JavaScript event to the AbortPostBack() function using a JavaScript event attribute. Add a JavaScript event attribute to virtually any HTML element. For example, you can deal with client-side clicks using the onclick attribute. Here’s a basic HTML button that uses this technique to connect itself to the AbortPostBack() function: ● If you click this Cancel button, the client-side AbortPostBack() function will be triggered and the callback will be cancelled immediately. Typically, this button in the ProgressTemplate of the UpdateProgress control, as shown in Figure 1. munotes.in

Page 246


246 .Net technology
Figure 1 ProgressTemplate 17.5 TIMED REFRESHES ● ASP.NET AJAX includes a Timer control that can help you implement a page that includes a stock ticker, and want to refresh this ticker periodically (say, every 5 minutes) to ensure it doesn’t become drastically outdated. ● The Timer control is refreshingly straightforward. You simply add it to a page and set its Interval property to the maximum number of milliseconds that should elapse before an update. ● For example 9 & 10, if you set Interval to 60000, the timer will force a postback after one minute elapses. ● If the Timer is in an UpdatePanel, it will trigger an asynchronous postback. If it’s not, and it’s not linked to an UpdatePanel with a trigger, the Timer will trigger an ordinary full-page postback. ● The timer raises a server-side Tick event, which you can handle to update your page. ● The timer is particularly well suited to pages that use partial rendering. That's because a refresh in a partially rendered page might just need to change a single portion of the page. ● To use the timer with partial rendering, wrap the updateable portions of the page in UpdatePanel controls with the UpdateMode set to Conditional, and add a trigger that forces an update whenever the timer fires:
munotes.in

Page 247


247
ASP.NET AJAX Example 9: UpdateMode="Conditional">

...





OnTick="Timer1_Tick" /> ● To stop the timer, simply need to set the Enabled property to false in server-side code. For example, following code show how to disable the timer after ten updates: Example 10: protected void Timer1_Tick(object sender, EventArgs e)
{
// Update the tick count and store it in view state.
int tickCo unt = 0;
if (ViewState["TickCount"] != null)
{
tickCount = (int)ViewState["TickCount"];
}
tickCount++;
ViewState["TickCount"] = tickCount;
// Decide whether to disable the timer.
if (tickCount > 10)
{
Timer1.Enabled = false;
}
} munotes.in

Page 248


248 .Net technology 17.6 SUMMARY ● The most exciting feature of ASP.NET AJAX is that it isn’t just another JavaScript library or a simple .NET component that simplifies callbacks. ● You can write your own JavaScript code that calls server-side functionality. ● We can keep using ordinary ASP.NET server controls but extend them with ASP.NET AJAX-fortified ingredients such as the UpdatePanel, or use the snazzy controls and control extenders that are included with the ASP.NET AJAX Control Toolkit. ● We can create your own client-side components, controls, and behaviors, and use them independently or in conjunction with a custom ASP.NET server control. 17.7 REFERENCE FOR FURTHER READING 1. Beginning ASP.NET 4.5 in C#, Matthew MacDonald, Apress(2012) 2. The Complete Reference ASP .NET, MacDonald, Tata McGraw Hill 3. Beginning ASP.NET 4 in C# and VB Imar Spanajaars, WROX 17.8 UNIT END EXERCISES 1. What is the use of ScriptManager in ASP.NET AJAX? 2. Explain the Partial Refreshes with an example. 3. Explain Progress Notification with the help of an example? 4. Write a short note on Timed Refreshes?  munotes.in