shylaja

Embed Size (px)

Citation preview

.1 Features of Object -Oriented approach...............................................................2 .2 Phases of Object -Oriented approach.................................................................4 .3 C# Data Types TOP ............................................................................................................................4 .4 Operators .5 Decision-Making Constructs and Loop Constructs .6 Events and Delegates .7 Stream class to implement File handling .8 Collections .9 Threading .10 Serialization: .11 Exception handling .13 Introduction to .NET Framework TOP ................6

.......................................8 TOP ........................14 ..............................16 TOP ......................19 ................................21 TOP ......................23 TOP ......................24 TOP ..............................28 ......................31

WEBPAGES ..............................................................................................31 Directives..............................................................................................................................32 .12 Creating a Website ..........................34 ..................................................................39 .13 Hierarchy of .config files TOP .......................39

.14 Configuring Server Controls............................................................................42 .15 Creating Master pages to establish a common layout for a web application ...........................................................................................................................55 .16 Constructing Web Application using Web Parts .17 Site Navigation .18 ASP.NET State Management & Security TOP .....................64

TOP .......................66 TOP ............................68

.19 Windows Forms & Controls............................................................................77 .20 Crystal Report .21 Components .22 Asynchronous Programming .23 Web Services ..............................79 TOP .....................83 ..............................85 ..................................88

1

.24 WCF (Windows Communication Foundation) .25 Remote Client and Server Application .26 Message Queuing .27 Message Queuing in Client and Server applications .28 Web Services Enhancement (WSE) .29 LINQ (Language-Integrated Query)

TOP ..........................95 TOP ......................100 TOP ....................105 TOP .......................106 TOP ......................108 TOP .......................111

.30 XML.............................................................................................................118 .31 XML Schema TOP .........................................................................................................................120 .32 XSLT (Extensible Style sheet Language Transformations) TOP .33 Books .34 XPath Patterns .35 XML Reader .36 XML Writer .37 DOM API for XML .38 ADO.NET .39 Connected and Disconnected Architecture .40 Store and Retrieve Binary Data using ADO.NET .41 Performing Bulk Copy Operations in ADO.NET .42 Manage Distributed Transactions .43 Caching ....................122

TOP......................123 ...............................126 TOP ......................127 TOP .......................129 TOP .......................131 TOP ......................139 TOP .....................147 TOP.........................148 TOP ..........................154 TOP .....................157 TOP ....................159

TOP

Chapter IObject-oriented Programming using C Sharp

.1 Features of Object -Oriented approachClasses and Object

A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would

2

be the variable. Class is the general thing and object is the specialization of general thing. For example if Human can be a class and linto, raj etc are names of persons which can be considered as object.Encapsulation Encapsulation is one of the fundamental principles of object-oriented programming. It is a process of hiding all the internal details of an object from the outside world. Encapsulation is the ability to hide its data and methods from outside the world and only expose data and methods that are required.

Example:Chair has some length, breath and height state and we can sit on chair, chair legs can be break, u can move it are the examples of behavior. State and behavior are encapsulated inside Object , that is called EncapsulationAbstraction Abstraction is the representation of only the essential features of an object and hiding unessential features of an object. Through Abstraction all relevant data can be hide in order to reduce complexity and increase efficiency. It is simplifying complex reality by modeling classes appropriate to the problem .

Example:People own savings accounts, checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case, a bank account can be an abstract class and all the other specialized bank accounts inherit from bank account.Difference between Encapsulation and Abstraction 1. Abstraction solves the problem in the design 1. Encapsulation solves the problem in the level implementation level 2. Abstraction is used for hiding the unwanted data and giving relevant data 2. Encapsulation means hiding the code and data in to a single unit to protect the data from outside world

3. Abstraction is a technique that helps to 3. Encapsulation is the technique for packaging the identify which specific information should be information in such a way as to hide what should be visible and which information should be hidden. hidden, and make visible what is intended to be visible.

PolymorphismExample:Car is a Polymorphism because it have different speed as display in same speedometer.

Inheritance Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes The Class whose methods and variables are defined is called super class or base class The Class that inherits methods and variables are defined is called sub class or derived class Sometimes base class known as generalized class and derived class known as specialized class .Keyword to declare inheritance is ":" (colon) in visual C#.

Human | ____|_____ || 3

// Men Women Here Human is general class and Men and Women are sub classes of general thing. That is Human class contains all features general and Man and Women contains features specific to their own class.TOP

.2 Phases of Object -Oriented approachSpecification: During this stage a rough idea of the subsystem and the service it will provide is proposed. Exploratory Design: During this stage key objects and their interactions are identified. Each key class role and responsiblities are described.The additional layer of each subsystem design can be elaborated. Detailed Modeling: In this section extensive review of the initial model is done.New supporting class can be created.Permissible patterns of collabration between objects can be formalized through contact that spell out services used by specific clients.Class inheritance hierarchy can be developed. Implementation Phase: Actual coding and building of system. Integration: Crucial point in any large applications comes when subsystems developed in relative isolation are made to work together. It is at this stage that hidden assumptions about sertvices provided and or expected patterns of usage are uncovered. Validation: It is necessary to validate behaviour of individual components and the overall behaviour of major subsystem in the actual working eviroment. Clean Up: A relatively minor sweep through the classes and working code can often provide dramatic improvements in performance, code clarity and robustness.

.3 C# Data TypesTOP

Primitive Data Type

sbyte: Holds 8-bit signed integers. The s in sbyte stands for signed, meaning that the variable's value can be either positive or negative. . byte: Holds 8-bit unsigned integers. Unlike sbyte variables, byte variables are not signed and 4

can only hold positive numbers. short: Holds 16-bit signed integers. The smallest possible value for a short variable is -32,768; the largest possible value is 32,767. ushort: Holds 16-bit unsigned integers. The u in ushort stands for unsigned. The smallest possible value of an ushort variable is 0; uint: Holds 32-bit unsigned integers. The u in uint stands for unsigned. The smallest possible value of a uint variable is 0; long: Holds 64-bit signed integers. The smallest possible value of a long variable is 9,223,372,036,854,775,808; ulong: Holds 64-bit unsigned integers. The u in ulong stands for unsigned. The smallest possible value of a ulong variable is 0; char: Holds 16-bit Unicode characters. The smallest possible value of a char variable is the Unicode character whose value is 0; float: Holds a 32-bit signed floating-point value. The smallest possible value of a float type is approximately 1.5 times 10 to the 45th power; double: Holds a 64-bit signed floating-point value. The smallest possible value of a double is approximately 5 times 10 to the 324th; decimal: Holds a 128-bit signed floating-point value. Variables of type decimal are good for financial calculations. bool : Holds one of two possible values, true or false. Secondary Data TypeStructure Struct describes a value type in the C# language. Structs can improve speed and memory usage. They cannot be used the same as classes. Collections of structs are allocated together. struct Simple { public int Position; public bool Exists; public double LastValue; }; Difference between Structures and Class

You cannot have instance Field initializers in structs. But classes can have. Classes can have explicit parameterless constructors. But structs cannot have explicitparameterless constructors. Enumerations The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example:

5

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; In this enumeration, the sequence of elements is forced to start from 1 instead of 0. A variable of type Days can be assigned any value in the range of the underlying type; the values are not limited to the named constants. The default value of an enum E is the value produced by the expression (E)0.

Arrays In C#, an array index starts at zero. That means the first item of an array starts at the 0 th position. The position of the last item on an array will total number of items - 1. So if an array has 10 items, the last 10 th item is at 9thposition. In C#, arrays can be declared as fixed length or dynamic. A fixed length array can store a predefined number of items. A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined. The following code snippet defines the simplest dynamic array of integer types that does not have a fixed size int[] intArray; As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket ([]) and name of the array. The following code snippet declares an array that can store 5 items only starting from index 0 to 4[Fixed Array]. int[] intArray; intArray = new int[5];

