You are on page 1of 165

.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

.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 I
Object-oriented Programming using C Sharp

.1 Features of Object -Oriented approach


Classes 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

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 Encapsulation
Abstraction 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.

Polymorphism
Example: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 approach


Specification: 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 Types
TOP

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 Type
Structure 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 explicit
parameterless 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:

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 Operators
TOP

Arithmetic Operator

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

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

< <= > >= == !=

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 Constructs


Decision-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)

{ 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");

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# program
Select 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 an
interface, you need to implement all the methods defined in the interface.

.6 Events and Delegates


TOP

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 handling


TOP

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 Collections
TOP

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 type
using 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(); } } }

Output
Joydip 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 Threading
Overview 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 SDK
using 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; } }

.11
TOP

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 text
files 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 Requirements


Hardware 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 memory


A 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 studio2008
The 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 in
ASP.NET programming

.13
TOP

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 Developer
The .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 Library


The 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) Code


When 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.

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

CLS
The 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 software
Visual 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 Browser
The 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.

WEBPAGES
ASP.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 the
developers 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 <%@, followed by the directive name, plus any attributes and their corresponding values, then end with %>. The most common directive is <%@ Page %> 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: <%@ Page Language="VB" %> <BR> <%@ Page Language="C#" %> 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#.

Namespaces
Namespaces 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 files


TOP

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 <system.web> tag and inside the <Configuration> tag <connectionStrings> <add name="NameConnectionString" connectionString="Data Source= (Default);Initial Catalog=DatabaseName;User ID=Username;Password="Your Password"" providerName="System.Data.SqlClient"/> </connectionStrings>

How to manage Form authentication and the authorization in the Web.config file. Following code demonstrate the way it can be implement.
<authentication mode="Forms"> <forms loginUrl="login page url" timeout="30"></forms> </authentication> Then you should show the location which need to be restricted from anonymous users.

After the <system.web/> tag we can write following code to above purpose.
<location path="FolderNameAuthenticationNeed" allowOverride="true"> <system.web> <authorization> <deny users="?"/> </authorization> </system.web> </location> How we should configure the Web,config file according to the E-mail sending... After the <system.web/> we should change following changes to the Web.config file <system.net> <mailSettings> <smtp>

40

<network host="Host name" port="25" userName="Username" password="password" /> </smtp> </mailSettings> </system.net>

How to set the Image path when uploading images to the web..
<appSettings> <add key="ItemImagePath" value="Specify the path to save images"/> </appSettings> 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 III
Server Controls and Customizing a Web Application

TOP

.14 Configuring Server Controls


Server 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 webpage


Convert the HTML element to a server control by setting the runat attribute. In source view add the runat="server"

Web server controls


Web 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: <asp:control_name id= some_id runat=server />

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 Description


Attribute 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 Controls


The 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 <asp:Label ID="Label1" runat="server" style="color:Blue" Text="Test Text" > </asp:Label> 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. <asp:textbox id=TextBox1 runat="server"> </asp:textbox> 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 <span> 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: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Literal ID="Literal1" runat="server"></asp:Literal><br /> <asp:Literal ID="Literal2" runat="server"></asp:Literal><br /> <asp:Literal ID="Literal3" runat="server"></asp:Literal> </div> </form> </body> </html> protected void Page_Load(object sender, EventArgs e) { Literal1.Text=@"This is an<font size=4>example</font><script>alert(""Hi"");</script>";

Literal2.Text =@"This is an<font size=2>example</font><script>alert(""Hi"");</script>"; Literal3.Text =@"This is an<font size=7>example</font><script>alert(""Hi"");</script>"; Literal1.Mode = LiteralMode.PassThrough; Literal2.Mode = LiteralMode.Encode; Literal3.Mode = LiteralMode.Transform; } Output

This is an example This is an<font size=2> example</font><script>alert("Hi");</script> This is an

example
47

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 <table> tag for defining a table, the <tr> tag for creating a row, and the<td> 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<asp:image> 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<img> 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


<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="SM1" runat="server" /> <asp:UpdatePanel ID="UP1" runat="server"> <ContentTemplate> <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> <asp:View ID="View1" runat="server"> This is View1. Click the button to goto View 2. </asp:View> <asp:View ID="View2" runat="server"> This is View2. Enter your name and click the button to goto View 3.<br /> Name: <asp:TextBox ID="fld_Name" runat="server" /> </asp:View> <asp:View ID="View3" runat="server"> <asp:Literal ID="lit_Name" runat="server" /> This is View3. </asp:View> </asp:MultiView> <br /><br /> <asp:Button ID="but_Submit" runat="server" Text="Continue" onclick="but_Submit_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html> 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:

<asp:control_name id=id_name runat=server/>


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 control


AdRotator 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. <imageUrl>: Optional. The path to the image file 2. <NavigateUrl>: Optional. The URL to link to if the user clicks the ad 3. <AlternateText>: Optional. An alternate text for the image 4. <Keyword>: Optional. A category for the ad 5. <Impressions>: 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: <Advertisements> <Ad> <ImageUrl>images/img1.jpg</ImageUrl> <NavigateUrl>http://www.main.com</NavigateUrl> <AlternateText> Main</AlternateText> <Impressions>50</Impressions> <Keyword>Product1</Keyword> </Ad> <Ad> <ImageUrl> images/img2.jpg</ImageUrl> <NavigateUrl>http://www.main2.com</NavigateUrl> <AlternateText> Main Page 2</AlternateText> <Impressions>75</Impressions> <Keyword>Product2</Keyword> </Ad> Example

53

<?xml version="1.0" encoding="utf-8" ?> <Advertisements> <Ad> <ImageUrl>images\koala.jpg</ImageUrl> <NavigateUrl>http://www.asp.net</NavigateUrl> <AlternateText>ASP.NET Logo</AlternateText> <Keyword></Keyword> <Impressions>1</Impressions> <Caption>This is the caption for Ad#1</Caption> </Ad> <Ad> <ImageUrl>images\penguins.jpg</ImageUrl> <NavigateUrl>http://www.yahoo.com</NavigateUrl> <AlternateText>www.yahoo.com</AlternateText> <Keyword></Keyword> <Impressions>1</Impressions> <Caption>This is the caption for Ad#2</Caption> </Ad> </Advertisements>

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: <asp:AdRotator id="AdRotator1" style="Z-INDEX: 102; LEFT: 32px; POSITION: absolute; TOP: 32px" runat="server" Width="468px" Height="60px"></asp:AdRotator> 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 <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:AdRotator ID="AdRotator2" runat="server" AdvertisementFile="wd.xml" Width="200px" Height="100px"/> </div> </form> </body> </html>

54

.15 Creating Master pages to establish a common layout for a web application
ASP.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. <%@ Master Language="C#" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> 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

<%@ Master Language="C#" Inherits="MasterPage" %>

AutoEventWireup="true"

CodeFile="MasterPage.master.cs"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Master Page</title> </head> <body> <form id="form1" runat="server"> <table bgcolor="#cccc99" id="header" style="WIDTH: 100%; HEIGHT: 80px" cellspacing="1" cellpadding="1" border="1"> <tr> <td width="100%" style="TEXT-ALIGN: center"> This is the header from the Master Page </td> </tr> </table> <b/> <table bgcolor="#99cc99" id="leftNav" style="WIDTH: 108px; HEIGHT: 100%" cellspacing="1" cellpadding="1" border="1"> <tr> <td style="WIDTH: 100px"> Left Navigation </td> 56

</tr> </table> <table bgcolor="#ccff99" id="mainBody" style="LEFT: 120px; VERTICALALIGN: top; WIDTH: 848px; POSITION: absolute; TOP: 94px; HEIGHT: 100%" border="1"> <tr> <td width="100%" style="VERTICAL-ALIGN: top"> <asp:contentplaceholder id="middleContent" runat="Server"></asp:contentplaceholder> </td> </tr> </table> </form> </body> </html>

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


<%@ Page Language="C#" MasterPageFile="~/MyMaster.master" Title="Content Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="middleContent" Runat="Server"> <asp:label runat="server" id="lblMessage"> This content is from the content page </asp:label> </asp:Content> Output

Themes
In 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 get
this

4. Select the Skin File option.


5. Name the file as Label.skin and enter
<asp:label runat="server" width="300px" height="24px" font-bold="True" font-overline="True" font-size="Medium" forecolor="Green" backcolor="Silver"/>

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
<asp:button runat="server" forecolor="RoyalBlue" backcolor="Silver"/>

9. Add a web form and enter the markup as


<%@ page theme="ControlsTheme" language="C#"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html> <head id="Head1" runat="server"> <title>Applying Custom Themes to an ASP.NET Page</title> </head> <body> <form id="Form1" runat="server"> <asp:button id="Button1" runat="server" text="This button inherits the style specified in the Button.skin file" />

60

<br/><br/> <asp:label id="Label1" runat="server">This Label inherits the style specified in the Label.skin file</asp:label> </form> </body> </html>

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 file


Style 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<p>.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: <head runat="server">

61

<link rel="Stylesheet" href="StyleSheet.css" /> <title></title> </head> 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: <head runat="server"> <style type="text/css"> body { color:Blue; background-color:Lime;

} </style> <title>page</title> </head>

How to Deploy ASP. Net Websites on IIS 7.0


Let 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 Parts


TOP

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: <body> <form id="form1" runat="server"> <asp:WebPartManager ID="WebPartManager2" runat="server"> </asp:WebPartManager> <div> <table> <tr> <td> <asp:WebPartZone ID="SidebarZone" runat="server" HeaderText="Sidebar"> <ZoneTemplate> <asp:Label runat="server" ID="linksPart" title="My Links"> <a href="http://www.Google.com">Google site</a> <br /> </asp:Label> </ZoneTemplate> </asp:WebPartZone> </td> <td> <asp:WebPartZone ID="MainZone" runat="server" HeaderText="Main"> <ZoneTemplate> <asp:Label ID="lbl" Text="Some text" Title="Content" runat="server"></asp:Label> </ZoneTemplate> </asp:WebPartZone>

65

</td> <td> <asp:EditorZone ID="EditorZone1" runat="server"> <ZoneTemplate> <asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" /> <asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" /> </ZoneTemplate> </asp:EditorZone> </td> </tr> </table> </div> </form> </body> </html> Output

.17 Site Navigation


TOP

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 Navigation
Client-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 <asp:HyperLink ID=HyperLink1 runat=server NavigateUrl=~/NavigateTest2.aspx>Goto NavigateTest2</asp:HyperLink> HyperLink Control : Rendered HTML <a id=HyperLink1 href=NavigateTest2.aspx> Goto NavigateTest2</a> 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 <input id=Button1 Button1_onclick() /> type=button value=Goto NavigateTest2 onclick=return

The JavaScript source for the Button1_onclick method is added into the <head> element of the page <script language=javascript type=text/javascript> function Button1_onclick { document.location = NavigateTest2.aspx; } </script>

Cross-Page Posting
A 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 Redirect


Server-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 Transfer
Server-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 & Security


TOP

ASP.NET State Management Techniques


Generally, 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 options


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

68

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

Cookie
A 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 fields
Hidden 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: <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

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 File: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"/> Code File: protected void Page_Load(object sender, EventArgs e) { TextBox1.Text = Request.QueryString["aa"]; } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("Default2.aspx?aa=" + TextBox1.Text);

70

Control State:
Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled.

Server Side State management:


State information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server. Application object Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object. In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea Application.Lock(); Application["mydata"]="mydata"; Application.UnLock();

Session object:
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the <session State> section in the application's web.config file. Configuration information: <sessionState mode = <"inproc" | "sqlserver" | "stateserver"> cookieless = <"true" | "false"> timeout = <positive integer indicating the session timeout in minutes> sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode> server = <The server name that is only required when the mode is State Server> port = <The port number that is only required when the mode is State Server> Mode: This setting supports three options. They are InProc, SQLServer, and State Server Cookie less: This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one. Timeout: This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes SqlConnectionString: This identifies the database connection string that names the database used for mode SQLServer.

71

Server: In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state. Port: This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network. We can disable session for a page using EnableSessionState attribute. We can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application. ASP.NET Session state provides a place to store values that will persist across page requests. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { Session["aa"] = 0; } } protected void Button2_Click(object sender, EventArgs e) { TextBox1.Text = Convert.ToString(Session["aa"]); Response.Redirect("Default2.aspx"); } In the source code type the below code: <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

Security
There are two concepts at security for distributed applications - authentication and authorization. Authentication is the process of obtaining some sort of credentials from the users and using thosecredentials to verify the user's identity. Authorization is the process of allowing an authenticated user access to resources.Authentication is always precedes to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous. Authentication providers ASP.net gives a choice of three different authentication providers. The windows Authentication provider lets you authenticates users based on their windows accounts. This provider uses IIS to perform the authentication and then passes the authenticated identity to

72

your code. This is the default provided for ASP.net. The passport authentication provider uses Microsoft's passport service to authenticate users. The forms authentication provider uses custom HTML forms to collect authentication information and lets you use your own logic to authenticate users. The user's credentials are stored in a cookie for use during the session.

Form Authentication Forms authentication generally refers to a system in which unauthenticated requests are redirected to an HTML form, using HTTP client-side redirection. Forms authentication is a good choice if your application needs to collect its own user credentials at logon time through HTML forms. The user provides credentials and submits the form. If the application authenticates the request, the system issues a form that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the form in the request headers. They are authenticated and authorized by an ASP.NET handler using whatever validation method the application specifies. Try the below steps to implement Form Authentication In the web.config file type the below mentioned code <authentication mode = "Forms"> <forms loginUrl = "/Default4.aspx"> <credentials passwordFormat="Clear"> <user name = "Mary" password = "123" /> </credentials> </forms> </authentication> In the source file type the below mentioned code: <head runat="server"> <title></title> <script language = "C#" runat="server"> void Button1_Click (Object sender, EventArgs E) { if (FormsAuthentication.Authenticate (TextBox1.Text, TextBox2.Text))

Response.Write("Valid"); else Response.Write("Invalid"); } </script> </head>

73

<form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"> </asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </div> </form> Windows-Based Authentication Windows-based authentication is handled between the Windows server where the ASP.NET application resides and the client machine. In a Windows-based authentication model, the requests go directly to IIS to provide the authentication process. This type of authentication is quite useful in an intranet environment where you can let the server deal completely with the authentication process especially in environments where users are already logged onto a network. Creating Users Within your Windows XP or Windows Server 2003 server, choose Start-->Control Panel->Administrative Tools-->Computer Management. If you are using Windows Vista, choose Start-->Control Panel-->System and Maintenance-->Administrative Tools-->Computer Management. Either one opens the Computer Management utility. It manages and controls resources on the local Web server. You can accomplish many things using this utility, but the focus here is on the creation of users. Expand the System Tools node. Expand the Local Users and Groups node. Select the Users folder. You see something similar to the results shown in Fig 2.

Right-click the Users folder and select New User. The New User dialog appears, as shown in Figure 3.

74

Give the user a name, password, and description stating that this is a test user. In this example, the user is called Bubbles. Clear the check box that requires the user to change his password at the next login. Click the Create button. Your test user is created and presented in the Users folder of the Computer Management utility, as shown

Now create a page to work with this user. Add the section presented in Listing 1 to your web.config file. Listing 1: Denying all users through the web.config file <system.web> <authentication mode="Windows" /> <authorization> <deny users="*" /> </authorization> </system.web> Passport Authentication: .NET Passport allows users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. By implementing the Passport SSI, you won't have to implement your own user-authentication mechanism. Users authenticate with the SSI, which passes their identities to your site securely. Although Passport authenticates users, it doesn't grant or deny access to individual sites i.e. .NET Passport does only authentication not authroziation .

75

Passport simply tells a participating site who the user is. Each site must implement its own accesscontrol mechanisms based on the user's Passport User ID (PUID). To Implement .NET Passport Authentication We need to download the Microsoft .NET Passport SDK from the Microsoft Site and install it in our web server.

Chapter IV

TOP

GUI Application Development Using .NET Framework

TOP

Visual Studio Windows-based Applications