.4 OperatorsTOP

Arithmetic Operator

They used to perform the general arithmetic operations. Operator + * / % Addition Subtraction Multiplication Division Gets the remainder left after integer division Description

6

Unary Operators The unary operators forms expression on a single variable.

Operator ++x --y x++ y-~ Pre_Increment Pre_Decrement Post_Increment Post_Decrement Works by flipping bits

Description

Assignment Operator The assignment operators assign a new value to a variable, a property, an event, or an indexer element.

Operator = *= /= %= += -= = &= ^= |= Basic assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator Compound assignment operator

Description

Comparison Operator The set of relational operators referred to as comparison operators.

Operator

Description

7

< >= == !=

less than operator less than or equal to operator grater than operator grater than or equal to perator equal to operator not equal to operator

Logical operators Based on the value of the variable they are used to make the decision on which loop to pass through.

Operator & | ^ || && ! And OR XOR Short-circuit OR Short-circuit AND NOT

Description

.5 Decision-Making Constructs and Loop ConstructsDecision-Making Constructs TOP

It decides which action to be taken based on user input and external condition. The IF Block The if block is the powerhouse of conditional logic, able to evaluate any combination of conditions and deal with multiple and different pieces of data.

Lets see this with an example: static void Main(string[] args)

8

{ int x1 = 50; int x2 = 100; if(x1>x2) { Console.WriteLine("X1 is greater"); } else { Console.WriteLine("X2 is greater"); } } OUTPUT X2 is greater The switch block The switch statement selects for execution a statement list having an associated switch label that corresponds to the value of the switch expression. int caseSwitch = 1; switch (caseSwitch) { case 1: Console.WriteLine("Case 1"); break; case 2: Console.WriteLine("Case 2"); break;

default:

Console.WriteLine("Default case");

9

break; }

OUTPUT Case 1 Loop Constructs The while loop The while loop is probably the most simple one, so we will start with that. The while loop simply executes a block of code as long as the condition you give it is true. Lets see this with an example. static void Main(string[] args) { int number = 0; while (number < 5) { Console.WriteLine(number); number = number + 1; } Console.ReadLine(); } OUTPUT 0 1 2 3 4

The do loop The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once. Lets see this with an example.

10

int number = 0; do { Console.WriteLine(number); number = number + 1; } while (number < 4); OUTPUT 0 1 2 3 The for loop The for loop is preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount. Here is an example on the for loop. int number = 5; for (int i = 0; i < number; i++) Console.WriteLine(i); Console.ReadLine(); OUTPUT 0 1 2 3 4 The foreach loop The foreach loop operates on collections of items, for instance arrays or other built-in list types. In our example we will use one of the simple lists, called an ArrayList. using System.Collections; ArrayList list = new ArrayList(); list. Add("John Doe"); list. Add("Jane Doe");

11

list. Add("Someone Else"); foreach (string name in list) Console.WriteLine(name); Console.ReadLine(); OUTPUT John Doe Jane Doe Someone Else

A sample C# programSelect File->New->Project. From the dialog box select Visual C# and then click on Console Application. With the help of Browse button choose the required location and click OK. Type the below given code in the code file. The console application will have the extension .cs . using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public class first

{ static void Main(string[] args) {

Console.WriteLine("Welcome"); } } } Compile the above program using Debug option

12

Output: Welcome

Descreption of the program:NameSpace Namespaces allow you to create a system to organize your code. A good way to organize your namespaces is via a hierarchical system. You put the more general names at the top of the hierarchy and get more specific as you go down. This hierarchical system can be represented by nested namespaces. Example : using System Console.ReadLine

You want to read user input from the console in your C# program in the simplest way possible. The Console.ReadLine method in the System namespace in the .NET Framework allows you to read a string of characters.Console.WriteLine

You are writing a console program using the C# language and want to write text or data to the screen. This is best done with Console.WriteLine

Interfaces:Interfaces in C# are provided as a replacement of multiple inheritance. Because C# does not support multiple inheritance, it was necessary to incorporate some other method so that the class can inherit the behavior of more than one class.using System; namespace ConsoleApplication1 {

public class Mammal { protected string Characteristis; public string characteristics { get { return this.Characteristis; } set { this.Characteristis=value; } } } interface IIntelligence { /// Interface method declaration bool intelligent_behavior(); }

13

class Human: Mammal, IIntelligence { public Human() { characteristics = "Human are mammals"; } ///Interface method definition in the class that implements it public bool intelligent_behavior() { Console.WriteLine("{0} and have intelligence",characteristics) return true } } class Whale: Mammal { public Whale() { characteristics = "Whale are mammals"; Console.WriteLine("{0}",characteristics); } } class InterfaceApp { public static void Main(string[] args) { Whale whale = new Whale(); Human human = new Human(); /// The human object is casted to the interface type IIntelligence humanIQ = (IIntelligence)human; humanIQ.intelligent_behavior(); Console.Read(); } } }

Output:Whale are mammal Human are mammals and have intelligence

Difference between abstraction and interfaces: An abstract class is a class that can not be instantiated but that can contain code. An interface only contains method definitions but does not contain any code. With aninterface, you need to implement all the methods defined in the interface.

.6 Events and DelegatesTOP

An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver. A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. A delegate declaration is sufficient to define a delegate class. The

14

declaration supplies the signature of the delegate, and the common language runtime provides the implementation. The following example shows an event delegate declaration. Delegates: Example: // Declaration public delegate void SimpleDelegate(); class Program { public static void MyFunc() { Console.WriteLine("I was called by delegate ..."); } static void Main(string[] args) { // Instantiation SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

// Invocation simpleDelegate(); } } OUTPUT: I was called by delegate ... Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. Events: namespace ConsoleApplication2 { public delegate void MyDelegate(); // delegate declaration public interface I { event MyDelegate MyEvent; void FireAway(); } public class MyClass : I { public event MyDelegate MyEvent; public void FireAway()

15

{ if (MyEvent != null) MyEvent(); } }

public class MainClass { static private void f() { Console.WriteLine("This is called when the event fires."); } static public void Main() { I i = new MyClass(); i.MyEvent += new MyDelegate(f); i.FireAway(); } } } OUTPUT: This is called when the event fires.

.7 Stream class to implement File handlingTOP

StreamWriter Class The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters. The following table describes some of the methods used by StreamWriter class.

Methods

Description

16

Close Flush Write WriteLine

Closes the current StreamWriter object and the underlying stream Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream Writes to the stream Writes data specified by the overloaded parameters, followed by end of line

Program to write user input to a file using StreamWriter Class using System; using System.Text; using System.IO; namespace FileWriting_SW { class Program { class FileWrite { public void WriteData() { FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); Console.WriteLine("Enter the text which you want to write to the file"); string str = Console.ReadLine(); sw.WriteLine(str); sw.Flush(); sw.Close(); fs.Close(); }

} static void Main(string[] args) { FileWrite wr = new FileWrite(); wr.WriteData(); } } } OUTPUT

17

Enter the text which you want to write to the file Press Enter The text will be replaced in the document StreamReader Class The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters. The following table describes some methods of the StreamReader class.

Methods Close Peek Read ReadLine Seek

Description Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader Returns the next available character but doesn't consume it Reads the next character or the next set of characters from the stream Reads a line of characters from the current stream and returns data as a string Allows the read/write position to be moved to any position with the file