A Visual Studio Windows-based application is built around the .NET Framework, a rich set of classes that you can use to develop sophisticated applications. You can create Windows-based applications by using any programming language that works with the .NET Framework (Visual Basic, C#, C++, and many others) and .NET Framework debugging tools. Windows-based applications created by using .NET Framework classes offer other benefits. You can access operating-system services and take advantage of other benefits provided by your user's computing environment. You can access data by using ADO.NET.

76

Windows-based applications can make calls to methods exposed through XML Web services

.19 Windows Forms & Controls


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. 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. As we design and modify the user interface of our Windows Forms applications, we will need to add, align, and position controls. Controls are objects that are contained within form objects. Each type of control has its own set of properties, methods, and events that make it suitable for a particular purpose. We can manipulate controls in the designer and write code to add controls dynamically at run time. The web forms are used in a web based application whereas the windows forms are used within the company and its scope is very much limited. Create a Windows Form Application as follows, File->New->Project->Windows Form Application

Windows forms controls


Windows Forms controls based on the .NET Framework includes controls for Data display, Data binding

77

and navigation, Text editing, Information display (read-only), Web page display, Selection from a list, Graphics display, Value setting, Date setting, Dialog boxes. Some important controls which we use often in windows forms are: Combo Box: In the Combo Box we can add items to the list. In the item properties we need to add the elements to the list.From the collections we can choose one. DateTime Picker: We can add the Date and Time to the the windows form by means of DateTime Picker Control. By means of the value property we can change the date and time of the control. Data GridView: By means of the GridView we can bind the value from the DataBase to the DataGridView control. When we click the small icon near by the GridView control we can find choose the DataSource option. After that we need to give the Database,DataSource and the connection name. Data will then bind to the GridView control. ListBox: In the ListBox control we can add the items to the list. Its like grouping of similar items together. In the ListBox control when we click the small icon it will display Edit Item option. By means of

Edit Item Option we can add the elements to the list. ContextMenuStrip: In the ContextMenuStrip we can create menu. And also we can list sub elements inside the menu. It reduces the task of creating menu. GroupBox: By means of the Group Box control we can place other controls inside the Group Box control. Panel: By means of the Panel control we can place other controls inside the Panel control. The main difference between panel and group box control is Group Box provides a caption and border around a group of controls. Tree View: By means of tree view control. We can add items to the tree view control in a hierarchical order. ListView: Displays items in one of four different views. Views include text only, text with small icons, text with large icons, and a details view.

78

PictureBox: Displays graphical files, such as bitmaps and icons, in a frame.

.20

Crystal Report

Crystal Reports is an integral part of Visual Studio .NET and ships as a part of it. By making Crystal Reports a part of Visual Studio .NET suite, Microsoft has added one more useful tool to the Visual Studio family. Crystal Reports is the standard reporting tool for Visual Studio .NET used to display data of

presentation quality. You can display multiple-level totals, charts to analyze data, and much more in Crystal Reports. Creating a Crystal Report requires minimal coding since it is created in Designer interface. It is available as an integrated feature of Microsoft Visual Studio .NET, Borland Delphi, and C#Builder.
Crystal Reports allows users to graphically design data connections and report layout. In the Database Expert, users can select and link tables from a wide variety of data sources, including Excel spreadsheets, oracle databases, and local file system information. Fields from these tables can be placed on the report design surface, and can also be used in custom formulas, using Crystal's own syntax, which are then placed on the design surface. Both fields and formulae have a wide array of formatting options available, which can be applied absolutely or conditionally. The data can be grouped into bands, each of which can be split further and conditionally suppressed as needed. Crystal Reports also supports sub reports, graphing, and a limited amount of GIS functionality.

Advantages of Crystal Reports Some of the major advantages of using Crystal Reports are: Rapid report development since the designer interface would ease the coding work for the programmer. Can extend it to complicated reports with interactive charts and enhance the understanding of the business model. Exposes a report object model, can interact with other controls on the ASP.NET Web form. Can programmatically export the reports into widely used formats like .pdf, .doc, .xls, .html and .rtf.

79

Implementation Models
Crystal Reports need database drivers to connect to the data source for accessing data. Crystal Reports in .net support two methods to access data from a data source:

The Pull Method


When this model is used to access data from the data source, the database driver directly retrieves the data from the data source. This model does not require the developer to write code for creating a connection and retrieving data from the data source. It is the Crystal report that manages the SQL commands for connecting by using the specified driver.

The Push Method


When this model is used to access data from data source, the developer writes the code to connect to the data source and retrieve data. The data from the data source is cached in dataset and multiple crystal reports accesses data from the dataset. The performance can be optimized in this manner by using connection sharing and manually limiting the number of records that are passed on to the report.

Crystal Reports Types


Crystal Report Designer can load reports that are included into the project as well as those that are independent of the project.

Strongly-typed Report
When you add a report file into the project, it becomes a "strongly-typed" report. In this case, you will have the advantage of directly creating an instance of the report object, which could reduce a few lines of code, and cache it to improve performance. The related .vb file, which is hidden, can be viewed using the editor's "show all files" icon in the Solution Explorer.

Un-Typed Report
Those reports that are not included into the project are "un-typed" reports. In this case, you will have to create an instance of the Crystal Report Engine's "ReportDocument" object and manually load the report into it.

Steps involved in creating crystal reports: 1. File ->New->Project->Crystal Report 80

2. Select the standard option

3.Select the connection and give the table name.

4. Select the available fields

81

4. The report is generated as below

Output First Name Last Name Country

Kavi

Priya

India

82

.21
TOP

Components

Component is a set pre-compiled class, which is reusable.

COM (Component Object Model) technology in the Microsoft Windows-family of Operating Systems enables software components to communicate. COM is used by developers to create re-usable software components, link components together to build applications, and take advantage of Windows services. COM objects can be created with a variety of programming languages. Object-oriented languages, such as C++, provide programming mechanisms that simplify the implementation of COM objects. The family of COM technologies includes COM+, Distributed COM (DCOM) and ActiveX Controls. Microsoft provides COM interfaces for many Windows application programming interfaces such as Direct Show, Media Foundation, Packaging API, Windows Animation Manager, Windows Portable Devices, and Microsoft Active Directory (AD). COM is used in applications such as the Microsoft Office Family of products. For example COM OLE technology allows Word documents to dynamically link to data in Excel spreadsheets and COM Automation allows users to build scripts in their applications to perform repetitive tasks or control one application from another.
How Component can Improve Application Performance? CLR is a place where .Net Application codes get compiled. Whenever you made a request to ASP.NET page, the page gets compiled first and then is transferred to the user. The compilation process is also completed in two steps.

An IL (Intermediate Language) is generated and then this is handed over for JIT JIT (Just In Time) compilation which produces the machine code and our pages get displayed with
their dynamic content. The performance of our web application can be improved by creating pre-compiled libraries of IL which can then be handed over to JIT directly without having the inclusion of an extra process to make the conversion. This method is called componentization. Components are pre-compiled set of classes that have been developed in the form of DLL files and can then be included within our projects. This is also known as an assembly. Advantages of Component Improving Application Performance

83

Better Code Management and Maintenance

Example

1. Open the website 2. Click on Project Menu->Add Component --->Component Class 3. In the code file type the below code and debug the file.

using System; using System.Diagnostics; using System.ComponentModel; namespace InstConLib { /* InstanceControlLib Class controls the instance */ public class InstanceControl : Component { private string stProcName = null; /*constructor which holds the application name*/ public InstanceControl(string ProcName) { stProcName = ProcName; } public bool IsAnyInstanceExist() { /*process class GetProcessesByName() checks for particular process is currently running and returns array of processes with that name*/ Process[] processes = Process.GetProcessesByName(stProcName); if (processes.Length != 1) return false; /*false no instance exist*/ else return true; /*true mean instance exist*/ } } /*end of class*/ }/*end of namespace*/

4. Create another website and a console application 5. In the Program.cs file ( InstClient.cs ) enter the following code

using using using using

System; System.Collections.Generic; System.Linq; System.Text;

using InstConLib; namespace consoleusecom

84

class Program { static void Main(string[] args) { //First Object which looks for testApp.exe process //remember its not neccessary to give extention of

process

InstConLib.InstanceControl in1 = new InstConLib.InstanceControl("testApp"); if (in1.IsAnyInstanceExist()) Console.WriteLine("Already one instance is running"); else Console.WriteLine("No Instance running"); //Second Object which looks for Explorer.exe process //remember its not neccessary to give extention of process InstConLib.InstanceControl in2 = new InstConLib.InstanceControl("Explorer"); if (in2.IsAnyInstanceExist()) Console.WriteLine("Already one instance is running"); else Console.WriteLine("No Instance running"); Console.ReadLine(); } } }

Output No Instance running Already one instance is running

.22 Asynchronous Programming


Input/Output operations are normally slower than other processing operations. Synchronous programming is when threads need to wait until they can execute I/O routine has completed. When threads can continue to execute without waiting for an operation to complete, we say that threads can perform asynchronous I/O. Stated loosely, asynchronous programming is allowing some portions of code to be executed on separate threads. This is referred to as the Asynchronous Programming Model (APM).

85

Throughout the .NET Framework, many classes support using the APM by providing BeginXXX and EndXXX versions of methods. For example, the FileStream class that is defined in the System.IO namespace has a Read method that reads data from a stream. To support the APM model, it also supports BeginRead and EndRead methods. This pattern of using BeginXXX and EndReadXXX methods allows you to execute methods asynchronously. The real-world programming strength of the APM is that a single pattern can be used to asynchronously execute both compute-bound and I/O bound operations. This article purposes to describe the three "rendezvous" techniques that comprise the APM. This chapter will start by examining how to use the APM to perform an asynchronous computebound operation. The code given below is an example of the pattern of using BeginXXX and EndXXX methods to allow you to execute code asynchronously: To explain, the purpose of the example code above was to read some bytes (100) from a file stream asynchronously using the APM. First we have to construct a FileStream object by calling one of its constructors that accepts the System.IO.FileOptions argument. For this argument, we have to pass in the FileOptions.Asynchronous flag: this tells the FileStream object that we intend to perform asynchronous read and write operations against the file. Note that a flag is simply just an algorithm that indicates the status of an operation. In this case, the FileOptions.Asynchronous flag is set to a binary one. To synchronously read bytes from a FileStream, we'd call its Read method, which is prototyped as follows: public Int32 Read(Byte[] array, Int32 offset, Int32 count) The Read method accepts a reference to a Byte[] that will have its bytes filled with bytes from the file. The count argument indicates the number of bytes that we need to read. The bytes will be placed in an array (buffer) between offset and (offset + count - 1). Note because we are dealing with a buffer, it will have a length. The Read method returns the number of bytes actually read from the file. When we call the method, the read occurs synchronously. That is, the method does not return until the requested bytes have been read into the array.

86

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; namespace Asynchronous{ class Program { static void Main(string[] args) { byte[] buffer = new byte[100]; string filename = String.Concat(Environment.SystemDirectory, "\\ntdll.dll"); FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); IAsyncResult result = fs.BeginRead(buffer, 0, buffer.Length, null, null); int numBytes = fs.EndRead(result); fs.Close(); Console.WriteLine("Read {0} Bytes:", numBytes); Console.WriteLine(BitConverter.ToString(buffer)); Console.ReadLine(); } } }

Output
Read 100 Bytes: 4D-5A-90-00-03-00-00-00-04-00-00-00-FF-FF-00-00-B8-00-00-00-00-00-00-0040-00-00 -00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-0000-00-0 0-00-00-00-00-00-00-D0-00-00-00-0E-1F-BA-0E-00-B4-09-CD-21-B8-01-4C-CD21-54-68-69-73-20-70-72-6F-67-72-61-6D-20-63-61-6E-6E-6F-74-20-62-65

CHAPTER V

TOP

87

Distributed Application Development

.23

Web Services

Web services are the amalgamation of eXtensible Markup Language (XML) and HyperText Transfer Protocol HTTP that can convert our application into a Web-application, which publish its function or message to the rest of the world. In other words, we can say, web services are just Internet Application Programming Interfaces (API) that can be accessed over a network, such as Internet and intranet, and executed on a remote system hosting the requested services. Web-applications are simple applications that run on the web. Web services are browsers and operating system independent service, which means it, can run on any browser without the need of making any changes. Web Services take Web-applications to the Next Level. In short,

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

Small Units of Code Web services are small units of code designed to handle a limited set of tasks. An example of a web service can be a small program designed to supply other applications with the latest stock exchange prices. Another example can be a small program designed to handle credit card payment. XML Based Web Protocols Web services use the standard web protocols HTTP, XML, SOAP, WSDL, and UDDI. HTTP HTTP (Hypertext Transfer Protocol) is the World Wide Web standard for communication over the Internet. HTTP is standardized by the World Wide Web Consortium (W3C). 88

XML XML (eXtensible Markup Language) is a well known standard for storing, carrying, and exchanging data. XML is standardized by the W3C. SOAP SOAP (Simple Object Access Protocol) is a lightweight platform and language neutral communication protocol that allows programs to communicate via standard Internet HTTP. SOAP is standardized by the W3C. WSDL WSDL (Web Services Description Language) is an XML-based language used to define web services and to describe how to access them. WSDL is a suggestion by Ariba, IBM and Microsoft for describing services for the W3C XML Activity on XML Protocols. UDDI UDDI (Universal Description, Discovery and Integration) is a directory service where businesses can register and search for web services. UDDI is a public registry, where one can publish and inquire about web services. Benefits of Web Services Easier to communicate between applications Easier to reuse existing services Easier to distribute information to more consumers Rapid development

An

asp.net

web

service

is

class

we

write

that

inherits

from

the

class

System.Services.WebService.This class provides a wrapper for our service code. In this way; we are free to write web service in the same way we would write any other class and method. Following is the Web Service; it exposes two methods (Add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services uses the .asmx extension. Note that a method exposed as a Web Service has the WebMethod attribute. Save this file as filename.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebServices). In the webservice include the add method.
using System;

89

using System.Collections.Generic; using System.Linq; Using System. Web; using System.Web.Services; using System.Xml.Serialization; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http://localhost/MyWebServices")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { public WebService () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public int Add(int a, int b) { return a + b; } [WebMethod] public string HelloWorld() { return "Hello World"; } }

To test a Web Service, it must be published. A Web Service can be published either on an intranet or the Internet. We will publish this Web Service on IIS running on a local machine. Let's start with configuring the IIS.

Open Start->Settings->Control Panel->Administrative tools->Internet Services Manager. Expand and right-click on [Default Web Site]; select New ->Virtual Directory. The Virtual Directory Creation Wizard opens. Click Next. 90

The "Virtual Directory Alias" screen opens. Type the virtual directory namefor example, MyWebServicesand click Next. The "Web Site Content Directory" screen opens. Here, enter the directory path name for the virtual directoryfor example, c:\MyWebServicesand clicks next. The "Access Permission" screen opens. Change the settings as per your requirements. Let's keep the default settings for this exercise. Click the Next button. It completes the IIS configuration. Click Finish to complete the configuration.

If it does not work, try replacing localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure IIS and Virtual Directory. To test our Web Service, copy FirstService.asmx in the IIS virtual directory created above (C:\MyWebServices). Open the Web Service in Internet Explorer (http://localhost/MyWebServices/WebService.asmx). It should open your Web Service page. The page should have links to two methods exposed as Web Services by our application.

Testing the Web Service As we have just seen, writing Web Services is easy in the .NET Framework. Writing Web Service consumers is also easy in the .NET framework; As said earlier, we will write two types of service consumers, one Web- and another Windows application-based consumer. Let's write our first Web Service consumer. Web-Based Service Consumer Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the Web Service (c:\MyWebServices\WebApp.aspx). This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web Services. WebApp.aspx <%@ Page Language="C#" %> <script runat="server"> void runSrvice_Click(Object sender, EventArgs e) { FirstService mySvc = new FirstService(); Label1.Text = mySvc.SayHello(); Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString();

91

} </script> <html> <head> </head> <body> <form runat="server"> <p> <em>First Number to Add </em>: <asp:TextBox id="txtNum1" runat="server" Width="43px">4</asp:TextBox> </p> <p> <em>Second Number To Add </em>: <asp:TextBox id="txtNum2" runat="server" Width="44px">5</asp:TextBox> </p> <p> <strong><u>Web Service Result -</u></strong> </p> <p> <em>Hello world Service</em> : <asp:Label id="Label1" runat="server" Font-Underline="True">Label</asp:Label> </p> <p> <em>Add Service</em> : & <asp:Label id="Label2" runat="server" Font-Underline="True">Label</asp:Label> </p> <p align="left"> <asp:Button id="runSrvice" onclick="runSrvice_Click" runat="server" Text="Execute"></asp:Button> </p> </form> </body> </html>

After the consumer is created, we need to create a proxy for the Web Service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a Web Service that has 92

been added. Here are the steps to be followed: Create a proxy for the Web Service to be consumed. The proxy is created using

the wsdl utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy automatically for you when the reference for the Web Service is added. Create a proxy for the Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service. c:> WSDL http://localhost/MyWebServices/ FirstService.asmx? WSDL c:> csc /t:library FirstService.cs Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). IIS looks for the proxy in this directory. Create the service consumer, which we have already done. Note that I have instantiated an object of the Web Service proxy in the consumer. This proxy takes care of interacting with the service. Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx). Windows Application-Based Web Service Consumer Writing a Windows application-based Web Service consumer is the same as writing any other Windows application. The only work to be done is to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the Web Service. This application creates a Web Service object (of course, proxy) and calls the SayHello and Add methods on it.
WinApp.cs using System; using System.IO; namespace SvcConsumer{ class SvcEater { public static void Main(String[] args) { FirstService mySvc = new FirstService(); Console.WriteLine("Calling Hello World Service: " + mySvc.SayHello());

93

Console.WriteLine("Calling Add(2, 3) Service: " + mySvc.Add(2, 3).ToString()); } } }

Compile it using c:>csc /r:webservicename.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the Web Service. To check the web service created with console application, follow the steps : Write the above in a console application Right click on Solution Explorer, choose Add Web Reference In Add Web Reference window, choose Web Services on the local machine Type the URL as http://localhost/webservice/webservicename.asmx and deploy it

Output:

94

.24 WCF (Windows Communication Foundation)


TOP

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristic of WCF.WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. Windows communication foundation service is primarily based on the

System.ServiceModel namespace. This is the Programming interface to the developers. The System.ServiceModel namespace is very rich in its design so that it allows much easier programming interface. Before getting into first programming sample of a WCF service, lets look into the programming model of the WCF service.

95

Programming Model: The Programming model mainly constitutes of the End points. The endpoint is the basic unit of communication in Windows Communication Foundation (WCF). Each endpoint is made up of three elements: an address, a binding, and a contract, Address Binding Contracts Address: Address specifies the info about where can I find my service. Binding: Binding specifies the info that how can I interact with my service. Contracts: Contracts specifies the info that how my service is implemented and what it can offer me. Now lets look into the various components that constitute the WCF service.

Address: Every WCF endpoint must have an address so that other end points can initialize the communication. Each Address consists of an Uri and Address properties. The address properties consist of an Identity and optional Headers. The endpoints can be added programmatically or in configuration files. The configuration files provide the flexibility of changing the endpoints in the future without a need to recompile the application and deploying it. Addresses will be of the format http://localhost:8000/HelloWorld. Binding: Bindings describe how the endpoints communicate with the external world. The bindings specify the following: The protocol stack. The transport protocol Encoding. Contracts: 96

A contract specifies what the endpoint communicates. What the service can offer. It is a collection of messages. Called message exchange. (MEX) Open Visual Studio and create a new WCF Service Application:

In the existing solution, there is a Web.config file. Instead of editing it at this moment, it is recommended to delete it since we wont be using it for now. At the debugging stage, IDE will automatically generate a new one with just the debugging settings present. As we look through the existing code, we can see that there is a lot of sample data that might or might not be useful for us. Now we have a clean Service1 class and a clean IService1 interface. NOTE: Keep the default names for the service and related components as it is. Now, my service class looks like this: Using System; Using System.Runtime.Serialization; Using System.ServiceModel; Using System.ServiceModel.Web; namespace REST_TEST { public class Service1 : IService1 {

97

} } And the interface for the above mentioned service looks like this: using System; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; namespace REST_TEST { [ServiceContract] public interface IService1 { } }

Now, in the IService1 interface define a sample method, called GetDateTime that will return a string. The only thing that we should add to it is an additional set of attributes that will control how this method will be used by the WCF service. So we get, [ServiceContract] public interface IService1 { [WebGet(UriTemplate="/")] [OperationContract] string GetDateTime(); } With the help of WebGet, the method will be available through a REST call. The UriTemplate defines the access point, this being set to root. Therefore, when testing the service in the browser, the address to call the GetDateTime method will be http://localhost:3660/Service1.svc/. We can also modify this to something else, for example /GetDateTime 1. [WebGet(UriTemplate="/GetDateTime")]

98

This way, when we will access the service by its root identifier, we will get an Endpoint not found error (since there is no endpoint defined for that). However, if we access http://localhost:3660/Service1.svc/GetTimeDate , we will call the needed method and get the correct output. OperationContract specifies that the method is a part of an operation that the service is bound to via a contract. We need to have this attribute present in the method definition (inside the interface) in order to be able to call it from the current service, Service1.svc. Now lets work on the actual method. public string GetDateTime() { return DateTime.Now.ToString(); } This will return the current date and time. Due to the nature of the service, the data will be serialized automatically when returned; therefore at this point we dont have to worry about manual serialization. Before going any further, we need to enable metadata publishing for the service. To do this, right click on Service1.svc in the Solution Explorer and select View Markup:

Once there, add the following property to the existing set: Factory="System.ServiceModel.Activation.WebServiceHostFactory" Now, right click on the Service1.svc in Solution Explorer once again and select View in Browser. Once the browser opens, we should see a response similar to this: 99

This is absolutely normal, since we did not define an endpoint for the root location. Now, in the address bar, right after the service name, type /GetDateTime. When we navigate to that address, here is what we should get Output:

.25 Remote Client and Server Application


TOP

Remote Objects, Clients, and Servers Before stepping into the details of the .NET Remoting architecture, this section looks briefly at a remote object and a client-server application that uses this remote object. After that the required steps and options are discussed in more detail 100

Remote Objects Remote objects are required for distributed computing. An object that should be called remotely from a different system must be derived from System.MarshalByRefObject. MarshalByRefObject objects are confined to the application domain in which they were created. This means that they are never passed across application domains; instead, a proxy object is used to access the remote object from another application domain. The other application domain can live inside the same process, in another process, or on another system. A remote object has distributed identity. Because of this, a reference to the object can be passed to other clients, and they will still access the same object. The proxy knows about the identity of the remote object. The MarshalByRefObject class has, in addition to the inherited methods from the Object class, methods to initialize and to get the lifetime services. The lifetime services define how long the remote object lives. To see .NET Remoting in action, create a Class Library for the remote object. The class Hello derives from System.MarshalByRefObject. In the constructor a message is written to the console that provides information about the objects lifetime. In addition, add the method Greeting() that will be called from the client. To distinguish easily between the assembly and the class in the following sections, give them different names in the arguments of the method calls used. The name of the assembly is RemoteHello, and the class is named Hello: File->New->Project->Class library using System; namespace Wrox.ProCSharp.Remoting { public class Hello : System.MarshalByRefObject { public Hello() { Console.WriteLine("Constructor called"); } public string Greeting(string name) { Console.WriteLine("Greeting called"); return "Hello, " + name; } } 101

The Server
For the server, create a new C# console application called HelloServer. To use the TcpServerChannel class, you have to reference the System.Runtime.Remoting assembly. Its also required that you reference the RemoteHello assembly that was created earlier.In Main () method, an object of type System.Runtime.Remoting.Channels.Tcp.TcpServerChannel is created with the port number 8086. This channel is registered with the System.Runtime.Remoting .Channels.ChannelServices class to make it available for remote objects. The remote object type is registered by calling the methodRemotingConfiguration.RegisterWellKnownServiceType(). In the example, the type of the remote object class, the URI used by the client, and a mode are specified. The mode WellKnownObject.SingleCall means that a new instance is created for every method call; in the sample application no state is held in the remote object. After registration of the remote object, it is necessary to keep the server running until a key is pressed: File->New->Project->Console Application using System; using System.Collections.Generic; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Wrox.ProCSharp.Remoting { class Program { static void Main() { TcpServerChannel channel = new TcpServerChannel(8086); ChannelServices.RegisterChannel(channel, true); RemotingConfiguration.RegisterWellKnownServiceType( typeof(Hello), "Hi", WellKnownObjectMode.SingleCall); Console.WriteLine("Press return to exit"); Console.ReadLine(); } } }

102

The Client The client is again a C# console application: HelloClient. With this project, you also have to reference the System.Runtime.Remoting assembly so that the TcpClientChannel class can be used. In addition, you have to reference the RemoteHello assembly. Although the object will be created on the remote server, the assembly is needed on the client for the proxy to read the type information during runtime. In the client program, create a TcpClientChannel object thats registered in ChannelServices. For the TcpChannel, you can use the default constructor, so a free port is selected. Next, the Activator class is used to return a proxy to the remote object. The proxy is of type System.Runtime.Remoting.Proxies .__TransparentProxy. This object looks like the real object because it offers the same methods. The transparent proxy uses the real proxy to send messages to the channel: File->New->Project->Console Application using System; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Wrox.ProCSharp.Remoting { class Program { static void Main() { Console.WriteLine("Press return after the server is started"); Console.ReadLine(); ChannelServices.RegisterChannel(new TcpClientChannel(), true); Hello obj = (Hello)Activator.GetObject( typeof(Hello), "tcp://localhost:8086/Hi"); if (obj == null) { Console.WriteLine("could not locate server"); return; } for (int i=0; i< 5; i++) { Console.WriteLine(obj.Greeting("Christian")); } } } }

103

Now you can start the server and then the client program

Output: Server

Client

104

.26 Message Queuing


TOP

Before diving into programming Message Queuing, this section discusses the basic concepts of messaging and compares it to synchronous and asynchronous programming. With synchronous programming, when a method is invoked, the caller has to wait until the method is completed. With asynchronous programming, the calling thread starts the method that runs concurrently. Asynchronous programming can be done with delegates, class libraries that already support asynchronous methods with both synchronous and asynchronous programming, the client and the server must be running at the same time. Although Message Queuing operates asynchronously, because the client (sender) does not wait for the server (receiver) to read the data sent to it, there is a crucial difference between Messaging Queuing and asynchronous programming: Message Queuing can be done in a disconnected environment. At the time data is sent, the receiver can be offline. Later, when the receiver goes online, it receives the data without the sending application to intervene. You can compare connected and disconnected programming with talking to someone on the phone and sending an e-mail. When talking to someone on the phone, both participants must be connected at the same time. The communication is synchronous. With an e-mail, the sender isnt sure when the e-mail will be dealt with. People using this technology are working in a disconnected mode. Of course the e-mail may never be dealt with - it may be ignored. Thats in the nature of disconnected communication. To avoid this problem, it is possible to ask for a reply to confirm that the e-mail has been read. If the answer doesnt arrive within a time limit, you may be required to deal with this exception. This is also possible with Message Queuing. In some ways Message Queuing is e-mail for application-to-application communication, instead of person-to-person communication. However, this gives you a lot of features that are not available with mailing services, such as guaranteed delivery, transactions, confirmations, express mode using memory, and so on. As we see in the next section, Message Queuing has a lot of features useful for communication between applications

Creating a Message Queue Message queues can be created programmatically with the Create () method of the MessageQueue class. With the Create () method, the path of the new queue must be passed. The path consists of the host name where the queue is located 105 and the name of the queue.

After the Create () method is invoked, properties of queue can be changed. For example, using the Label property, the label of the queue is set to Demo Queue. The sample program writes the path of the queue and the format name to the console. The format name is automatically created with a UUID that can be used to access the queue without the name of the server:

using System; using System.Messaging; namespace MessageQueuingInDot { class Program { static void Main() { using (MessageQueue queue = MessageQueue.Create(@".\MyNewPublicQueue")) { queue.Label = "Demo Queue"; Console.WriteLine("Queue created:"); Console.WriteLine("Path: {0}", queue.Path); Console.WriteLine("FormatName: {0}", queue.FormatName); } } } }

.27 Message Queuing in Client and Server applications


TOP

Creating a Message Queue (Client program) In C#, we can also create Message Queues programmatically using the Create() method of MessageQueue class. With Create () method, the path of the new queue must be passed. The path consists of the hostname where the queue is located and the name of the queue. Now we will write an example, which will create on the localhost that is 'MynewPublicQueue'. To create a private queue, the path name must include private$. For example: \private$\MynewPrivateQueue. Once the create () method is invoked, properties of the queue can be changed. Using label property, 106

the label of the queue is set to "First Queue". The following program writes the path of the queue and the format name to the console. The format name is automatically created with a UUID (Universal Unique Identifiers) that can be used to access the queue without the name of the server.

using System.Messaging; namespace FirstQueue { class Program { static void Main(string[] args) { using (MessageQueue queue = MessageQueue.Create(@".\Private$\FirstQueuessnsv")) { queue.Label = "Demo Queue"; Console.WriteLine("Queue created:"); Console.WriteLine("Path: {0}", queue.Path); Console.WriteLine("FormatName: {0}", queue.FormatName); } Console.ReadLine(); } } }

Sending a Message (Server program) By using the Send method of the MessageQueue class, you can send the message to the queue. The object passed as an argument of the Send () Method is serialized queue. The Send () method is overloaded so that a Label and a MessageQueueTransaction object can be passed. Now we will write a small example to check if the queue exists and if it doesn't exist, a queue is created. Then the queue is opened and the message "First Message" is sent to the queue using the Send () method.

The path name specifies "." for the server name, which is the local system. Path name to private queues only works locally. Add the following code in the Visual Studio C# console environment.

Using System. Messaging;

107

namespace sending message { class Program { static void Main(string[] args) { try { if (!MessageQueue.Exists(@".\Private$\FirstQueuessnsv")) { MessageQueue.Create(@".\Private$\FirstQueuessnsv"); } MessageQueue queue = new MessageQueue(@".\Private$\FirstQueuessnsv"); queue.Send("First Message ", " Label "); } catch (MessageQueueException ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } }

Build the application. Now we can view the message in the Component Management admin tool[control panel->administrative tools->service and application and message queuing->private queue-<Queue name>] as shown in figure above. By opening the message and selecting the body tab of the dialog, we can see the message was formatted using XML.

.28 Web Services Enhancement (WSE)


TOP

WSE 3.0 simplifies the development and deployment of secure Web services. It enables developers and administrators to apply security policies to Web services running on the .NET Framework 2.0. Using WSE 3.0, Web services communication can be signed and encrypted using Kerberos tickets, X.509 certificates and other custom binary and XML-based security tokens. In addition username/password credentials can be used for authentication purposes. An enhanced security model provides a policy-driven foundation for securing Web services. WSE also supports 108

the ability to establish a trust-issuing service for retrieval and validation of security tokens, as well as the ability to establish more efficient long-running secure communication via secure conversations.

The WS-Security Specification WS-Security describes independent mechanisms to: describe assertions made about security determine if a message has been altered (message integrity) Prevent a message from being read by an unauthorized party (message confidentiality).

These mechanisms can be used to provide end-to-end security for a message. Unlike SSL which only provides encryption between two points, message security must apply to all the intermediates through which a message flows. Consider an order that flows from an order entry application, to an inventory control system that checks for availability, to a billing system that processes the order, to a fulfillment system that ships it. Your credit card information should be encrypted so that only the billing system can read it. The inventory control system needs only to know the items requested and their quantity. If each of these intermediates is a separate division of a company, or a separate company, this message is said to cross a trust domain. Trust is the degree to which one entity believes the claims of another, or allows another to undertake actions on its behalf. Since different companies or divisions trust each other to varying degrees, the security models built with WSSecurity have to allow for varying levels of trust. In our mortgage example, the Credit Agency, the Bank, and the Loan officer are different trust domains. The level of trust between the Mortgage decision service and the Bank Portal is much higher, than the level of trust between the Credit Agency and the Bank, or the Bank and the Loan officer. Each of these mechanisms uses a security token to represent a security claim. For example, an X509 certificate represents an association between a public key and an identity that is verified by some third party. An X509 security token represents this association. If you know how WSE 2.0 implements these security tokens, you will understand how WSE 2.0 implements WS-Security. Each security token is associated with a particular type of security protocol such as username and password, X509 certificates, Kerberos or SAML. Each of these protocols has an associated specification. For example, X509 certificates are described in the Web Services Security X509 Certificate Token Profile specification. These tokens and the associated information are placed in the SOAP headers associated with the SOAP message as described in previous articles.

109

It is also important to be clear about what WS-Security and its associated specifications do not do. The specification tells you how to place a security token such as username and password, or X509 certificate in a SOAP message. How you use this token to authenticate a user is up to you. You can decide to store your passwords in plain text in a file that is available to everyone. You can decide to ignore an X509 certificate that is present in a given message. Although the specification recommends you do not do so, you can accept the X509 certificate even if you know it is no longer valid. While the specification allows you to implement different trust levels for different trust domains, it does not tell you how to determine those different levels of trust. You decide how the security protocols you use are implemented. WS-Security does not tell you how to develop a security model. While a discussion of security models is beyond the scope of these articles, one example should make clear their importance. Any sophisticated electronic commerce application has to deal with non-repudiation. When you make a purchase at a store's physical location, and sign a credit card slip, that signature can be used to prevent you from repudiating, or claiming you never made that transaction. WS-Security tells you how to place a digital signature in a message, but it does not tell you how to implement nonrepudiation in your application.

WSE Policy Framework The WSE policy framework describes constraints and requirements for communicating with an ASMX (ASP.NET Web services framework) or WSE Web service. Policy is a deployment-time concept. An instance of a policy is translated into run-time components that apply the requirements at the sender or enforce them at the receiver. This process of translation, referred to as policy compilation, takes place before any messages are exchanged between the client and the service. The atomic run-time components are called SOAP filters and operate at the level of a single SOAP envelope. Their primary responsibility is to inspect or transform the SOAP envelope. For example, a SOAP filter on the sender may digitally sign the message and add a Security header to it, as defined in the WS-Security specification. Similarly, a SOAP filter on the receiver may extract the Security header from the SOAP envelope and require that the digital signature it contains be successfully verified before dispatching the message to the application code.

Using the WSE Router One of the benefits of using WSE router with a distributed application is that a computer hosting a Web service can be taken offline for maintenance without modifying either the client code 110

or its configuration. An administrator of the computer hosting WSE router can make all the changes needed to redirect the SOAP messages to another computer. To do so, an administrator prepares a backup computer to be brought online to host the Web service, while the router continues to delegate SOAP messages to the primary computer. Then the administrator prepares a Web.config file that specifies the file containing the referral cache and a new referral cache containing the URL for the backup computer. A referral cache is an XML file that contains the ultimate destination for URLs received by the router. Then, when the primary computer is taken offline, the Web.config and referral cache are placed on the computer hosting the router. Subsequent SOAP messages are then dynamically routed to the backup computerall unbeknownst to the client application, which is still sending SOAP messages to the router. The following graphic depicts sending SOAP messages to a WSE router, which delegates the SOAP message to another Web server based on the contents of a referral cache. In this graphic, the referral cache is configured to send the SOAP message to Web server B, but the referral cache could be modified to send it to Web server C.

.29 LINQ (Language-Integrated Query)


TOP

LINQ stands for Language Integrated Query. LINQ is a data querying methodology which provides querying capabilities to .Net languages with syntax similar to SQL query. LINQ has a set of querying operators that can be used to query in memory object collection, Sql database, XML, etc. LINQ processing engine will then convert the LINQ query to native query specific to the database to execute against the datasource. Since, the querying feature is integrated with the language; one can build an efficient query based on the language of their choice.

We use the term language-integrated query to indicate that query is an integrated feature of the developer's primary programming languages (for example, Visual C#, Visual Basic). Language-integrated query allows query expressions to benefit from the rich metadata, compiletime syntax checking, static typing and IntelliSense that was previously available only to imperative code. Language-integrated query also allows a single general purpose declarative query facility to be applied to all in-memory information, not just information from external sources.

Example 1 111

To see language-integrated query at work, we'll begin with a simple program that uses the standard query operators to process the contents of an array:
using System; using System.Linq; using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; IEnumerable<string> query = from s in names where s.Length == 5 orderby s select s.ToUpper(); foreach (string item in query) Console.WriteLine(item); } }

Output: BURKE DAVID FRANK Explanation of language-integrated query in the first statement of our program. IEnumerable<string> query = from s in names where s.Length == 5 Orderby s select s.ToUpper(); The local variable query is initialized with a query expression. A query expression operates on one or more information sources by applying one or more query operators from either the standard query operators or domain-specific operators. This expression uses three of the standard query operators: Where, OrderBy, and Select. Example 2

112

1. Create a new website and add a class by right clicking on the solution explores and Add New Item. Name the classname as Location.cs 2. Enter the code as:
using System; using System.Collections.Generic; using System.Web; public class Location { // Fields private string _country; private int _distance; private string _city; // Properties public string Country { get { return _country; } set { _country = value; } } public int Distance { get { return _distance; } set { _distance = value; } } public string City { get { return _city; } set { _city = value; } } }

3. Source file code is :


<%@ Page Language="C#" CodeFile="Step2.aspx.cs" Inherits="Step2" %> <html> <body> <form id="form1" runat="server"> <h1>Cities and their Distances</h1> <asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None"> <Columns> <asp:BoundField HeaderText="Country" DataField="Country" /> <asp:BoundField HeaderText="City" DataField="City" /> <asp:BoundField HeaderText="Distance from Seattle" DataField="Distance" /> </Columns> <FooterStyle BackColor="Tan" /> <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />

113

<HeaderStyle BackColor="Tan" Font-Bold="True" /> <AlternatingRowStyle BackColor="PaleGoldenrod" /> </asp:GridView> </form> </body> </html>

4. Enter the following in code behind file: 5. 6. 7. 8.


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; public partial class Step2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<Location> cities = new List<Location> {

new Location { City="London", Distance=4789, Country="UK" }, new Location { City="Amsterdam", Distance=4869, Country="Netherlands" }, new Location { City="San Francisco", Distance=684, Country="USA" }, new Location { City="Las Vegas", Distance=872, Country="USA" }, new Location { City="Boston", Distance=2488, Country="USA" }, new Location { City="Raleigh", Distance=2363, Country="USA" }, new Location { City="Chicago", Distance=1733, Country="USA" }, new Location { City="Charleston", Distance=2421, Country="USA" }, new Location { City="Helsinki", Distance=4771, Country="Finland" }, new Location { City="Nice", Distance=5428, Country="France" }, new Location { City="Dublin", Distance=4527, Country="Ireland" } }; GridView1.DataSource = from location in cities where location.Distance > 1000 orderby location.Country, location.City

114

select location; } } GridView1.DataBind();

5. Compile and Run the application Output Cities and their Distances Country City Distance from Seattle Finland Helsinki 4771 France Nice 5428 Ireland Dublin 4527 Netherlands Amsterdam 4869 UK London 4789 USA Boston 2488 USA Charleston 2421 USA Chicago 1733 USA Raleigh 2363

List View and Paging with Data Pager

ASP.NET 3.5 includes two new data controls, namely, ListView and DataPager. The new and improved ListView control included as part of ASP.NET 3.5 support all CRUD (Create, Read, Update, Delete) operations. It also supports paging and sorting of data. We can use the new DataPager control to implement paging functionality to our data controls seamlessly. The ListView control uses template for displaying data. However, it supports many additional templates that allow for more scenarios when working with our data. The ListView control can be binded to the SQL. LayoutTemplate - The root template that defines a container object, such as a table, div, or span element, that will contain the content defined in the ItemTemplate or GroupTemplate template. It might also contain a DataPager object. ItemTemplate - Defines the data-bound content to display for individual items. ItemSeparatorTemplate - Defines the content to render between individual items. GroupTemplate - Defines a container object, such as a table row (tr), div, or span element, that will contain the content defined in the ItemTemplate and EmptyItemTemplate templates. The number of 115

items that are displayed in a group is specified by the GroupItemCount property. GroupSeparatorTemplate - Defines the content to render between groups of items. EmptyItemTemplate - Defines the content to render for an empty item when a GroupTemplate template is used. For example, if the GroupItemCount property is set to 5, and the total number of items returned from the data source is 8, the last group of data displayed by the ListView control will contain three items as specified by the ItemTemplate template, and two items as specified by the EmptyItemTemplate template. EmptyDataTemplate - Defines the content to render if the data source returns no data. SelectedItemTemplate - Defines the content to render for the selected data item to differentiate the selected item from other items. AlternatingItemTemplate - Defines the content to render for alternating items to make it easier to distinguish between consecutive items. EditItemTemplate - Defines the content to render when an item is being edited. The EditItemTemplate template is rendered in place of the ItemTemplate template for the data item that is being edited. InsertItemTemplate - Defines the content to render to insert an item. The InsertItemTemplate template is rendered in place of an ItemTemplate template at either the start or at the end of the items that are displayed by the ListView control. You can specify where the InsertItemTemplate template is rendered by using the InsertItemPosition property of the ListView control. Data Pager DataPager Web control is used to page data and display navigation controls for data-bound controls that implement the IPageableItemContainer interface.ListView implements the IPageableItemContainer and will use DataPager to support Paging. Here we are using a database table ds with a column name. File->New->Web Site In the source file type the below code:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:catConnectionString2 %>" SelectCommand="SELECT * FROM [ds]"></asp:SqlDataSource> <asp:ListView ID="ListView1" runat="server" DataKeyNames="names" DataSourceID="SqlDataSource1">

116

<LayoutTemplate> <asp:DataPager ID="dpListView" runat="server" PageSize="5"> <Fields> <asp:NumericPagerField ButtonType="Button" NextPageText="more.." /> </Fields> </asp:DataPager> <div ID="itemPlaceholderContainer" runat="server" style="font-family: Verdana, Arial, Helvetica, sans-serif;"> <span ID="itemPlaceholder" runat="server" /> </div> <div style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;"> </div> </LayoutTemplate> <ItemTemplate> <span style="background-color: #DCDCDC;color: #000000;">Name: <asp: Label ID="EmpIDLabel3" runat="server" Text='<%# Eval ("names") %>' /> <br /> <br /> </span> </ItemTemplate> </asp:ListView>

Output

117

CHAPTER VI
Developing database Applications using ADO.NET and XML

TOP

.30 XML
XML (eXtensible Markup Language): A markup language for organizing information in text files. XML File: A text file that contains information organized in a structure that meets XML standards.

Main features of XML XML files are text files, which can be managed by any text editor. XML is very simple, because it has less than 10 syntax rules. XML is extensible, because it only specifies the structural rules of tags. No specification on tags them self.

Advantages of XML XML provides a basic syntax that can be used to share information between different kinds of computers, different applications, and different organizations. XML data is stored in plain text format. This software- and hardware-independent way of storing data allows different

118

incompatible systems to share data without needing to pass them through many layers of conversion. This also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing any data. XML provides a gateway for communication between applications, even applications on wildly different systems. As long as applications can share data (through HTTP, file sharing, or another mechanism), and have an XML parser, they can share structured information that is easily processed. It supports Unicode, allowing almost any information in any written human language to be communicated. It can represent common computer science data structures: records, lists and trees. Its self-documenting format describes structure and field names as well as specific values. XML is heavily used as a format for document storage and processing, both online and offline. The hierarchical structure is suitable for most (but not all) types of documents.

It is platform-independent, thus relatively immune to changes in technology How to create your first XML file. 1. Use any text editor to enter the following lines of text into a file:
<? Xml version="1.0" <p>Hello world! </p>

encoding="UTF-8?>

2. Save this file with name: "hello.xml". We have successfully created an XML file. The <? xml ...?> statement is called the Processing Instruction. Every XML file must contain one "xml" processing instruction at the beginning of the file to declare that this file is an XML file. Version - A required attribute that specifies the version of the XML standard this XML file conforms to. Currently, there are two versions of the XML standard available: 1.0 and 1.1. Encoding - An optional attribute that specifies the character encoding schema used in this XML file. Currently, there are many encodings supported by most XML applications: UTF8, UTF-16, ISO-10646-UCS-2, ISO-10646-UCS-4, and ISO-8859-1... ISO-8859-9, ISO2022-JP, Shift_JIS, EUC-JP.

119

.31 XML Schema


TOP

What is XML Schema? XML Schema is an XML schema language recommended by W3C (World Wide Web Consortium) in 2001. An XML schema is a set of rules to which an XML document must conform in order to be considered 'valid' according to that schema. An XML schema language is a set of rules on how to write an XML schema. An XML Schema describes the structure of an XML document. What is XSD? XSD stands for XML Schema Definition. An XML schema document written in XML Schema is called XSD and typically has the filename extension ".xsd". Formally, XML Schema and XSD refer to two different things: XML Schema refers to the schema language and XSD refers to a schema document written in XML Schema. But XML Schema is sometimes informally referenced as XSD. Creating Schema Documents - "schema" Element We have two options 1. empty_default_namespace.xsd - Using the default namespace:
<?xml version="1.0"?> <schema xmlns="http://www.w3.org/2001/XMLSchema"> </schema>

2. empty_xs_namespace.xsd - Using a namespace prefix:


<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> </xs:schema>

Using a namespace prefix is the recommended option.

Declaring Root Elements - "element" Element Every XML document must have a root element. So the first thing we need to do in a schema is declare a root element for the conforming XML documents. Rule 1. A schema must have at least one Element Declaration Component to declare a root element for the conforming XML document. Rule 2. The XML representation of an Element Declaration Component is an "element" element, which must have one attribute called "name" to provide the element name for the conforming XML document. 120

Rule 3. The namespace of all elements used in the XML representation must be from the schema namespace, 'http: www.w3.org/2001/XMLSchema'.

A simple schema example represented as an XML document, word.xsd <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="word"/> </xs:schema>

It declares that the conforming XML document must have a root element called "word" Example 1: Let's look at a simple example of XSD (a XML schema written in XML Schema language). Here is the content of the XSD example file, hello.xsd: <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="p" type="xsd:string"/> </xsd:schema> Code Explanation :

This XSD file is a true XML document with the root element named as "schema". This XSD file contains one "Element Declaration" statement <element ...>. The "Element Declaration" statement declares that the conforming XML documents must have a root element named as "p".

The "Element Declaration" statement also declares that the root element "p" should have content of "string" type.

Obviously, hello.xsd is a very simple XML schema. Writing an XML document that conforms to hello.xsd is easy. There is an example, hello.xml

<?xml version="1.0"?> <p>Hello world!</p>


121

Example 2
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

.32 XSLT (Extensible Style sheet Language Transformations) TOP


XSLT is XML based scripting language applies on XML files for data transformation. (OR) XSLT is a language that allows you to write a stylesheet to describe rules for transformation a source XML document into a result text document. (OR) Extensible Stylesheet Language Transformations or XSLT is a language that allows you to transform XML documents into XML, HTML, XHTML, or plain text documents. (OR) Example 1 1. Create a website and add an XML file with code as below
<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet type="text/xsl" href="XSLTFile.xslt"?> <bookList> <book id="1"> <title>C Sharp</title> </book> <book id="2"> <title>.net</title> </book> <book id="3"> <title>Java</title> </book> </bookList>

2. Add an XSLT file and enter the code 122

<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-resultprefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template>

<xsl:template match="/"> <html> <body> <h2>Books</h2> <table border="1"> <tr bgcolor #bc03d6"> <th>Title</th> </tr> <xsl:for-each select="bookList/book"> <tr> <td> <xsl:value-of select="title"/> </td>

</tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

Output

.33
TOP

Books

Title C Sharp .net Java

Example 2 123

1. Create a website and add an XML file with code as below <?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet type="text/xsl" href="XSLTFile4.xslt"?> <!-- Edited by XMLSpy --> <catalog> <cd> <name>Rose</name> <color>Red</color> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <name>Jasmine</name> <color>White</color> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd> </catalog>

Add an XSLT file and enter the code


<?xml version="1.0" encoding="iso-8859-1"?> <!-- Edited by XMLSpy --> <xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2 style="Margin-left=55px;">My Flower Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Name</th> <th>Color</th> <th>Country</th> <th>Company</th> <th>Price</th> <th>Year</th> </tr>

124

<xsl:for-each select="catalog/cd"> <tr> <td> <xsl:value-of select="name"/> </td> <td> <xsl:value-of select="color"/> </td> <td> <xsl:value-of select="country"/> </td> <td> <xsl:value-of select="company"/> </td> <td> <xsl:value-of select="price"/> </td> <td> <xsl:value-of select="year"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

Output

My Flower Collection
Name Color Country Company Price Year Rose Red USA Columbia 10.90 1985 Jasmine White UK CBS Records 9.90 1988

TOP

125

.34 XPath Patterns


XPath enables you to locate any one or more nodes within an XML document, often by using multiple alternate routes. In essence, XPath provides the syntax for performing basic queries upon your XML document data. It works by utilizing the ability to work with XML documents as hierarchically structured data sets. All XML documents can be represented as a hierarchy or tree of nodes. This aspect of XML shares a similarity to how paths are encoded in file system URLs, which are used in Windows Explorer to produce tree views of files and folders on your computer The following XML sample document shows a simple hierarchy, which can be used to demonstrate some of the facilities of XPath. <? xml version='1.0'?> <authors> <author period="classical"> <name>Sophocles</name> <nationality>Greek</nationality> </author> <author> <name>Leo Tolstoy</name> <nationality>Russian</nationality> </author> <author period="classical"> <name>Plato</name> <nationality>Greek</nationality> </author> </authors> A basic XPath pattern describes a path through the XML hierarchy with a slash-separated list of child element names. For example, starting from the document root of the previous sample, the following pattern traverses down through the hierarchy to the <name> elements. authors/author/name The XPath pattern identifies all elements that match the path. In addition to describing an exact path down a known hierarchy, XPath can include wildcards for describing unknown elements and selecting a set of nodes. This provides the basics of an XML query facility. For example, an element of any name can be represented by the "*" wildcard as shown in the following pattern. authors/*/name The preceding sample identifies all the <name> elements that are grandchildren (children of any child element for the <authors> element), but without requiring them to be children of an <author> element. Here is another example that can be used to find both <name> and <nationality> elements in our sample document. 126

authors/author/* Using additional patterns within square brackets can specify branches on the path. For example, the following query describes a branch on the <author> element, indicating that only the <author> elements with <nationality> children should be considered as a pattern match. authors/author[nationality]/name This becomes even more useful for the sample data when comparisons are added. The following query returns the names of Russian authors. Note comparisons can be used only within brackets. authors/author[nationality='Russian']/name Attributes are indicated in a query by preceding the name of the attribute with "@". The attribute can be tested as a branch off the main path, or the query can identify attribute nodes. The following examples return authors from the classical period, and just the two period attributes, respectively. authors/author[@period="classical"] authors/author/@period

.35 XML Reader


TOP

XmlTextReader class is used to read Extensible Markup Language (XML) from a file. XmlTextReader provides direct parsing and tokenizing of XML and implements the XML 1.0 specification as well as the namespaces in the XML specification from the World Wide Web Consortium (W3C). The XmlReader class supports reading XML data from a stream or file. It defines methods and properties that allow you to move through the data and read the contents of a node. The current node refers to the node on which the reader is positioned. The reader is advanced using any of the read methods and properties return the value of the current node. The XmlTextReader, XmlNodeReader, and XmlValidatingReader classes are defined from the XmlReader class Reading an XML file XmlTextReader reader = new XmlTextReader(@"C:\Documents and Settings\PuranMAC\My Documents\Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\XMLFile1.xml"); Console.WriteLine("General Information"); Console.WriteLine("= = = = = = = = = "); Console.WriteLine(reader.Name); Console.WriteLine(reader.BaseURI); Console.WriteLine(reader.LocalName);

127

The Node Type property returns the type of the current node in the form of XmlNodeType enumeration: XmlNodeType type = reader.NodeType; Which defines the type of a node. The XmlReader class enables you to: Verify that the characters are legal XML characters, and that element and attribute names are valid XML names. Verify that the XML document is well formed. Validate the data against a DTD or schema. Retrieve data from the XML stream or skip unwanted records using a pull model. Example 1. Create a console application
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace xmlreaderwrit { class Program { static void Main(string[] args) { XmlTextReader reader = new XmlTextReader("books.xml"); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. Console.Write("<" + reader.Name); Console.WriteLine(">"); break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine(reader.Value); break; case XmlNodeType.EndElement: //Display the end of the element. Console.Write("</" + reader.Name); Console.WriteLine(">"); break; } } Console.ReadLine(); } } }

2. Create an XML file as books.xml


<?xml version="1.0" encoding="utf-8" ?> <bookstore> <book> <title> The Autobiography of Benjamin Franklin </title> <author> <first-name> Benjamin

128

</first-name> <last-name> Franklin </last-name> </author> <price> 8.99 </price> </book> </bookstore>

3. In the projects folder, copy books.xml file and paste into Bin ---> Debug 4. Run the console application. Output
<bookstore> <book> <title> The Autobiography of Benjamin Franklin </title> <author> <first-name> Benjamin </first-name> <last-name> Franklin </last-name> </author> <price> 8.99 </price> </book> </bookstore>

.36 XML Writer


TOP

The XmlWriter and XmlTextWriter classes are defined in the System.XML namespace. The XmlTextWriter class is derived from XmlWriter class, which represents a writer that provides fast non-cached forward-only way of generating XML documents based on the W3C Extensible Markup Language (XML) 1.0 specification. Since Xml classes are defined in the System.XML namespace, so first thing you need to do is to Add the System.XML reference to the project. Using System.Xml; XmlWriter is an abstract base class that defines an interface for writing XML. The following list shows that the XmlWriter has methods and properties defined to:

129

Write well-formed XML. Manage the output, including methods to determine the progress of the output, with the WriteState property.

Flush or close the output. Write valid names, qualified names, and name tokens

Example 1. Create a Console Application as below


using using using using System; System.Collections.Generic; System.Linq; System.Text;

using System.Xml; namespace writerx { class Program { static void Main(string[] args) { XmlTextWriter XmlWriter = new XmlTextWriter(Console.Out); XmlWriter.WriteStartDocument(); XmlWriter.WriteComment("This is the comments."); XmlWriter.WriteStartElement("BOOK"); XmlWriter.WriteElementString("TITLE", "this is the title."); XmlWriter.WriteElementString("AUTHOR", "I am the author."); XmlWriter.WriteElementString("PUBLISHER", "who is the XmlWriter.WriteEndElement(); XmlWriter.WriteEndDocument(); Console.ReadLine(); }

publisher");

} }

2. Run the application Output

130

<?xml version="1.0" encoding="IBM437"?><!--This is the comments.--><Book><TITLE>this is the title.</Title><Author>I am the author.</Author><PUBLISHER>who is the publisher</PUBLISHER></BOOK>

Difference between Xml writer and Xml reader XmlReaderRepresents a reader that provides fast, non-cached, forward-only access to XML data. XmlWriter is totally different from above; it is only used to write the xml doc.

.37 DOM API for XML


TOP

What is DOM? The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page. DOM API The DOM API, on the other hand, follows a treelike construct. Elements have parent-child relations with other elements. With this API, the parser builds an internal structure such that an application can navigate it in a treelike fashion. DOM allows an application to have random access to the tree-structured document at the cost of increased memory usage. The DOM API is ideal when we want to manage XML data or access a complex data structure repeatedly. The DOM API: Builds the data as a tree structure in memory Parses an entire XML document at one time Allows applications to make dynamic updates to the tree structure in memory. (As a result, we could use a second application to create a new XML document based on the updated tree structure that is held in memory.)

131

Using the DOM API preserves the structure of the document (and the relationship between elements) and does the parsing up front so that we do not have to do the parsing process over again each time we access a piece of data. If you choose to validate your document, we can be assured that the syntax of the data is valid while we are working with it. However, the DOM API requires the memory needed to store the data, which can be expensive in terms of machine cycles. In addition, the DOM API is, by nature, a two-step process: It parses the entire XML document. Applications interact with the XML data held in memory using the C/C++ APIs. As a result, we cannot begin working with the data until the DOM API has completely parsed the entire document.

The System.Xml.XmlDocument class implements the core XML Document Object Model (DOM) parser of the .NET Framework. XML content can be classified broadly into a collection of nodes and attributes of those nodes. You can use the DOM model implementation of System.Xml to query or to access these nodes and attributes of XML documents. The DOM implementation of System.Xml provides several ways to access these nodes and the attributes. The .NET DOM implementation (System.Xml.XmlDocument) supports all of DOM Level 1 and all of DOM Level 2 Core, but with a few minor naming changes. As mentioned earlier, central to the DOM API is the DOM tree data structure. The tree consists of nodes or elements. All nodes of a typical XML document (elements, processing instructions, attributes, text, comments, and so on) are represented in the DOM tree. Because the DOM tree is built in memory for the entire document, we are free to navigate anywhere in the document.

Example 1. Use Notepad or a similar text editor to save the following data as a file named E:\file1.xml: <?xml version='1.0' encoding='ISO-8859-1' standalone='yes'?> <Collection> <Book Id='1' ISBN='1-100000ABC-200'> <Title>Principle of Relativity</Title> <!-- Famous physicist --> <Author>Albert Einstein</Author> <Genre>Physics</Genre> </Book> <Book Id='2' ISBN='1-100000ABC-300'> <!-- Also came as a TV serial --> 132

<Title>Cosmos</Title> <Author>Carl Sagan</Author> <Genre>Cosmology</Genre> </Book> <!-- Add additional books here --> </Collection> 2. Create a website and open a Console Application with the following code
using System; using System.Xml; using System.Text; namespace ConsoleApplication1 { class Class1 { public static int GetNodeTypeCount(XmlNode node, XmlNodeType nodeType) { // Recursively loop through the given node and return // the number of occurences of a specific nodeType. int i = 0; if (node.NodeType == nodeType) i = i + 1; if (node.HasChildNodes) foreach (XmlNode cNode in node.ChildNodes) i = i + GetNodeTypeCount(cNode, nodeType); } return i;

[STAThread] static void Main(string[] args) { try { // Create an Xml document instance and load XML data. XmlDocument doc = new XmlDocument(); doc.Load("E:\\file1.xml"); // 1. Select all the Book titles by using an XPath query. XmlNodeList nodeList = doc.SelectNodes("//Book/Title"); XmlNode node; Console.WriteLine("{0}", "TITLES LIST: "); foreach (XmlNode nd in nodeList) Console.WriteLine("{0}", nd.InnerText); // 2. Read the XmlDeclartion values. XmlDeclaration decl = (XmlDeclaration)doc.FirstChild; Console.WriteLine("\n{0}", "XML DECLARTION:"); Console.WriteLine("{0}", "Version " + "= " + Console.WriteLine("{0}", "Encoding " + "= " +

decl.Version); decl.Encoding);

Console.WriteLine("{0}", "Standalone " + "= " + decl.Standalone); // 3. Move to the first node of DOM and get all of its

133

attributes.

XmlElement root = doc.DocumentElement; node = root.FirstChild; Console.WriteLine("\n{0}", "ATTRIBUTES OF THE FIRST foreach (XmlAttribute attr in node.Attributes) Console.WriteLine("{0}", attr.Name + " = " + // 4. Navigate to the child nodes of the first Book node. Console.WriteLine("\n{0}", "FIRST NODE'S CHILDREN:"); if (node.HasChildNodes) foreach (XmlNode cNode in node.ChildNodes) Console.WriteLine("{0}", cNode.OuterXml); // 5. Navigate to the next sibling of the first Book node. node = node.NextSibling; Console.WriteLine("\n{0}", "NEXT SIBLING:"); if (node != null) Console.WriteLine("{0}", node.OuterXml);

CHILD:"); attr.InnerText);

// 6. Get the parent node details of the current node. Console.WriteLine("\n{0}", "PARENT NODE NAME = " + node.ParentNode.Name); Console.WriteLine("{0}", "PARENT NODE HAS " + node.ParentNode.ChildNodes.Count + " CHILD NODES"); Console.WriteLine("{0}", "PARENT NODE'S NAMESPACE URI = " + node.ParentNode.NamespaceURI); // 7. Count the number of Comment nodes in the document. // You could search for other types in the same way. int commentNodes = Class1.GetNodeTypeCount(doc.DocumentElement, XmlNodeType.Comment); Console.WriteLine("\n{0}\n", "NUMBER OF COMMENT NODES IN THE DOC = " + commentNodes); Console.ReadLine(); } catch (XmlException xmlEx) // Handle the XML Exceptions here. { Console.WriteLine("{0}", xmlEx.Message); } catch (Exception ex) // Handle the Generic Exceptions here. { Console.WriteLine("{0}", ex.Message); } Console.ReadLine(); } } }

Compile and then run the application. NOTE: The file file1.xml should be in the same folder as the executable file (or we can modify the file path in the code). Output TITLES LIST: Principle of Relativity 134

Cosmos XML DECLARTION: Version = 1.0 Encoding = ISO-8859-1 Standalone = yes ATTRIBUTES OF THE FIRST CHILD: Id = 1 ISBN = 1-100000ABC-200 FIRST NODE'S CHILDREN: <Title>Principle of Relativity</Title> <!-- Famous physicist --> <Author>Albert Einstein</Author> <Genre>Physics</Genre> NEXT SIBLING: <Book Id="2" ISBN="1-100000ABC-300"><!-- Also came as a TV serial --><Title>Cosm os</Title><Author>Carl Sagan</Author><Genre>Cosmology</Genre></Book> PARENT NODE NAME = Collection PARENT NODE HAS 3 CHILD NODES PARENT NODE'S NAMESPACE URI = NUMBER OF COMMENT NODES IN THE DOC = 3 Example 2 Create a new project and a console application. The code for this file is :
using using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Xml; System.IO; System.Collections;

namespace dom { class Program { Hashtable attributes; public void Person() { attributes = new Hashtable(); attributes.Add("id", null); attributes.Add("ssn", null); // attributes.Add("FirstName", null); attributes.Add("LastName", null); attributes.Add("City", null); attributes.Add("State", null);

135

attributes.Add("Street", null); attributes.Add("ZipCode", null); attributes.Add("Title", null); attributes.Add("Description", null); } public object GetID() { return attributes["id"]; } // public object GetFirstName() { return attributes["FirstName"]; } public object GetLastName() { return attributes["LastName"]; } public object GetSSN() { return attributes["ssn"]; } public object GetCity() { return attributes["City"]; } public object GetState() { return attributes["State"]; } public object GetStreet() { return attributes["Street"]; } public object GetZip() { return attributes["ZipCode"]; } public object GetTitle() { return attributes["Title"]; } public object GetDescription() { return attributes["Description"]; } public void SetID(object o) { attributes["id"] = o; } //public void SetFirstName(object o) { attributes["FirstName"] = public void SetLastName(object o) { attributes["LastName"] = o; } public void SetSSN(object o) { attributes["ssn"] = o; } public void SetCity(object o) { attributes["City"] = o; } public void SetState(object o) { attributes["State"] = o; } public void SetStreet(object o) { attributes["Street"] = o; } public void SetZip(object o) { attributes["ZipCode"] = o; } public void SetTitle(object o) { attributes["Title"] = o; } public void SetDescription(object o) { attributes["Description"] = o; } public void ToXml() { XmlTextWriter tw = new XmlTextWriter(Console.Out); XmlNode childNode = null; tw.Formatting = Formatting.Indented; XmlDocument doc = new XmlDocument(); XmlNode node = doc.CreateElement("Person"); AppendAttribute(doc, node, "id"); AppendAttribute(doc, node, "ssn"); doc.AppendChild(node); childNode = AppendElement(doc, node, "Name", true); AppendElement(doc, childNode, "LastName", false); // AppendElement(doc, childNode, "FirstName", false); childNode = AppendElement(doc, node, "Address", true); AppendElement(doc, childNode, "Street", false); AppendElement(doc, childNode, "City", false); AppendElement(doc, childNode, "State", false); AppendElement(doc, childNode, "ZipCode", false); childNode = AppendElement(doc, node, "Job", true); AppendElement(doc, childNode, "Title", false); AppendElement(doc, childNode, "Description", false);

o; }

136

doc.WriteContentTo(tw);

private XmlNode AppendElement(XmlDocument doc, XmlNode parent, string name, bool containerElement) { XmlNode child = doc.CreateNode(XmlNodeType.Element, name, ""); if (!containerElement) { child.AppendChild(doc.CreateTextNode( (string)attributes[name])); } parent.AppendChild(child); return child; } private void AppendAttribute(XmlDocument doc, XmlNode parent, string name) { XmlAttribute child = doc.CreateAttribute(name); child.Value = (string)attributes[name]; parent.Attributes.Append(child); } static void Main(string[] args) { Program p = new Program(); p.Person(); // p.SetFirstName("Jack"); p.SetID("jnicholson"); p.SetSSN("123456789"); p.SetLastName("Nicholson"); p.SetStreet("101 Acting Blvd"); p.SetCity("Beverly Hills"); p.SetState("CA"); p.SetZip("90210"); p.SetTitle("Actor"); p.SetDescription("Acted as Colonel NathanJessop in A Few Good Men"); p.ToXml(); Console.ReadLine(); } } }

Compile and Run Output

137

Description: The ToXml() uses the AppendAttribute and AppendElement methods to abstract out the creation of elements and attributes. We start by creating the XmlTextWriter and signaling it to pretty-print the XML to Console.Out: XmlTextWriter tw = new XmlTextWriter(Console.Out); XmlNode childNode = null; tw.Formatting = Formatting.Indented; Next, we create the XmlDocument object to which all the elements will be appended. We create a Person node from the document object, which automatically appends the node to the document. Next, we use the AppendAttribute call to set the attributes of the _Person node: XmlNode node = doc.CreateElement("Person"); AppendAttribute(doc, node, "id"); The AppendAttribute method creates an attribute, sets its value, and then appends the attribute node to the collection of attributes of the _parent node. Note that in the .NET API, an attribute is a type of node and hence must be appended to the parent node just as any other child node is:

138

XmlAttribute child = doc.CreateAttribute(name); child.Value = (string)attributes[name]; parent.Attributes.Append(child); Next, we use repetitive calls to the AppendElement method to append the element nodes to the document. The method creates an element node and sets its value from the object if it is not a container node. (A container node is an element node that is not a text node; that is, it contains other element nodes as its children.) The method returns the child node created, and thus successive calls to the AppendElement method will append new element nodes to the most recent child node: XmlNode child = doc.CreateNode(XmlNodeType.Element,name,""); if (!containerElement) { child.AppendChild(doc.CreateTextNode((string)attributes[_name])); } parent.AppendChild(child); return child;

.38 ADO.NET
TOP

ADO .NET is a .Net version of ADO. But nothing seems to be similar in both. ADO is connected data-access approach and ADO .NET is disconnected data-access approach which is totally different. In ADO, datasource connection stays open for the lifetime of the application which leads to concerns like database security, network traffic and system performance.In contrary, ADO .NET uses disconnected architecture i.e datasource connection is kept open in need. ADO .NET is nothing but data-access component which is being shipped with .NET. EVOLUTION Lets step into its evolution. Traditional data processing depends primarily on a connected, two tier model. As of today data processing uses multi-tier architecture so there is a need to switch over to a disconnected approach for better scalability. Todays web application model uses XML to encode data and HTTP as a medium of communication between tiers. So maintaining state between requests is mandatory (connected approach doesnt require to handle state, where connection is open for programs lifetime.). So ADO .NET, which works with any component on any platform 139

that understands XML, was designed for this new programming model which comprises: Disconnected data architecture Tight integration with XML Common data representation ADO .NET ARCHITECTURE ADO .Net uses structured process flow containing components. Data in datasource is retrieved using various component of data provider and provide data to an application, then update changes back to database. ADO .NET classes are in system. Data namespace and used in application by importing, for instance, Imports system.data (VB) Using system.data (C#) ADO .NET clearly factors data access from data manipulation.

ADO.NET Key Components 1. The Dataset Object 2. The Data Provider Object The Dataset Object It is an in-memory representation of data. It can be used with multiple and differing data sources such as XML file or stream, data local to application. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. You can even define relations between tables to create parent-child relationships. The DataSet is specifically designed to help manage data in memory and to support disconnected operations on data, when such a scenario make sense. The DataSet is an object that is used by all of the Data Providers, which is why it does not have a Data Provider specific prefix. Dataset can be used if an application meets any of the following requirements: Remote data access Multiple and differing data sources Cache data local to the application Provide hierarchical XML view of a relational data and use XSL,Xpath tools Disconnected data access. 140

The Data Provider Object Data in datasource is retrieved using various components of data provider and provide data to application and update the changes back to datasource. Components of Data Provider Connection Command Data adapter Data Reader The SqlConnection Object To interact with a database, you must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on.

Properties of Connection Object Connection String: It is a primary property. Connection String provides information like data provider, data source, database name, Integrated Security and so on. For instance, Provider=SqlOledb1;Data Source=MySqlServer;Initial Catalog= Northwind;Integrated Security=SSPI The Connection We can initialize database connection as follows:
SqlConnection objConnect = new SqlConnection (Your Connection String); objConnect.Open();

Above, we set up our SQLConnection Connection object with our database connection information, and then we opened it. Listed below are the common connection object methods we could work with: Open - Opens the connection to our database Close - Closes the database connection

141

Dispose - Releases the resources on the connection object. Used to force garbage collecting, ensuring no resources are being held after our connection is used. Incidentally, by using the Dispose method we automatically call the Close method as well.

State - Tells you what type of connection state your object is in, often used to check whether our connection is still using any resources. Ex. if (ConnectionObject.State == ConnectionState.Open)

The SqlCommand Object The process of interacting with a database means that you must specify the actions you want to occur. This is done with a command object. You use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. You can use a command object alone, to execute a command directly, or assign a reference to a command object to an SqlDataAdapter, which holds a set of commands that work on a group of data as described below. Property of Command Object Command Text Property: It possess Sql Statement or name of the Stored Procedure to perform the command. Command Type Property: It contains stored procedure setting or text setting Command Object provides several execute methods namely execute scalar, execute reader, execute nonquery method. Lets have a brief look into its function. Execute Scalar Performs query commands that return a single value. For example, counting the number of records in a table. Execute Non Query Executes commands that returns the number of rows affected by the command. Execute Reader It reads records sequentially from the database

142

The SqlDataReader Object Data Reader can be used to increase the performance of the application which works in read-only, forward-only mode. Many data operations require that we only get a stream of data for reading. The data reader object allows us to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward-only stream of data. This means that we can only pull the data from the stream in a sequential manner The DataReader cannot be created directly from code; they can create only by calling the ExecuteReader method of a Command Object.

The DataReader Object provides a connection oriented data access to the Data Sources. A Connection Object can contain only one DataReader at a time and the connection in the DataReader remains open, also it cannot be used for any other purpose while data is being accessed. When we started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . Usually we are using two types of DataReader in ADO.NET. They are SqlDataReader and the OleDbDataReader. The System.Data.SqlClient and System.Data.OleDb are containing these DataReaders respectively SqlDataReader Object provides a connection oriented data access to the SQL Server data Sources from C# applications. ExecuteReader () in the SqlCommand Object sends the SQL statements to the SqlConnection Object and populate a SqlDataReader Object based on the SQL statement or Stored Procedures.
SqlDataReader sqlReader = sqlCmd.ExecuteReader();

When the ExecuteReader method in the SqlCommand Object execute, it will instantiate a SqlClient.SqlDataReader Object.
SqlDataReader.Read()

The SqlDataAdapter Object Sometimes the data we work with is primarily read-only and we rarely need to make 143

changes to the underlying data source. Some situations also call for caching data in memory to minimize the number of database calls for data that does not change. The data adapter makes it easy to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. Additionally, the data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. DataAdapter object is like a bridge that links the database and a Connection object with the ADO.NET-managed DataSet object through its SELECT and action query Commands. It specifies what data to move into and out of the DataSet. Often, this takes the form of references to SQL statements or stored procedures that are invoked to read or write to a database.

Example This example demonstrates how to populate GridView with data from the database using the ADO.NET. STEP 1: Open WebConfig file and set up connection string like below: <connectionStrings> <add name="MyDBConnection" connectionString="Data Source=WPHVD1850229O0;Initial Catalog=Northwind;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/> </connectionStrings> STEP 2: Create the GetConnectionString() method - Create a method for accessing our connection string that was set up at the WebConfig file private string GetConnectionString() { return System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].Connection String; 144

Note: MyDBConnection is the name of the connectionstring that was set up in the webconfig. STEP 3: Setting up the GridView in the mark up (ASPX) - Grab a GridView from the Visual Studio ToolBox and then Set AutoGenerateColumns to False. - Add BoundField Columns in GridView and set the DataField and the HeaderText accordingly. See below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Populating GrindView Control</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="CompanyName" HeaderText="Company"/> <asp:BoundField DataField="ContactName" HeaderText="Name"/> <asp:BoundField DataField="ContactTitle" HeaderText="Title"/> <asp:BoundField DataField="Address" HeaderText="Address"/> </Columns> </asp:GridView> </div> </form> </body> </html>

145

STEP 4: Create the BindGridView () method - After setting up GridView in the mark up then switch back to Code behind - Declare the following NameSpace below so that we can use the SqlClient built-in libraries Using System.Data.SqlClient; -Create the method for Binding the GridView

private void BindGridView() { DataTable dt = new DataTable(); SqlConnection connection = new SqlConnection(GetConnectionString()); try { connection.Open(); string sqlStatement = "SELECT * FROM Customers"; SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection); SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); sqlDa.Fill(dt); if (dt.Rows.Count > 0) { GridView1.DataSource = dt; GridView1.DataBind(); } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Fetch Error:"; msg += ex.Message; throw new Exception(msg); } finally { connection.Close(); } } 146

STEP 5: Calling the BindGridView() method on initial load of the page. protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindGridView(); } }

.39 Connected and Disconnected Architecture


TOP

The ADO.NET Framework supports two models of Data Access Architecture, Connection Oriented Data Access Architecture and Disconnected Data Access Architecture. In Connection Oriented Data Access Architecture the applications makes a connection to the Data Source and then interact with it through SQL requests using the same connection. In these cases the application stays connected to the database system even when it is not using any Database Operations. ADO.Net solves this problem by introduces a new component called Dataset. The DataSet is the central component in the ADO.NET Disconnected Data Access Architecture. A DataSet is an inmemory data store that can hold multiple tables at the same time. Datasets only hold data and do not interact with a Data Source. One of the key characteristics of the DataSet is that it has no knowledge of the underlying Data Source that might have been used to populate it. DataSet ds = new DataSet ();

147

In Connection Oriented Data Access, when you read data from a database by using a DataReader object, an open connection must be maintained between your application and the Data Source. Unlike the DataReader, the DataSet is not connected directly to a Data Source through a Connection object when you populate it. It is the DataAdapter that manages connections between Data Source and Dataset by fill the data from Data Source to the Dataset and giving a disconnected behavior to the Dataset. The DataAdapter acts as a bridge between the Connected and Disconnected Objects. SqlDataAdapter adapter = new SqlDataAdapter("sql", "connection"); DataSet ds = new DataSet(); adapter.Fill(ds, "Src Table"); By keeping connections open for only a minimum period of time, ADO .NET conserves system resources and provides maximum security for databases and also has less impact on system performance.

.40 Store and Retrieve Binary Data using ADO.NET


TOP

Storing Binary Images, Files into SQL Server using ADO.Net MS SQL Servers provide a field data type named varbinary (MAX) to hold binary data. Well be using ASP.Net to upload a file using asp:FileUpload Control, store this uploaded file into a binary buffer and then insert this binary buffer data into the varbinary (MAX) field using simple ADO.Net way. 1. Create a database table named StoreImageFiles in SQL Server 2008 to hold the records for uploaded image files etc. Essentially, there would be four fields named ImageFileID, ImageFileSize, ImageFileMIMEType and ImageFileBinaryData. SQL Script :
CREATE TABLE [dbo].[StoreImageFiles] ( [ImageFileID] [int] IDENTITY(1,1) NOT NULL, [ImageFileSize] [int] NOT NULL, [ImageFileMIMEType] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [ImageFileBinaryData] [varbinary](max) NOT NULL, CONSTRAINT [PK_StoredBinaryData] PRIMARY KEY CLUSTERED ( [ImageFileID] ASC)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]

ImageFileID: It's the primary key for the table StoreImageFiles ImageFileSize: It's the actual size of binary file to be stored in each record. The Size would be in bytes. Also, we'll be requiring this column in order to retrieve the binary image file. ImageFileMIMEType: Its' the type of the file being stored. Also, we'll be requiring this column 148

as well in order to retrieve the binary image file and ImageFileBinaryData: It's the actual binary data for the file (image etc.). 2. Create a new Asp.Net website named 'StoreImagesInDB', say. Place an asp:FileUpload and a button controls named 'UploadImageFile' and 'btnSaveImageFile' respectively on to web form. Below is the page markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StoringBinaryDataInSqlServer.aspx.cs" Inherits="StoringBinaryDataInSqlServer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Saving Image Files in SQL Server using ADO.Net</title> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="UploadImageFile" runat="server" /> <asp:Button ID="btnSaveImageFile" runat="server" Text="Upload and Store Binary Data in SQL Server database" OnClick="btnSaveImageFile_Click" /> </form> </body> </html>

We'll simply upload the file to be stored using 'UploadImageFile' FileUpload control, get the size of the file in bytes, get the file type, read the file into a binary buffer and using standard ADO.Net save this binary stream from memory into database table. 3. Enter the code in code behind file as:
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.IO; using System.Data;

149

public partial class StoringBinaryDataInSqlSqerver : System.Web.UI.Page { protected void btnSaveImageFile_Click(object sender, EventArgs e) { string imageToDbConStr = "Data Source=ADMIN-PC4;Initial Catalog=project1;User Id=sa;Password=sql@123;"; using (SqlConnection imageToDbConn = new SqlConnection(imageToDbConStr)) { int imageFileSize = UploadImageFile.PostedFile.ContentLength; string imageFileMIMEType = UploadImageFile.PostedFile.ContentType; BinaryReader imageFileBinaryReader = new BinaryReader(UploadImageFile.FileContent); byte[] imageFileBinaryBuffer = imageFileBinaryReader.ReadBytes(imageFileSize); imageFileBinaryReader.Close();

string imageToDbQueryStr = @"INSERT INTO StoreImageFiles(ImageFileSize, ImageFileMIMEType, ImageFileBinaryData) VALUES(@ImageFileSize, @ImageFileMIMEType, @ImageFileBinaryData)"; SqlCommand imageToDbCmd = new SqlCommand(imageToDbQueryStr, imageToDbConn);

imageToDbCmd.Parameters.AddWithValue("@ImageFileSize", imageFileSize); imageToDbCmd.Parameters.AddWithValue("@ImageFileMIMEType", imageFileMIMEType);

SqlParameter imageFileBinaryParam = new SqlParameter("@ImageFileBinaryData", SqlDbType.VarBinary, imageFileSize); imageFileBinaryParam.Value = imageFileBinaryBuffer;

imageToDbCmd.Parameters.Add(imageFileBinaryParam);

imageToDbConn.Open();

150

int noOfRowsAffected = imageToDbCmd.ExecuteNonQuery(); } } }

Compile and Run the application. The output window will have the File Upload Control with browse button. Here we have to browse the path of the image to be stored and click upload button. Then the image will be stored in the database file. Check the storage by SQL statement select * from
StoreImageFiles

Retrieve Binary Images, Files from DB & Display in Gridview TOP We can retrieve binary image file data, which is stored in SQL Server database table, using SqlDataReader (standard ADO.Net) and display each image record in asp:GridView 1. Creating a new Asp.Net Website named 'RetrievingImagesFromDB' 2. Place asp:GridView and asp:SqlDataSource on to the webform. Configure the datasource here. 3. Enter the following Markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile= "RetrievingImagesFromDB.aspx.cs" Inherits= "RetrievingImagesFromDB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Retrieve Binary Image From SQL Server and Display in Gridview</title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="GridViewDisplayImages" runat="server" AutoGenerateColumns="False" DataKeyNames="ImageFileID" DataSourceID="SqlDataSourceRetrieve"> <Columns> <asp:BoundField DataField="ImageFileID" HeaderText="ImageFileID" InsertVisible="False" ReadOnly="True" SortExpression="ImageFileID" /> <asp:BoundField DataField="ImageFileSize" HeaderText="ImageFileSize" SortExpression="ImageFileSize" />

151

<asp:BoundField DataField="ImageFileMIMEType" HeaderText="ImageFileMIMEType" SortExpression="ImageFileMIMEType" />

<asp:ImageField HeaderText="Image" DataImageUrlFormatString="DisplayImage.ashx?ImageFileID={0}" DataImageUrlField="ImageFileID"></asp:ImageField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSourceRetrieve" runat="server" ConnectionString="<%$ ConnectionStrings:project1ConnectionString %>" SelectCommand="SELECT [ImageFileID], [ImageFileSize], [ImageFileMIMEType], [ImageFileBinaryData] FROM [StoreImageFiles]"></asp:SqlDataSource> </form> </body> </html>

4.

We're having four columns in GridView as the table has four fields. First three of them are

regular asp:BoundFields and the forth one is asp:ImageField that'll be used to display the images in GridView. In image field we've DataImageUrlFormatString set to a URL. This URL can be to a regular .aspx webform. Here we are using a generic handler .ashx to avoid complete page processing. For each row in GridView we'll be passing value of 'ImageFileID' to this generic handler in querystring. And in response it will return an image. In the solution explorer, right click, Add New Item Generic Handler and enter the filename as DisplayImage.ashx and enter the following code:
<%@ WebHandler Language="C#" Class="DisplayImage" %> using System; using System.Web; using System.Data; using System.Data.SqlClient; using System.IO;

public class DisplayImage : IHttpHandler { public void ProcessRequest (HttpContext context) {

152

HttpRequest imageRequest = context.Request; HttpResponse imageResponse = context.Response; int imageFileID = Convert.ToInt32(imageRequest.QueryString["ImageFileID"]);

string imageFromDbConStr = "Data Source=ADMIN-PC4;Initial Catalog=project1;User Id=sa;Password=sql@123;"; using (SqlConnection imageFromDbConn = new SqlConnection(imageFromDbConStr)) { string imageFromDbQueryStr = @"SELECT ImageFileSize, ImageFileMIMEType, ImageFileBinaryData FROM StoreImageFiles WHERE ImageFileID = @ImageFileID "; SqlCommand imageFromDbCmd = new SqlCommand(imageFromDbQueryStr, imageFromDbConn); imageFromDbCmd.Parameters.AddWithValue("@ImageFileID", imageFileID); imageFromDbConn.Open(); SqlDataReader imageFromDbReader = imageFromDbCmd.ExecuteReader(CommandBehavior.SingleRow); if (imageFromDbReader.HasRows) { imageFromDbReader.Read(); string imageFileMIMEType = imageFromDbReader["ImageFileMIMEType"].ToString(); string imageFileSize = imageFromDbReader["ImageFileSize"].ToString(); byte[] ImageFileBinaryData = (byte[])imageFromDbReader["ImageFileBinaryData"];

imageResponse.ContentType = imageFileMIMEType; imageResponse.AddHeader("ImageFileSize", imageFileSize);

BinaryWriter imageFromDbWriter = new BinaryWriter(imageResponse.OutputStream); imageFromDbWriter.Write(ImageFileBinaryData, 0, ImageFileBinaryData.Length);

153

imageFromDbWriter.Close(); } } } public bool IsReusable { get { return false; } } }

5. In the code behind file the code should be like this:


public partial class RetrievingImagesFromDB : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }

Compile and Run the application. Output will be ImageFileID ImageFileSize ImageFileMIMEType Image

2018

image/pjpeg

3049

image/pjpeg

.41 Performing Bulk Copy Operations in ADO.NET


TOP

Bulk copying of data from one data source to another data source is a new feature added to ADO.NET. A bulk copy class provides the fastest way to transfer set of data from one source to the 154

other. Each ADO.NET data provider provides bulk copy classes. For example, in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class; data from a data source can be copied to one of the four types - DataReader, DataSet, DataTable, or XML. Using bulk copy operation, we can transfer data between two tables on the same SQL Server, between two different SQL Servers, or even two different types of database servers. Filling Data from the Source The first step in copying bulk data from a data source to another is to fill data from the source database. This source data can be filled in a DataSet, DataTable, or a DataReader. // Select data from Products table cmd = new SqlCommand("SELECT * FROM Products", source); // Execute reader SqlDataReader reader = cmd.ExecuteReader(); Creating SqlBulkCopy Object In ADO.NET, each data provider has a bulk copy operations class, which provides bulk copy related functionality. For example, SQL data provider has SqlBulkCopy class. SqlBulkCopy class constructor takes a connection string or SqlConnection object as first parameter, which defines the destination data source. After creating the object, we need to set the DestinationTableName propety to the table, which we want to copy date to. // Create SqlBulkCopy SqlBulkCopy bulkData = new SqlBulkCopy (destination); // Set destination table name bulkData.DestinationTableName = "BulkDataTable"; Copying Data to the Destination The SqlBulkCopy class provides WriteToServer method which is used to write data from a DataReader, DataSet, or DataTable to the destination data source. bulkData.WriteToServer(reader); In this code, I fill data in a DataReader object from the source data source. You can even fill data in a DataSet and pass DataSet as the input parameter of WriteToServer method. You can also pass an XML object or fill data in a DataSet from XML document. Closing SqlBulkCopy Object The Close method of SqlBulkCopy closes the bulk copy operation. bulkData.Close ();

Example 1. Create a database project1, table emp under this database and insert some records. 2. Create another database test and create a table emp1. 3. Create a website and enter the following code in code file:
using using using using using using using using System; System.Collections.Generic; System.Linq; System.Web; System.Web.UI; System.Web.UI.WebControls; System.Data; System.Data.SqlClient;

155

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { /***** Bulk copy Order Details data from Northwind to Northwind2 ******/ string northwindConnectionString = "Data Source=ADMIN-PC4;Initial Catalog=project1;User Id=sa;Password=sql@123;"; string northwind2ConnectionString = "Data Source=ADMIN-PC4;Initial Catalog=test;User Id=sa;Password=sql@123;"; using (SqlConnection northwindConnection = new SqlConnection(northwindConnectionString)) database { northwindConnection.Open(); SqlCommand command = new SqlCommand("Select * from [emp]", northwindConnection); SqlDataReader dataReader = command.ExecuteReader(); using (SqlConnection northwind2Connection = new SqlConnection(northwind2ConnectionString)) { northwind2Connection.Open(); SqlBulkCopy bulkCopy = new SqlBulkCopy(northwind2Connection); bulkCopy.DestinationTableName = "[emp1]"; bulkCopy.WriteToServer(dataReader); northwind2Connection.Close(); } northwindConnection.Close();

} Response.Write("Bulk Copy Operation Successful"); } }

4. Compile and Run the application. Output Bulk Copy Operation Successful

156

5. Check the bulk copy of records by using database test and sql statement select * from emp1 All records in emp (Database project1) will be copied into table emp1 (Database test)

.42 Manage Distributed Transactions


TOP

A transaction is a unit of work. You use transactions to ensure the consistency and integrity of a database. If a transaction is successful, all of the data modifications performed during the transaction are committed and made permanent. If an error occurs during a transaction, you can roll back the transaction to undo the data modifications that occurred during the transaction. Scope of transaction includes activities such as retrieving data from SQLServer, reading message from the message queue & writing to the database. Database transaction: Invoking a stored procedure that wraps required operation with BEGIN TRANSACTION & COMMIT/ROLLBACK TRANSACTION gives you to run transaction in a single round trip to the database server. There are two types of transaction that you will deal with Local Implicit and Distributed Implicit. A local implicit transaction is the transaction that simply talks to only one database. We already saw many examples on local implicit transaction. A distributed transaction talks to multiple databases at the same time. Creating a transaction is easy, simply create a TransactionScope with a using statement and include your code to execute your sql statements. When the transaction is complete, tell the TransactionScope, that the commit is ready by setting the Consistent property to true. The TransactionScope class in the System.Transactions namespace enables developer to programmatically wrap a series of statements within the scope of a transaction and includes support for complex transactions that involve multiple sources, such as two different databases or even heterogeneous type of data stores such as Microsoft SQL server, and Oracle database & a web service. TransactionScope class uses Microsoft Distributed Transaction Coordinator (MSDTC) the configuration and implementation make it rather advance topic and beyond the scope of this tutorials.