Program to read from a file using StreamReader Class using System; using System.IO; namespace FileReading_SR {

class Program { class FileRead { public void ReadData() { FileStream fs = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs); Console.WriteLine("Program to show content of test file"); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); }

18

Console.ReadLine(); sr.Close(); fs.Close(); } } static void Main(string[] args) { FileRead wr = new FileRead(); wr.ReadData(); } } }

OUTPUT Program to show content of test file

.8 CollectionsTOP

The .NET Framework has powerful support for Collections. Collections are enumerable data structures that can be assessed using indexes or keys. The System.Collections namespace The System.Collections namespace provides a lot of classes, methods and properties to interact with the varying data structures that are supported by it. Let us see the few examples of Collections. ArrayList The ArrayList class is a dynamic array of heterogeneous objects. Note that in an array we can store only objects of the same type. In an ArrayList, however, we can have different type of objects; these in turn would be stored as object type only. We can have an ArrayList object that stores integer, float, string, etc., but all these objects would only be stored as object typeusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Array_list { class Program { static void Main(string[] args) { int i = 100;

19

double d = 20.5; ArrayList arrayList = new ArrayList(); arrayList.Add("Joydip"); arrayList.Add(i); arrayList.Add(d);

for (int index = 0; index < arrayList.Count; index++) Console.WriteLine(arrayList[index]); Console.ReadLine(); } } }

OutputJoydip 100 20.5

StringCollection The StringCollection class implements the IList interface and is like an ArrayList of strings. The following code example shows how we can work with a StringCollection class.using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Collections.Specialized; namespace Array_list { class Program { static void Main(string[] args) { StringCollection stringList = new StringCollection(); stringList.Add("Manashi"); stringList.Add("Joydip"); stringList.Add("Jini");

stringList.Add("Piku"); foreach (string str in stringList)

20

{ Console.WriteLine(str); } Console.ReadLine(); } } }

Output:

Manashi Joydip Jini Piku

.9 ThreadingOverview Multithreading or free-threading is the ability of an operating system to concurrently run programs that have been divided into subcomponents, or threads. Technically, multithreaded programming requires a multitasking/multithreading operating system, such as GNU/Linux, Windows NT/2000 or OS/2; capable of running many programs concurrently, and of course, programs have to be written in a special way in order to take advantage of these multitasking operating systems which appear to function as multiple processors. In reality, the user's sense of time is much slower than the processing speed of a computer, and multitasking appears to be simultaneous, even though only one task at a time can use a computer processing cycle. Features and Benefits of Threads Mutually exclusive tasks, such as gathering user input and background processing can be managed with the use of threads. Threads can also be used as a convenient way to structure a program that performs several similar or identical tasks concurrently. One of the advantages of using the threads is that you can have multiple activities happening simultaneously. Another advantage is that a developer can make use of threads to achieve faster computations by doing two different computations in two threads instead of serially one after the other.

Threading Concepts in C#In .NET, threads run in AppDomains. An AppDomain is a runtime representation of a logical process within a physical process. And a thread is the basic unit to which the OS allocates processor time. To start with, each AppDomain is started with a single thread. But it is capable of creating other threads from the single thread and from any created thread as well. How do they work A multitasking operation system divides the available processor time among the processes and threads that need it. A thread is executed in the given time slice, and then it is suspended and execution starts for next thread/process in the queue. When the OS switches from one thread to another, it saves thread context for preempted thread and loads the thread context for the thread to execute. The length of time slice that is allocated for a thread depends on the OS, the processor, as also on the priority of the task itself.

21