157

Steps for TransactionScope: Reference to the system.Transactions assembly. Import the system.Transactions namespace in your application. If you want to specify nesting behavior for transaction declare TransactionScopeOption variable and assign it a suitable value. If you want to specify the isolation level or timeout for the transaction, create a TransactionOptions instance and set its isolation level and TimeOut properties. Create new TransactionScope Object. Pass a TransactionScope object variable and TransactionOptions object into the constructor, if appropriate. Open connections to each database that you need to update, and perform update operations as required by application, if all updates succeed, call the Complete method on the TransactionScope object close the using block.

Using (TransactionScope transScope = new TransactionScope()) { string conString1 = WebConfigurationManager.ConnectionString [DB1].ConnectionString; string conString2 = WebConfigurationManager.ConnectionString[DB2].ConnectionString; using(SqlConnection Sqlcon = new SqlConnection(conString1)) { SqlCommand SqlCmd = Sqlcon.CreateCommand(); cmd.CommandText = "INSERT INTO asps(emp, name) Values (2,'Electronics')"; SqlCon.Open(); SqlComd.ExecuteNonQuery(); SqlCon.Close(); } using SqlConnection SqlCon1 = new SqlConnection(conString2); {

158

SqlCommand SqlCmd2 = SqlCon1.CreateCommand(); SqlCmd2.CommandText = "INSERT INTO ds(names) Values ('java')"; SqlCon2.Open(); SqlCmd2.ExecuteNonQuery(); SqlCon2.Close(); } transScope.Complete(); }

.43 Caching
TOP

Web applications are accessed by multiple users. A web site can have an extremely low load for minimum number of client access which provide faster access of the sites or may be heavy load on the site can increase exponentially which can slow down the server as well as access of Sites. Slow access is the most common problem for any web site when it is accessed by a large number of clients simultaneously. For resolve this problem we can have used high level of hardware configuration, Load Balancer, High bandwidth but load is not the only reason that make a web site is slow, so we need to provide such kind of mechanism which also provide fast data access and provide performance improvement of web site. Caching provide the solution. Caching is a technique where we can store frequently used data and Web pages are stored temporarily on local hard disks for later retrieval. This technique improves the access time when multiple users access a Web site simultaneously or a single user accesses a Web site multiple times. Caching for Web applications can occur on the client (browser caching), on a server between the client and the Web server (proxy caching / Reverse Proxy Caching), and on the Web server itself (page caching or data caching). Maximum time we chose web server to store cached data though it improved the performance but it does not solve our purpose every time. If we consider about load on Web Server we have to consider about the location that when the cached data should store. Following section will describe on different location of storing cached data. 159

ASP.NET Supports Three Type of Caching Page Output caching [Output caching] Fragment caching [Output caching ] Data Caching

Page Output Caching Before starting Page Output caching we need to know the compilation process of a page, because based on the generation of page we should able to understand why should we use caching . ASPX Page compiles in two stage process. First, the code is compiled into the Microsoft Intermediate Language (MSIL). Then, the MSIL is compiled into native code (by JIT Compiler ) during execution. and entire code in an ASP.NET Web page is compiled into MSIL when we built the sites , but at the time of execution only the portion of MSIL Converted to native code which is need by user or user request, which also improve performance. Now whatever we are getting , if there is some page which change frequently JIT need compile every time. So, We can use Page output for those page which content are relatively static. So rather than generating the page on each user request we can cache the page using Page output caching so that it can be access from cache itself. So, Instead of pages can be generated once and then cached for subsequent fetches, Page output caching allows the entire content of a given page to be stored in the cache. When the first request is generated page has been cached and for same page request page should be retrieve from cache itself rather than regenerating the page. For Output caching , OutputCache directive can be added to any ASP.NET page, specifying the duration (in seconds) that the page should be cached. The code file is :
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Cache.SetExpires(DateTime.Now.AddSeconds(360));