Working with threads In .NET framework, System.Threading namespace provides classes and interfaces that enable multi-threaded programming. This namespace provides: ThreadPool class for managing group of threads, Timer class to enable calling of delegates after a certain amount of time, A Mutex class for synchronizing mutually exclusive threads, along with classes for scheduling the threads, Information on this namespace is available in the help documentations in the Framework SDKusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Threading { class Program { public void InstanceMethod() {

Console.WriteLine("You are in InstranceMethod.Running on Thread A"); Console.WriteLine("Thread A Going to Sleep Zzzzzzzz"); // Pause for a moment to provide a delay to make threads more apparent.

Thread. Sleep(3000); Console.WriteLine ("You are Back in InstanceMethod.Running on Thread A"); } public static void Main(string[] args) { Console.WriteLine("You are in StaticMethod. Running on Thread B."); // Pause for a moment to provide a delay to make threads more apparent. Console.WriteLine("Thread B Going to Sleep Zzzzzzzz"); Thread.Sleep(5000); Console.WriteLine("You are back in static method. Running on Thread B"); Console.ReadLine(); } } }

OutPut: You are in StaticMethod. Running on Thread B Thread B Going to Sleep Zzzzzzzz

22

You are back in static method. Running on Thread B

.10 Serialization:TOP

Many application need to store or transfer objects. To make these tasks as simple as possible, the .net framework includes serialization techniques. Serialization is a process where an object is converted to a form able to be stored or transported to a different place. Such purpose can be if we want to save our object's data to a hard drive for example. Even more useful is its appliance when we want to send our object over some kind of network. Without serialization the remoting will be impossible.using System; namespace SufyanTestClass { // We are creating a simple class named SerialFor and to make // that class serializable we added an attribute [Serializable]. // This attribute makes the class ready for Serialization [Serializable] public class SerialFor { /* [NonSerialized] attribute is used to make a method * non-Serializable in a serializable envoironment. The * condition is that Sufyan wants to make the property uname * and uid non-serializable. While the remaining class remains serialized */ [NonSerialized] public string uname; [NonSerialized] public int uid; public string ename; public int esal; public int calcHRA(int a, int b) { return (a - b); }

public int CalcPF(int a, int b) { return (b - a); }

23

public int Deductions; public int NetSal; } }

.11TOP

Exception handling

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

The finally block is used to do all the clean up code. It does not support the error message, but all the code contained in the finally block is executed after the exception is raised. We can use this block along with try...catch and only with catch too. The finally block is executed even if the error is raised. Control is always passed to the finally block regardless of how the try blocks exits.If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. The throw statement throws an exception. A throw statement with an expression throws the exception produced by evaluating the expression. A throw statement with no expression is used in the catch block. It re-throws the exception that is currently being handled by the using System;using System.Collections.Generic; using System.Linq;

using System.Text; namespace exception_handling { class Program { static void Main(string[] args) { int x = 0; int div = 0;

24

try { div = 100/x; Console.WriteLine("Not executed line"); } catch(DivideByZeroException de) { Console.WriteLine("Exception occured"); } finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is {0}", div); Console.ReadLine(); } } } Output: Exception occurred Finally Block Result is {0}

Chapter II A.S.P .NET

TOP

ASP.NET is a part of the Microsoft .NET framework, and a powerful tool for creating dynamic and interactive web pages. ASP stands for Active Server Pages. It is a Microsoft server-side Web technology. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Run time (CLR), allowing programmers to write ASP.NET code using any supported .NET Language.

ASP.NET takes an object-oriented programming approach to Web page execution. Every element in 25

an ASP.NET page is treated as an object and run on the server. An ASP.NET page gets compiled into an intermediate language by a .NET Common Language Run time compiler. Then a JIT compiler turns the intermediate code to native machine code, and that machine code is eventually run on the processor. Because the code is run straight from the processor, pages load much faster than classic ASP pages, where embedded VBScript or JScript had to be continuously interpreted and cached. ASP.NET is used to create Web pages and Web services and is an integral part of Microsoft's .NET vision. Asp.Net enables you to access information from data sources such as back-end databases and textfiles that are stored on a web server or a computer that is accessible to a web server.Asp.Net enables you to separate HTML design from the data retrieval mechanism. As a result, changing the HTML design does not affect the programs that retrieve data from the database.

Some Important Features Better language support ASP.NET uses ADO.NET. ASP.NET supports full Visual Basic, not VBScript. ASP.NET supports C# (C sharp) and C++. ASP.NET supports JScript. Programmable controls ASP.NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP.NET control objects that can be controlled by scripts. ASP.NET also contains a new set of object-oriented input controls, like programmable list-boxes and validation controls. A new data grid control supports sorting, data paging, and everything you can expect from a dataset control. Event-driven programming All ASP.NET objects on a Web page can expose events that can be processed by ASP.NET code. Load, Click and Change events handled by code makes coding much simpler and much better organized. XML-based components ASP.NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store advertisement information and configuration. User authentication, with accounts and roles ASP.NET supports form-based user authentication, cookie management, and automatic redirecting of unauthorized logins. ASP.NET allows user accounts and roles, to give each user (with a given role) access to different server code and executables. Higher scalability 26

Much has been done with ASP.NET to provide greater scalability. Server-toserver communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers. Increased performance - Compiled code The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory. The result of this is greatly increased performance. Easier configuration and deployment Configuration of ASP.NET is done with plain text files. Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more metabase or registry puzzle. Not fully ASP compatible ASP.NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP.NET.To overcome this problem, ASP.NET uses a new file extension ".aspx". This will make ASP.NET applications able to run side by side with standard ASP applications on the same server.

.12 System RequirementsHardware Requirements The following Operating System are recommended to use .net 3.5 Microsoft Windows Server 2003 Windows Server 2008 Windows Vista Windows XP

1GB of system memoryA hard disk with at least 700MB of available space

Software Requirements

A Web Browser such as Microsoft Internet Explorer version 6 or later

27

Visual studio2008The Web Server's and Web Browser's Role The Web server is responsible for accepting request for a resource and sending the appropriate response.

The web browser is responsible for displaying data to the user, collecting data from the user and sending data to the web server. HTTP is a text-based communication protocol that is used to communicate between web browsers and web servers using port 80.

Secure HTTP (HTTPS) uses port 443.

Each HTTP command contains a method that indicates the desired action. Common methods are GET and POST.

Sending data to the web server from the browser is commonly referred to as a post-back inASP.NET programming

.13TOP

Introduction to .NET Framework

The .NET Framework is the infrastructure for the Microsoft .NET platform. The .NET Framework is an environment for building, deploying, and running Web applications and Web Services. Microsoft's first server technology ASP (Active Server Pages), was a powerful and flexible "programming language". But it was too code oriented. It was not an application framework and not an enterprise development tool. The Microsoft .NET Framework was developed to solve this problem. .NET Frameworks keywords: Easier and quicker programming Reduced amount of code Declarative programming model Richer server control hierarchy with events Larger class library Better support for development tools The .NET Framework consists of 3 main parts: Programming languages: C# (Pronounced C sharp) Visual Basic (VB .NET) J# (Pronounced J sharp) 28

Server technologies and client technologies: ASP .NET (Active Server Pages) Windows Forms (Windows desktop solutions) Compact Framework (PDA / Mobile solutions) Development environments: Visual Studio .NET (VS .NET) Visual Web DeveloperThe .NET Framework is a software framework for Microsoft Windows operating systems. It includes a large library, and it supports several programming languages which allow language interoperability (each language can use code written in other languages). The .NET library is available to all the programming languages that .NET supports.

Base Class LibraryThe Basic Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions, including file reading and writing, graphic rendering, database interaction, XML document manipulation and so on. The class library is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services. The framework's Base Class Library provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. The class library is used by programmers, who combine it with their code to produce applications. Programs written for the .NET Framework execute in a software (as contrasted to hardware) environment, known as the Common Language Run time (CLR). The CLR is an application virtual machine so that programmers need not consider the capabilities of the specific CPU that will execute the program. The CLR also provides other important services such as security, memory management, and exception handling. The class library and the CLR together constitute the .NET Framework.

29

Common Runtime Engine (CLR)The Common Language Run time (CLR) is the execution engine of the .NET Framework. All .NET programs execute under the supervision of the CLR, guaranteeing certain properties and behaviors in the areas of memory management, security, and exception handling.

MSIL (Microsoft Intermediate Language) CodeWhen we compile our .Net Program using any .Net compliant language like (C#, VB.NET, C+ +.NET) it does not get converted into the executable binary code but to an intermediate code, called MSIL or IL in short, understandable by CLR. MSIL is an OS and H/w independent code. When the program needs to be executed, this MSIL or intermediate code is converted to binary executable code, called native code. The presence of IL makes it possible the Cross Language Relationship as all the .Net compliant languages produce the similar standard IL code.

Just In Time Compilers (JIT)When our IL compiled code needs to be executed, CLR invokes JIT compilers which compile the IL code to native executable code (.exe or .dll) for the specific machine and OS.

CTSCommon Type System (CTS) describes how types are declared, used and managed. CTS facilitates Cross-language integration, type safety, and high performance code execution.

CLSThe CLS is a specification that defines the rules to support language integration. This is done in such a way, that programs written in any language (.NET compliant) can interoperate with one another. This also can take full advantage of inheritance, polymorphism, exceptions, and other features.

Garbage Collector (GC)CLR also contains Garbage Collector (GC) which runs in a low-priority thread and checks for unreferenced dynamically allocated memory space. If it finds some data that is no more referenced by any variable/reference, it re-claims it and returns the occupied memory back to the Operating System; so that it can be used by other programs as necessary.

30

Integrated Development Environment (IDE)An integrated development environment (IDE) (also known as integrated design environment, integrated debugging environment or interactive development environment) is a software application that provides comprehensive facilities to computer programmers for software development.IDEs typically present a single program in which all development is done. This program typically provides many features for authoring, modifying, compiling, deploying and debugging softwareVisual Studio .NET IDE Visual Studio .NET IDE (Integrated Development Environment) is the Development Environment for all .NET based applications which comes with rich features. VS .NET IDE provides many options and is packed with many features that simplify application development by handling the complexities. Visual Studio .NET IDE is an enhancement to all previous IDEs by Microsoft. One IDE for all .NET Projects Visual Studio .NET IDE provides a single environment for developing all types of .NET applications. Applications range from single windows applications to complex n-tier applications and rich web applications. Option to choose from Multiple Programming Languages You can choose the programming language of your choice to develop applications based on your expertise in that language. You can also incorporate multiple programming languages in one .NET solution and edit that with the IDE.

Built-in BrowserThe IDE comes with a built-in browser that helps you browse the Internet without launching another application. You can look for additional resources, online help files, source codes and much more with this built-in browser feature.

WEBPAGESASP.NET web pages, known officially as "web forms", are the main building block for application development. Web forms are contained in files with an ".aspx" extension; these files typically contain static

(X) HTML markup, as well as markup defining server-side Web Controls and User Controls where thedevelopers place all the required static and dynamic content for the web page. An ASP.NET Web page

consists of two parts: Visual elements, which include markup, server controls, and static text. Programming logic for the page, which includes event handlers and other code. ASP.NET provides two models for managing the visual elements and code the single-file page 31

model and the code-behind page model. Single-file Page Model In the single-file page model, the page's markup and its programming code are in the same physical .aspx file. Code behind Model Page Model Microsoft recommends dealing with dynamic program code by using the code-behind model, which places this code in a separate file or in a specially designated script tag. The codebehind page model allows you to keep the markup in one filethe .aspx fileand the programming code in another file. The name of the code file varies according to what programming language you are using. Code-behind files typically have names like MyPage.aspx.cs or MyPage.aspx.vb while the page file is MyPage.aspx (same file name as the page file (ASPX), but with the final extension denoting the page language). Advantages of Code-Behind Pages Code-behind pages offer advantages that make them suitable for Web applications with significant code or in which multiple developers are creating a Web site. Advantages of the code-behind model include the following: Code-behind pages offer a clean separation of the markup (user interface) and code. It is practical to have a designer working on the markup while a programmer writes code. Code is not exposed to page designers or others who are working only with the page markup. Code can be reused for multiple pages.

Directives A directive is special instructions on how ASP.NET should process the page. Each directive can contain one or more attributes (paired with values) that are specific to that directive. The directives section is one of the most important parts of an ASP.NET page. Directives control how a page is compiled, specify settings when navigating between pages, aid in debugging (errorfixing), and allow you to import classes to use within your pages code. Directives start with the sequence . The most common directive is which can specify many things, such as 32

which programming language is used for the server-side code. Page directive is used at the top of the page like:
The Page directive, in this case, specifies the language thats to be used for the application logic by setting the Language attribute appropriately. The value provided for this attribute, in quotes, specifies that were using either VB.NET or C#.

NamespacesNamespaces are a way to define the classes and other types of information into one hierarchical structure. System is the basic namespace used by every .NET code. If we can explore the System namespace little bit, we can see it has lot of namespace user the system namespace. For example, System.Io, System.Net, System.Collections, System.Threading, etc. Let us see the content of a few Namespaces: System: Contains classes for implementing base data types. System.Collection: Contains classes for working with standard collection type, such as hash table and array list. System.Componentmodel: Contains classes for implementing both the design-time and run-time behavior of components and controls. System. Data: Contains classes for implementing ADO.NET architecture. System. Web: Contains classes and interfaces that enable browser/server communication. System.web.sessionstate:

Contains classes for implementing session states. System.Web.UI Contains classes that are used in building the user interfaces of the ASP.NET page. System.Web.UI.WebControls Contains classes for providing web controls.

33

System.Web.UI.HtmlControls Contains classes for providing HTML controls. Life Cycle Events of an ASP.NET Page PreInit This is the first real event you might handle for a page. You typically use this event only if you need to dynamically set values such as master page or theme. Init This event fires after each control has been initialized. Init complete Raised once all initialization of the page and its controls have been completed. Preload This event fires before view state has been loaded for the page and its controls and before post back processing. Load The page is stable at this time Control (PostBack) event(s) ASP.Net now calls any events on the page or its controls that caused the PostBack to occur. LoadComplete At this point all controls are loaded PreRender Allows final changes to the page or its control. SaveStateComplete Prior to this event the view state for the page and its control is set. Render At this point ASP.NET call this method on each of the pages controls to get its output. Unload This event is used for cleanup code.

.12 Creating a Website

34

Go to File Menu and Click on New Web Site ... as displayed in the picture below.

A Dialogue box will appear asking for Template, Location, Language. Select/write the location in the location TextBox, Select ASP.NET Web Site as Tempate and Select Visual C# as language as displayed in the picture below. Click OK.

35

This will create a default.aspx, default.aspx.cs (it is called as codebehind file) file, web.cofig file and an App_Data (It is used to place your database like MS Access or SQL Express or xml files ) folder by default as displayed in the picture below.

Start writing few codes as displayed in the picture below. You can notice that as soon as you started writing code, Visual Web Develope will give intellisense (dropdown) to complete the code of the control as shown in the picture below.

36

Write a Label control and a Button control as displayed in the picture below. You can notice that in the OnClick property of the Button control I have specified the name of the method that will fire when the button will be clicked. I will write this method in the Codebehind file.

Now press F7 key from the Keyboard and you will jump to the Codebehind file named default.aspx.cs. Alternatively you can click + symbol beside the default.aspx file and double click default.aspx.cs. Write few lines of code into it as displayed in the picture below. In this file Page_Load method will be automatically written. I am writing SubmitMe method that will fire when Button will be clicked as stated above. Now Save all files by clicking on the Save All toolbar or by going through File->Save All.

37

Now hit F5 key from your keyboard and your application will start in the debug mode. Alternatively you can click on the Play button from the toolbar. This will ask you to modify the web.cofig file to start the application in the debug mode like picture below. Click OK button. Try clicking the Submit button and you will see that a message "Hello World" appears in the browser just beside the Button like below picture.

38

The default folders present in the newly created web site App_Code Folder As its name suggests the App_Code Folder stores classes, typed data sets, etc. All the items that are stored in App_Code are automatically accessible throughout the application. App_Data Folder The App_Data folder is used as storage for the web application. It can store files such as .mdf, .mdb, and XML. It manages all of your application's data centrally. It is accessible from anywhere in your web application. App_Theme Folder If you want to give your web sites a consistent look, then you need to design themes for your web application. The App_Themes folder contains all such themes. App_Browser Folder The App_Browser folder contains browser information files (.browser files). These files are XML based files which are used to identify the browser and browser capabilities. App_LocalResource Folder Local resources are specific to a single web page, and should be used for providing multilingual functionality on a web page. App_GlobalResource Folder The App_GlobalResource folder can be read from any page or code that is anywhere in the web site. Bin Folder Contains compiled assemblies for code that you want to reference in your application.

.13 Hierarchy of .config filesTOP

The .NET Framework relies on .config files to define configuration options. The .config files are text-based XML files. Multiple .config files can, and typically do, exist on a single system.

Web. Config file is used to control the behavior of individual ASP.NET applications. The .config files are text-based XML files.System-wide configuration settings for the .NET Framework are defined in the Machine.config file. The Machine.config file is located in the %SystemRoot%\Microsoft.NET\Framework\%VersionNumber %\CONFIG\ folder. The default settings that are contained in the Machine.config file can be modified to affect the behavior of .NET applications on the whole system.

Web.config File "What we can do using the Web.config file"...

39

Can create database connection using the Web.config file According to the user log in system environment, we can modify the Authentication and Authorization. We can set image path for the uploading images. Also we can manage the lager size files, when uploading to the web server. If the System.Net.Mail email sending, we should configure the Web.config file. How to Create Database connection in the Web.config file You can write following code before the tag and inside the tag

How to manage Form authentication and the authorization in the Web.config file. Following code demonstrate the way it can be implement. Then you should show the location which need to be restricted from anonymous users.

After the tag we can write following code to above purpose. How we should configure the Web,config file according to the E-mail sending... After the we should change following changes to the Web.config file

40

How to set the Image path when uploading images to the web.. Machine.config File The Machine.Config file, which specifies the settings that are global to a particular machine. This file is located at the following path: \WINNT\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications. You can override settings in the Machine.Config file for all the applications in a particular Web site by placing a Web.Config file in the root directory of the Web site as follows: \InetPub\wwwroot\Web.Config Difference between Machine.Config and Web.Config Machine.Config: i) This is automatically installed when you install Visual Studio. Net. ii) This is also called machine level configuration file. iii)Only one machine.config file exists on a server. iv) This file is at the highest level in the configuration hierarchy. Web.Config: i) This is automatically created when you create an ASP.Net web application project. ii) This is also called application level configuration file. iii)This file inherits setting from the machine.config