160

Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetSlidingExpiration(true); lbl_msg.Text = DateTime.Now.ToString(); } }

. Source file:
<%@ Page Language="C#" AutoEventWireup="true" Inherits="_Default" %> CodeFile="Default.aspx.cs"

<%@ OutputCache Duration='3' VaryByParam='none' %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <script runat="server"> protected void Page_Load(Object sender, EventArgs e) { lbl_msg.Text = DateTime.Now.ToString(); } </script> <h3>Output Cache example</h3> <p>Page generated on: <asp:label id="lbl_msg" runat="server"/></p>

</div> </form> </body> </html>

161

Output

Output Cache example


Page generated on: 2/25/2011 12:59:11 PM

Page Fragment Caching

TOP

There will be situations where we would like to cache only sections of page rather than the whole page. There may be sections of the page where the information gets updated every second or so and these sections should not cached. This can be implemented in ASP.NET using Fragment Caching. Fragment Caching is the technique by which we can cache a section of the page instead of caching the whole page

User Control (WebUserControl1.ascx)


<% @Control language="C#" %> <% @OutputCache duration="100" varybyparam="none" %> This user control was most recently generated at:<p> <% DateTime t = DateTime.Now; Response.Write(t); %>

Source (Default.aspx)
<%@ Page language="C#" %> <%@ Register tagprefix="myControl" tagname="Time" src="WebUserControl1.ascx" %> <%@ OutputCache duration="100" varybyparam="none" %> <myControl:Time runat="server" /><br> <br> <br> This page was most recently generated at:<p> <% DateTime t = DateTime.Now; Response.Write(t); %>