41

Chapter IIIServer Controls and Customizing a Web Application

TOP

.14 Configuring Server ControlsServer controls are tags that are understood by the server. There are three kinds of server controls: HTML Server Controls - Traditional HTML tags Web Server Controls - New ASP.NET tags Validation Server Controls - For input validation

HTML Server controls HTML server controls are HTML tags understood by the server. An Html server controls allows us to define actual HTML inside our ASP.Net page but work with the control on the server through an object model provided by the .net Framework.HTML elements in ASP.NET files are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control.Creating HTML server control in the designer: Open an ASP.NET page inside the designer In the Toolbox , click the HTML tab to expose the html controls

Drag an HTML element to either design or source view of the webpageConvert the HTML element to a server control by setting the runat attribute. In source view add the runat="server"

Web server controlsWeb Server controls are special ASP.NET tags understood by the server. Like HTML server controls, web server controls are created on the server and they require a runat-server attribute to work. The syntax for creating a web server control is:

42

Asp.Net provides programmers a set of web server control for creating web pages that provide more functionality and a moe consistent programming model. Adding web server control using Design View Open the toolbox and double click the required control ( OR ) Drag a webserver control from the toolbox and drop it on the web page either on the design or source view.

Properties and their DescriptionAttribute A list of all attribute name_value pairs expressed on a server control tag within a selected ASP.NET page. Disabled A value indicates whether the disabled attribute is included when an HTML control rendered on the browser,which makes the control read only ID The programmatic identification of the control. Style Alist of all cascading style sheet(css) properties that are applied to the specified HTML control. TagName The element of a tag that contain runat=server attribute Visible A value that indicates whether the HTML server control is displayed on the page .If this value is set to false, the control does not render any HTML to the browser. AccessKey The keyboard shortcut key.It can specify a single letter or numbers that the user can press while holding down Alt. Attributes A collection of additional attributes on the control that is not defined by a public property, but that should be rendered in the primary HTML element of this control. Back color The background color of the control, which can be set using standard HTML color identification such as "red or "blue". Border Color

43

The bordercolor of the control which can be set using standard HTML color identifiers such as "black" or "red" Border Width The width of the controls border in pixels Border Style The border style, If there is any possible values are not set, none, dotted and outset CSS Class The CSS class to assign to the content. Style A list of all CSS properties that are applied to the specified HTML server control

Enabled An attributes that disables the control when set to false. Enable Theming This enables themes for this control Font You can make a web server controls text italic by including the Font-Italic attributes in its opening tag. Fore Color The foreground color of the control Height It controls the height. Skin ID The skin to apply to the control Tab Index The controls position in the tab order ToolTip The text that appears when the user hovers the mouse pointer over a control. Width The width of the control. The possible units are pixels, pointpich and inch etc..

44

Exploring Common Server ControlsThe Label Control: The label control displays text at a specific location on a web page using the properties. Two Ways to set the value for the label control or Label1.Text="Test Text"; The TextBox control:

TOP

The TextBox control is used to collect information from a user.The TextBox control contains a TextMode property that you can set to single line,multi line or password. The single line value allows the user to enter a single line of text. The multiline value indicates taht a user is able to enter many lines of Text. Password value creates a single text box that makes the values entered by the user as they are entered MaxLength specifies the maximum number of characters the user can enter into the control. ReadOnly determines whether the data in the TextBox can be edited. The Button control

The Buton control displays a buttton on the web page that a user can click to trigger a postback to the web server.The Button control can be rendered as a submit button or a command Button. A submit button performs a postback to the server. You provide an event handler for the button's click event to control the actions performed when the user clicks the server button A button control can also be used as a command button, Which is one of a set of button that works together as a group such as a toolbar. You define a button as a command button by assisgning a value to its command name property. Checkbox Control The checkbox control gives the user the ability to select between true and false. The checkbox controls text property specifies its caption.The ChekedChanged event is raised when the the state of the CheckBox control changes.

45

Property: Text This property is used to get or set the text of the checkbox control. Items This property is used to access the individual check boxes in the checkboxlist control. RadioButton Control The radiobutton control gives the user the ability to select between mutually exclusive.Radio Button controls in a group. To group multiple radiobutton controls together,specify the same Group Name for each radiobutton controls in a group.ASP.net ensures that selected radio button is mutually exclusive within the group. Text: This property is used to get or set the text of the radio button control.

Items

This property is used to access the individual radio button in the radio button list control.

Exploring specialized server controls

The Literal Control The Literal control is similar to the Label control in that both control used to display static text in a web page.The Literal control does not provide substantial functionality and does not add any HTML elements to thepage,whereas the Label is rendered as a tag.This means that the literal control does not have a style property and therefore you cannot apply style to its content. . The Literal control is useful when you need to add text to the output of the page dynamically(from the server)but do not want to use a label. The Literal control's mode property which is used to specify particular handling of the content of the text property. Mode PassThrough: The text content is rendered as is. Encode: The text content is HTML-encoded.

46

Transform: The Text content is converted to match the markup language of the requesting browser, such as HTML and XHTML. Example: Untitled Page

protected void Page_Load(object sender, EventArgs e) { Literal1.Text=@"This is anexamplealert(""Hi"");";

Literal2.Text =@"This is anexamplealert(""Hi"");"; Literal3.Text =@"This is anexamplealert(""Hi"");"; Literal1.Mode = LiteralMode.PassThrough; Literal2.Mode = LiteralMode.Encode; Literal3.Mode = LiteralMode.Transform; } Output

This is an example This is an examplealert("Hi"); This is an

example47

The Table,TableRow and Tablecell Controls

Tables are useful for tabular data, but they can also help with the layout of graphics and controls on a form.The concept of column and rows is a powerful technique for web pages. HTML provides the tag for defining a table, the tag for creating a row, and the tag for defining a column in the row. Adding Rows and Cells Dynamically to a table control: 1.Open a Visual Studio Web Site or create a new one.Open a web page with which to work. 2.From the Toolbox, drag a Table control onto your page. 3.Open the code_behind file for the given page and add a PreInit event to the page. 4. Inside the PreInit event write a for loop to create five new rows in table. 5.Inside this loop, add another for loop to create three columns for each row. 6.Inside this loop,modify the TableCell.Text property to identify the row and column. protected void Page_PreInit(object sender, EventArgs e) { Table1.BorderWidth = 1; for (int row = 0; row < 5; row++) { TableRow tr = new TableRow(); for (int column = 0; column < 3; column++) { TableCell tc = new TableCell(); tc.Text = string.Format("Row:{0} Cell:{1}", row, column); tc.BorderWidth = 1; tr.Cells.Add(tc); } Table1.Rows.Add(tr); } } Output

Row:0 Cell:0 Row:1 Cell:0

Row:0 Cell:1 Row:1 Cell:1

Row:0 Cell:2 Row:1 Cell:2 48

Row:2 Cell:0 Row:3 Cell:0 Row:4 Cell:0

Row:2 Cell:1 Row:3 Cell:1 Row:4 Cell:1

Row:2 Cell:2 Row:3 Cell:2 Row:4 Cell:2

The Image Control: The image control can be used to display an image on a web page.The Image control inherits directly from the WebControl class.The ImageMap and Image-Button controls inherits directly from the Image control. The image control is represented as the element in the source and has no content embedded between its opening and closing tag. Image control's primary property ImageUrl, indicates the path to the image that is downloaded from the browser and displayed on the page.

AlternateText property of image control is used to dispaly a text message in the user's browser when the image is not available. The DescriptionUrl properrty is used to provide further explanation of the content and meaning of the image when using non visual page renders. Setting the GenerateEmptyAlternateText property to True will add the attribute alt="" to the element that the image control generates. The ImageButton Control The Image control does not have a click event.To make use of click event when it is needed then we can go for ImageButton control. Working with Calendar Controls The calendar control allows you to display a calendar on a web page. The calendar can be used when asking a user to select a given date or series of dates. Users can navigate between years,months and days. Property: Caption: The Text that is rendered in the Calendar. DayNameFormat: The Format for the names of the days of the week