Output This user control was most recently generated at: 3/7/2011 5:25:27 PM 162

This page was most recently generated at: 3/7/2011 5:25:27 PM

Data Caching Caching of data can dramatically improve the performance of an application by reducing database contention and round-trips. Simply data caching store the required data in cache so that web server did not send request to DB server every time for each and every request which increase the web site performance. For data caching we need to cached those data which is accessible to all or which is very common data. The data cache is a full-featured cache engine that enables you to store and retrieve data between multiple HTTP requests and multiple sessions within the same application. Create an XML file as mydata.xml
<?xml version="1.0" encoding="utf-8" ?> <bookstore> <genre name="Fiction"> <book ISBN="10-861003-324" Title="title 1" Price="19.99"> <chapter num="1" name="Introduction"> A </chapter> <chapter num="2" name="Body"> B </chapter> <chapter num="3" name="Conclusion"> C </chapter> </book> <book ISBN="1-861001-57-5" Title="title " Price="24.95"> <chapter num="1" name="Introduction"> D </chapter> <chapter num="2" name="Body"> E </chapter> <chapter num="3" name="Conclusion"> F </chapter> </book> </genre> <genre name="NonFiction"> <book ISBN="10-861003-324" Title="title 2" Price="19.99"> <chapter num="1" name="Introduction"> G </chapter> <chapter num="2" name="Body"> H

163

</chapter> <chapter num="3" name="Conclusion"> I </chapter> </book> <book ISBN="1-861001-57-6" Title="title 3" Price="27.95"> <chapter num="1" name="Introduction"> J </chapter> <chapter num="2" name="Body"> K </chapter> <chapter num="3" name="Conclusion"> L </chapter> </book> </genre> </bookstore>

Source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="datacaching.aspx.cs" Inherits="datacaching" %> <%@ Import Namespace="System.Xml" %> <script runat="server"> void Page_Load(object sender, EventArgs e) { lblCurrentTime.Text = "Current Time is : " + DateTime.Now.ToLongTimeString(); } </script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label Runat="server" ID="lblCurrentTime"></asp:Label> <asp:GridView ID="GridView1" Runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="False"> <Columns> <asp:BoundField HeaderText="ISBN" DataField="ISBN" SortExpression="ISBN"></asp:BoundField> <asp:BoundField HeaderText="Title" DataField="Title" SortExpression="Title"></asp:BoundField> <asp:BoundField HeaderText="Price" DataField="Price" SortExpression="Price"></asp:BoundField> </Columns>

164

</asp:GridView> <asp:XmlDataSource EnableCaching="true" CacheDuration="100" CacheExpirationPolicy="Absolute" ID="XmlDataSource1" Runat="server" DataFile="mydata.xml" XPath="bookstore/genre[@name='Fiction']/book"> </asp:XmlDataSource> </div> </form> </body> </html>

Output

165