49

Selected Date: The Date selected by the user. Selection Mode: A value that indicates how many dates can be selected.It can be a Day,DayWeekMonth or name. Todyas Date: Display Todays Date.. The FileUpload control The FileUpload control is used to allow a user to select and upload a single file to the server.The control displays as a text box and a browse button. Properties: FileBytes: The file is exposed as a byte array. FileContent The file is exposed as a stream. PostedFile The file is exposed as an object of type HttpPostedFile.This object has properties such as content type and content length. The Panel control: The panel control is used as a control container.It can be useful when you need to group controls and work with them as a single unit. The BackIMageUrl property can be used to display a background image in the panel control. The Wrap property specifies whether items in the panel automatically continue in the next line when a line is longer than the width of the panel control. The default button property can be set to the ID of any control on your form that implements the IButtonControl Interface. The MultiView and View Controls: Like the Panel control, the multiview and view controls are also continer controls; that is thay are used to group other controls.Amultiview exists to contain other view controls.A view control must be contained inside a multiview.

You can use the ActiveViewIndex property or the seactiveview method to chage the view programmatically.If the Activeviewindex is set to -1,no view controls are displayed.

50

Consider a user registration web page where you need need to walk a user through the process of registering with your siteYou could use a single multiview control and three view control to manage this process To manage the page in this example, the button the page are set to command buttons When a user clicks a button,the commandname property of commandeventargs is checked to determine the button pressed.Based on this information,the mutiview shows another view control.The following is an example of the code_behind page:

Create an aspx page and enter the following code Untitled Page This is View1. Click the button to goto View 2. This is View2. Enter your name and click the button to goto View 3.
Name: This is View3.

Code File protected void but_Submit_Click(object sender, EventArgs e) { if (MultiView1.ActiveViewIndex == 0) { MultiView1.SetActiveView(View2); } else if (MultiView1.ActiveViewIndex == 1)

51

{ MultiView1.SetActiveView(View3); if (String.IsNullOrEmpty(fld_Name.Text)) { lit_Name.Text = "You did not enter your name. "; } else { lit_Name.Text = "Hi, " + fld_Name.Text + ". "; } } else if (MultiView1.ActiveViewIndex == 2) { MultiView1.SetActiveView(View1); } }

The Wizard Control The wizard control is used to display a series of wizardstep controls to a user one after the other as part of a user input process.The wizard control builds on the mutiview and view controls presented previously.

Validation control: A Validation server control is used to validate the data of an input control. If the data does not pass validation, it will display an error message to the user. The syntax for creating a Validation server control is:

Validation Server Control Compare Validator Custom Validator Range Validator RegularExpression Validator RegularField Validator Validation Summary Properties Description Compares the value of one input control to the value of another input control or to a fixed value Allows you to write a method to handle the validation of the value entered Checks that the user enters a value that falls between two values Ensures that the value of an input control matches a specified pattern Makes an input control a required field Displays a report of all validation errors occurred in a Web page

52

ControlToValidate: This property is used to specify the ID of the control to be validated. ErrorMessage: This property is used to specify the error message dispalyed when the validation condition fails. Text This property is used to specify the error message dispalyed by the control.

AdRotator Web server controlAdRotator is one of the Rich Web Controls available in ASP.NET. AdRotator control is available in ASP. Net to make the task of rotating the advertisement images in a web form quickly and easily. The AdRotator Web server control can be used for the Advertisement(Ads) purposes in your ASP.NET Web pages. The control displays a graphic image a .gif file or similar image.It displays flashing banner advertisements randomly. It also enables you to display different types of images whenever you refresh the page. Adrotator control takes the information about the images that are to be displayed from an XML file which also have many other elements in it that are used by this control. Create an advertisement file The advertisement file is an XML file. The following are some of the elements of this XML file 1. : Optional. The path to the image file 2. : Optional. The URL to link to if the user clicks the ad 3. : Optional. An alternate text for the image 4. : Optional. A category for the ad 5. : Optional. The display rates in percent of the hits Let us assume that the advertisement XML file is named as myads.xml. The file is as: images/img1.jpg http://www.main.com Main 50 Product1 images/img2.jpg http://www.main2.com Main Page 2 75 Product2 Example

53

images\koala.jpg http://www.asp.net ASP.NET Logo 1 This is the caption for Ad#1 images\penguins.jpg http://www.yahoo.com www.yahoo.com 1 This is the caption for Ad#2

Create the application 1. Open a new ASP.NET Web application. 2. Click on the Web Forms tab of toolbox and add an AdRotator control on to the form. 3. Place the AdRotator control near the top center of the Web Form, and resize it so that it is the same size as the images that you created earlier. (To control the size more accurately, set the Height and Width properties). The following code is automatically generated: 4. Click AdRotator1 (the newly added AdRotator control), and then press the F4 key to view its properties. 5. Set the AdvertisementFile property to myads.xml. 6. Save and build the project

54

.15 Creating Master pages to establish a common layout for a web applicationASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.Advantages of Master Page: They allow you to centralize the common functionality of your pages so that you can make updates in just one place They make it esay to create one set of controls and code and apply the result to a set of pages

Master pages actually consist of two pieces, the master page itself and one or more content pages. Master Pages A master page is an ASP.NET file with the extension .master (for example, MySite.master) with a predefined layout that can include static text, HTML elements, and server controls. The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages. The @ Master directive can contain most of the same directives that a @ Control directive can contain. For example, the following master-page directive includes the name of a code-behind file, and assigns a class name to the master page. Replaceable Content Placeholders In addition to static text and controls that will appear on all pages, the master page also includes one or more ContentPlaceHolder controls. These placeholder controls define regions where replaceable content will appear. In turn, the replaceable content is defined in content pages. Create a master page using the Add New Item dialogue box, and then by selecting Master Page from the list.

55

AutoEventWireup="true"

CodeFile="MasterPage.master.cs"

Master Page This is the header from the Master Page Left Navigation 56

Content Pages You define the content for the master page's placeholder controls by creating individual content pages, which are ASP.NET pages (.aspx files and, optionally, code-behind files) that are bound to a specific master page. The binding is established in the content page's @ Page directive by including a MasterPageFile attribute that points to the master page to be used. In the content page, you create the content by adding Content controls and mapping them to ContentPlaceHolder controls on the master page.

Create a content page by selecting a web form from the Add New Item dialog box and select the Select master page check box at the bottom of the page as below

Clicking Add in the above dialog box will result in the Master Picker dialog box

57

being displayed. As we can see from the below screenshot, the master selection dialog box displays all the master pages available in the Web application.

58

Enter the markup code as This content is from the content page Output

ThemesIn ASP.Net theme is a collection of styles,property settings and graphics that define the appearance of pages and controls on your web site. Themes save your time and improve the consistency of a site by applying a common set of control properties,styles and graphics across all pages in a web site. Themes can be centralized allowing you to quickly change the appearance of all the controls on your site from a single file. ASP.NET themes consist of skin files, css, images and other resources. Right-click on the project in the Solutions Explorer, select Add ASP.NET Folder, and then

59

choose Theme from the submenu Theme1 will be added to the solution explorer, rename this folder as ControlsTheme

Right-click on the ControlsTheme folder we just created, select Add New Item, we will getthis

4. Select the Skin File option.5. Name the file as Label.skin and enter

6. Again right click ControlsTheme folder and select Add New Item 7. Select the Skin File option. 8. Name the file as Button.skin and enter

9. Add a web form and enter the markup as Applying Custom Themes to an ASP.NET Page

60



This Label inherits the style specified in the Label.skin file

10. Run the application Output:

This button inherits the style specified in the Button.skin file

This Label inherits the style specified in the Label.skin fileStyle sheet Styles defines the appearance of an HTML element.For example, you can define a color or a font to be used for an element, such as paragraph.A style sheet is document that defines a group styles.These style elements can be applied to any element in the web page.It as the extension .css CSS (Cascading Style Sheets) is a well established and frequently used technology to achieve the separation between formatting and content. It's supported by virtually all of the moderns web browsers. When you employ CSS techniques, you are always sure that altering the formatting of your web pages will go as smooth as possible. Different ways to use Style Sheets:

External Style Sheet: In the external style sheet we need to externally create the CSS file. This particular style sheet can be made use by all the web pages. Click on website->add new item->style sheet->add

Now type the below mentioned code in the style sheet file: body { color:Blue; background-color:Lime; } In the source file inside the head tag type the below mentioned code:

61

Internal Style Sheet: In the Internal style sheet, the style sheet file is applicable only to the current application.Other applications cannot share that file. Type the below code in the source file: body { color:Blue; background-color:Lime;

} page

How to Deploy ASP. Net Websites on IIS 7.0Let us see with an example on how to deploy ASP.NET websites on IIS 7.0. Step 1: From Visual Studio, publish your Web application. Step 2: Copy the published application folder to "C:\intepub\www.root" [default] folder. Step 3: From RUN - > inetmgr -> OK The following screen will come. This is the main page for any application. There are three panels.

62

"TestWeb" is a recently pasted webapplication on your wwwroot folder. Step 4: We need to convert it to an application, just right click and then Click on "ConvertToApplication" as shown in the following picture

After converting it to application, its icon will be changed and then you can set the property for your web application from the middle pane. You can set IIS Authentication Mode, Default Page Just like IIS 6.0:

63

.16 Constructing Web Application using Web PartsTOP

ASP.NET Web Parts controls are an integrated set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly in a browser. These controls and classes can be found inside the name space " System.Web.UI.WebControls.WebParts". WebPartManager: The webpartmanager control is required on every page that include web parts. It does not have a visual representation. Rather, it manages all the Web Part controls and their events on the given page. WebPart: The WebPart class represents the base class for all web parts that you develop. It provides UI,personalization and connection features. Catalog Part: The Catalog Part provides the UI for managing a group of web parts that can be added to a web part page. This group is typically sitewide. PageCatalogPart: The pagecatalogpart is similar to the catalogpart. However, it only groups those web parts that are part of the given page. In this way if a user closes certain web parts on the page, he or she can use the pagecatalogpart to read them to the page. EditorPart: The EditorPart control allow users to define customizations for the given web part, such as modifying property settings. DeclarativeCatalogPart DeclarativeCatalogPart allows you to declare web parts that should be available to add to a page or the entire site. WebPartZone

64

The webpartzone control is used to define an area on your page in which web parts can be hosted. EditorZone: The EditorZone control provides an area on the page where EditorPart controls can exist. CatalogZone: The CatalogZone control defines an area in which a catalog part control can exist on the page. To place web parts inside a zone, you have to add the ZoneTemplate control inside the webpartzone. The Zone template control lets you add other ASP.NET controls to the zone and have them turned into actual web parts. The following markup shows an example: Namespace: using System.Web.UI.WebControls.WebPart Source File: Google site

65

Output

.17 Site NavigationTOP

There are many ways to navigate from one page to another in ASP.NET. Client-side navigation Cross-page posting

66

Client-side browser redirect Server-side transfer

Client-side NavigationClient-side code or markup allows a user to request a new web page. It requests a new Web page in response to a client-side event, such as clicking a hyperlink or executing JavaScript as part of a buttonclick. HyperLink Control : Source Goto NavigateTest2 HyperLink Control : Rendered HTML Goto NavigateTest2 In this example, if this control is placed on a web page called NavigateTest1.aspx, and the HyperLink Control is clicked, the browser simply requests the NavigateTest2.aspx page. HTML button element with client-side JavaScript type=button value=Goto NavigateTest2 onclick=return

The JavaScript source for the Button1_onclick method is added into the element of the page function Button1_onclick { document.location = NavigateTest2.aspx; }

Cross-Page PostingA control and form are configured to PostBack to a different Web page than the one that made the original request. This navigation is frequently desired in a scenario where data is collected on one web page and processed on another web page that displays the results. Here a Button control has its PostBackUrl property set to the web page to which the processing should post back.The page that receives the PostBack receives the posted data from the first page for processing. Example protected void Page_Load(object sender, EventArgs e) { if(Page.Previous == null) { Label1Data.Text = No previous page in post ; } else

67

{ Label1Data.Text = ( (TextBox)PreviousPage.FindControl(TextBox1) ).Text; } } Here a web page called DataCollection.aspx contains a TextBox control called TextBox1 and a Button control that has its PostBackUrl set to ~/ProcessingPage.aspx. When ProcessingPage is posted by the data collection page, it executes server-side code to pull the data from the data collection page and put it inside a Label control.

Client-Side Browser RedirectServer-side code sends a message to the browser, informing the browser to request a different Web page from the server. The Redirect method can be used in server-side code to instruct the browser to initiate a request for another web page. The Redirect is not a PostBack. It is similar to the user clicking a hyperlink on a web page. Example protected void ButtonSubmit_Click(object sender, EventArgs e) { Response.Redirect(OrderDetails.aspx); }

Server-Side TransferServer-side code transfers control of a request to a different Web page. This method transfers the entire context of a Web page over to another page. The page that receives the transfer generates the response back to the user's browser. Example protected void ButtonSubmit_Click(object sender, EventArgs e) { Server.Transfer(OrderProcessing.aspx); }

.18 ASP.NET State Management & SecurityTOP

ASP.NET State Management TechniquesGenerally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested. In asp.net, there are two State Management Techniques, client side state management and server side state management.

Client side state management optionsASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden

68

fields, View State and Control state (ASP.NET 2.0).

CookieA cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user. Example Use of cookies to customize web page :

if (Request.Cookies["UserId"] != null)lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!"; else lbMessage.text = "Guest,welcome to our website!"; If we want to store client's information use the below code Response.Cookies["UserId"].Value=username;

Hidden fieldsHidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. Hidden field values can be intercepted(clearly visible) when passed over a network We can use hidden fields in ASP.NET pages using following syntax protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1; //to assign a value to Hidden field Hidden1.Value="Create hidden fields"; //to retrieve a value string str=Hidden1.Value; View State: View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. We can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true.View state information of all the controls on the page will be submitted to server on each post back.We can also disable View State for the entire page by adding EnableViewState=false to @page directive. View State can be used using following syntax in an ASP.NET web page. // Add item to ViewState ViewState["myviewstate"] = myValue; //Reading items from ViewState Response.Write(ViewState["myviewstate"]);

69

Example protected void Page_Load(object sender, EventArgs e) { //First we check if the page is loaded for the first time, if (!IsPostBack) { ViewState["PostBackCounter"] = 0; } //Now, we assign the variable value in the text box int counter = (int)ViewState["PostBackCounter"]; Label1.Text = counter.ToString(); } protected void Button1_Click(object sender, EventArgs e) { int oldCount = (int)ViewState["PostBackCounter"]; int newCount = oldCount + 1; //First, we assign this new value to the label Label1.Text = newCount.ToString(); //Secondly, we replace the old value of the view state so that the new value is read the next //time ViewState["PostBackCounter"] = newCount; } Source Code:

Query strings:Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Source