.NET Programming 1 www.ashagroup.org fiz; fo|kfFkZ;ksa] ;s uksV~l vki lcdh lgk;rk ds fy, cuk;s x;s gSaA ;s uksV~l ljy Hkk’kk esa cuk;s x;s gSaA bu uksV~l dks i<+dj vki fofHkUu ijh{kkvksa dh rS;kjh dj ldrs gSaA bu uksV~l ds ckjs esa vki vius lkfFk;ksa tkudkjksa o fj”rsnkjksa dks Hkh crk ldrs gSaA budks cukus esa dkQh le; o esgur yxh gSA buesa dqN =qfVa;k o xyfr;ka gks ldrh gSA dqN VkWfid de gks ldrs gSa blds ckjs esa vki gesa lwfpr dj ldrs gSaA /kU;okn

.NET Programming 2 www.ashagroup.org UNIT- I Introduction to .NET Framework: In July 2000 announced a whole new development framework for Windows called .NET in the Professional Developer Conference (PDC). In March 2002 Microsoft released final version of the .NET framework. We can develop various varieties of applications in it. It provides complete SDK (Software Development Kit). In .NET SDK classes, interfaces and language compilers are included. The Microsoft .NET framework 2.0 includes 18619 types 12909 classes 401759 public method, 93105 public property 30546 public events. Now we are using .NET framework 4.0 and 4.5. If we are developing powerful applications then we may require some IDE (Integrated Development Environment) that allows us rapid action development. The new visual studio.NET provides such IDE. There is various versions of VS such as VS 2008, 2010, 2012, 2013 are available. Terminology: To understand .NET framework properly we must have knowledge of some important terminologies.  Common Language Runtime CLR: An important part of .NET framework is CLR (Common Language Runtime). CLR is responsible for executing our application code. It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation. Those codes which are directly managed by the CLR are called the managed code.  MSIL (Microsoft Intermediate Language): When we write an application for the .NET framework with any language our is compiled directly into machine code. Instead our code is converted into a special language name MSIL (Microsoft Intermediate Language). MSIL is a low level and platform independent language. In reality the .NET framework understands only one language MSIL. We can write application using any language such as VB.NET, ++, Ada, COBOL, Fortran, Pascal, PHP, Perl, Java script and many more. The .NET framework includes compiler for these language that enables us to compile our code into MSIL. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific.  Framework Class Library: It contains a huge library of reusable types, classes, interfaces, structures and enumerated values, which are collectively called types. The .NET framework contains thousands of

.NET Programming 3 www.ashagroup.org classes those we can use when building an application. The framework class library was designed to make it easier to perform most common programming tasks.  Common Language Specification: It contains the specifications for the .Net supported languages and implementation of language integration.  Common Type System: It provides guidelines for declaring, using and managing types at runtime, and cross-language communication.  Namespaces: There are lots of classes in .NET framework. Microsoft divided the classes in framework into separate namespaces is simply a category to store the classes. Before we use a class in the program we must indicate the related namespace with the class name.  Assemblies: An assembly is the actual .DLL (Dynamic Linking Library) file on our hard disk, where the classes in the .NET framework are stored. In other words an assembly is the primary unit of deployment, security and version control in the .NET framework, because an assembly can span multiple files. An assembly is often referred to as a logical DLL.  Metadata: is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory.

C# (Sharp) and .NET: C# is a simple, modern, object oriented and type safe derived from C and C++. C# language was developed by small team of Microsoft engineer Anders Hejlsberg and Scott Wiltamuth. Hejlsberg is also known for creating Turbo Pascal. C# supports .NET framework and similar to java programming language. C# is a multi-paradigm programming language that encompasses functional, imperative, generic, object and component oriented programming disciplines. C# is one of the 44 programming languages supported by the .NET framework common language runtime. It was initially named cool which stood for C like Object Oriented Language. However in July 2000 when Microsoft made the project public the name of programming language was given as C#. Managed Execution Environment: The comparison between (C# / IL Code / CLR) and (Java / Bytecode / JVM) is an inevitable and valid comparison to make. With C and C++ we generally compile the source code to assembly language which will run on a

.NET Programming 4 www.ashagroup.org particular processor and a particular operating system. The compiler need to know which processor and operating system it is targeting, because processor may vary in instruction sets and operating system may vary in its functions. C and C++ model has been very successful but has its limitations.  Program interface do not interact with other programs. Microsoft COM (Component Object Model) was built to address this problem.  Program can’t be used on different platforms. Java addressed these problems by interpreting program to bytecode which then runs on a virtual machine. This bytecode is machine independent which means the same class file can be used on number of platforms. But the interpretation is very slow process and it is never appealing to the performance conscious . Today most JVM (Java Virtual Machine) use a Just In Time (JIT) compiler to make compilation fast. The basic model .NET uses the same as described above. The IL (MSIL) code has some improvements over byte code. 1. To provide greater type neutrality (helps implementation of templates). 2. To provide greater language neutrality. 3. To always be compiled to assembly language before executing and never interpreted. Similarities and Differences from Java: C++ and Java have many similarities. We can discuss these similarities and differences as follows:-  Both have powerful reflection capabilities.  C++ always uses .(dot) operator instead of arrow or scope resolution operator.  Null, Boolean / Bool keywords area available.  Garbage collection coupled with the elimination of pointers.  Compiles into machine independent codes. Java generates bytecode and C# generate IL code.  No header files, all code scoped to package or assemblies.  No global function or constants everything belongs to a class.  All values are initialized before use.  Arrays and strings with length built-in and bounds checking.  Both language support threads part of process such as open many tab in a browser.

.NET Programming 5 www.ashagroup.org Structure of C# Program: Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we can take it as a reference in upcoming chapters. A C# program basically consists of the following parts:  Namespace declaration  A class  Class methods  Class attributes  A Main method  Statements & Expressions  Comments Let us look at a simple code that would print the words "Hello World": using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine("Hello World"); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result: Hello World Let us look at various parts of the above program:  The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements.  The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld.  The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally

.NET Programming 6 www.ashagroup.org would contain more than one method. Methods define the behavior of the class. However, the HelloWorld class has only one method Main.  The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class will do when executed.  The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program.  The Main method specifies its behavior with the statement Console.WriteLine("Hello World"); WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.  The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.9610040036 It's worth to note the following points:  C# is case sensitive.  All statements and expression must end with a semicolon (;).  The program execution starts at the Main method.  Unlike Java, file name could be different from the class name. Compile & Execute a C# Program: If you are using Visual Studio.NET for compiling and executing C# programs, take the following steps:  Start Visual Studio.  On the menu bar, choose File, New, Project.  Choose Visual C# from templates, and then choose Windows.  Choose Console Application.  Specify a name for your project, and then choose the OK button.  The new project appears in Solution Explorer.  Write code in the Code Editor.  Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World. You can compile a C# program by using the command-line instead of the Visual Studio IDE:  Open a text editor and add the above-mentioned code.  Save the file as helloworld.cs  Open the command prompt tool and go to the directory where you saved the file.

.NET Programming 7 www.ashagroup.org

 Type csc helloworld.cs and press enter to compile your code.  If there are no errors in your code, the command prompt will take you to the next line and would generate helloworld.exe executable file.  Next, type helloworld to execute your program.  You will be able to see "Hello World" printed on the screen.

Language Features: Type System: The common type system supports two general categories of types, each of which is further divided into subcategories. Comman Type System

Reference Value Types Type

User Defined Self Deiscriptive Pointer Type Interface type Value Type Type

Enumeration Class Type Arrays

Built In Value User Defined Type Class

Boxed Value Type

Delegates

Value Types Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char, float which stores numbers, alphabets, floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value. Reference Types The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using more than one variable, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Reference types can be self-describing types, pointer types, or interface types.

.NET Programming 8 www.ashagroup.org Object Type The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. So object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. object obj; obj = 100; // this is boxing Dynamic Type You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. Syntax for declaring a dynamic type is: dynamic = value; For example, dynamic d = 20; Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables take place at run time. String Type The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted. For example, String str = "Tutorials Point"; A @quoted string literal looks like: @"Tutorials Point"; The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter. Pointer Types Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as in C or C++.

.NET Programming 9 www.ashagroup.org Boxing and Unboxing: Boxing and unboxing is an essential concept in .NET’s type system. With Boxing and unboxing one can link between value-types and reference (object) types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. Converting a value type to reference(object) type is called Boxing. Unboxing is the opposite operation and is an explicit operation. .NET provides a unified type system. All types including value types derive from the type object. It is possible to call object methods on any value, even values of primitive types such as int. The example class Test { static void Main() { int i = 1; object ob = i; // boxing int j = (int) ob; // unboxing } } An int value can be converted to object and back again to int. This example shows both boxing and unboxing. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.

.NET Programming 10 www.ashagroup.org

Flow Controls: Sometimes in programming we need to control flow of data and control. For this purpose we use control flow statements. In C# there is three types of control flow statements are available.  Decision Making / Conditional Statement  Iterative / Looping Statement  Branching / Jumping Statement C# provides following types of decision making statements. Statement Description An if statement consists of a boolean expression followed by one or

if statement more statements. An if statement can be followed by an optional else statement, which

if...else statement executes when the boolean expression is false. You can use one if or else if statement inside another if or else if

nested if statements statement(s). A switch statement allows a variable to be tested for equality against

switch statement a list of values.

Sometimes we need to repeat some task or calculations then we use looping statements. C# provides following types of loop to handle repetition requirements.

Loop Type Description Repeats a statement or group of statements while a given condition is

while loop true. It tests the condition before executing the loop body. Executes a sequence of statements multiple times and abbreviates the

for loop code that manages the loop variable. Like a while statement, except that it tests the condition at the end of

do...while loop the loop body Sometimes we need to stop a condition or loop in duration of processing. Statement Type Description It is used to stop the loop or condition. It transfers the control at break the end of that loop. It is also used to stop a loop or condition, But it transfers the continue control at next iteration of the loop.

.NET Programming 11 www.ashagroup.org

Objects and Classes Object is an entity, place or person of our world that can be identified according to their attributes and functions. For example boy, girl, pen, register, Jaipur, Delhi, chair, table etc. Class is group of similar things. In other words we can say that group of similar objects is called a class. The attributes and functions of objects are defined in a class. In programming context class is a user defined data structure which combine data (variables) members and member functions (methods). In C# class, we can use five types of access modifiers.  private: the private data member or member function can be accessed only inside of class.  public: the public data member or member function can be accessed outside of class.  protected: the protected data member or member function can be accessed only in its class or derived classes.  internal : the internal data member or member function can be accessed in an assembly or component that is being created but not to the client of that component.  protected internal: the protected or internal data member or member function can be accessed in the containing program and assembly and in the derived classes. using System; namespace BoxApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public void setLength( double len ) { length = len; }

public void setBreadth( double bre ) { breadth = bre; }

public void setHeight( double hei ) { height = hei; }

.NET Programming 12 www.ashagroup.org

public double getVolume() { return length * breadth * height; } } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); double volume;

// Declare Box2 of type Box // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0);

// box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0);

// volume of box 1 volume = Box1.getVolume(); Console.WriteLine("Volume of Box1 : {0}" ,volume);

// volume of box 2 volume = Box2.getVolume(); Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey(); } } }

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210 Volume of Box2 : 1560

.NET Programming 13 www.ashagroup.org Constructor and Destructor Constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor will have exact same name as the class and it does not have any return type. Following example explains the concept of constructor: using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() { Console.WriteLine("Object is being created"); }

public void setLength( double len ) { length = len; } public double getLength() { return length; }

static void Main(string[] args) { Line line = new Line(); // set line length line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); Console.ReadKey(); } } }

When the above code is compiled and executed, it produces the following result:

Object is being created Length of line : 6

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope. A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. Destructors cannot be inherited or overloaded.

.NET Programming 14 www.ashagroup.org

Following example explains the concept of destructor: using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() // constructor { Console.WriteLine("Object is being created"); } ~Line() //destructor { Console.WriteLine("Object is being deleted"); }

public void setLength( double len ) { length = len; } public double getLength() { return length; }

static void Main(string[] args) { Line line = new Line(); // set line length line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }

When the above code is compiled and executed, it produces the following result:

Object is being created Length of line : 6 Object is being deleted Inheritance: One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely

.NET Programming 15 www.ashagroup.org new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.Consider a base class Shape and its derived class Rectangle: using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; }

// Derived class class Rectangle: Shape { public int getArea() { return (width * height); } }

class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle();

Rect.setWidth(5); Rect.setHeight(7);

// Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.ReadKey(); } } }

When the above code is compiled and executed, it produces the following result: Total area: 35

.NET Programming 16 www.ashagroup.org Interface: C# does not support multiple inheritance. However, we can use interfaces to implement multiple inheritance. The following program demonstrates this: using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; }

// Base class PaintCost public interface PaintCost { int getCost(int area);

} // Derived class class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area)); Console.ReadKey(); } } }

When the above code is compiled and executed, it produces the following result:

Total area: 35 Total paint cost: $2450

.NET Programming 17 www.ashagroup.org

Serialization in C#: Conversion of an object into a data stream of bytes is known as serialization for storage in database to various media. Serialization performed by CLR (Common Language Runtime). In other words we can say that serialization is an easy way to convert an object to a binary representation that can be written to disk or sent over a wire. We can serialize our own classes. We mark them with (Serializable) attribute. This serializes all members of a class except those mark as (non-serialized). .NET provides three serializers- binary, SOAP(Simple Object Access Protocol), XML. To serialize an object we need to either mark the object class with the (Serializable) Attribute or implement the ISerializable interface. For example:- The following is a class that is mark with the serializable attribute. [Serializable] Public Class Myclass { ------} If a class to serialized contains references to other objects. The classes of those other objects must also be marked [Serializable] or implement the ISerializable interface. We use interface if we want our class to control its own serializable and deserialization. The ISerializable interface only has one method. GetDataObject( ) In this method we pass serialization info object and a streaming content object. The GetDataObject( ) will populate the serialization info object with the data necessary for the serialization of the target object. Classes that implement this interface include System.Data.DataSet, System.Drawing.Font, System.Collections.HashTable, System.Drawing.Icon and System.Drawing.Image.

.NET Programming 18 www.ashagroup.org Delegates: It is a powerful capability that C++ and some other languages have addressed with function pointer. A delegate can be thought of as a type safe object oriented function pointer, which is able to hold multiple methods rather than just one. Delegates handle problems which would be solved with function pointer in C++ and interface in Java. It improves on the function pointer approach by mean type safe and being able to hold multiple methods. It improves on the interface approach by allowing the invocation of a method without the need for extra code to handle multiple method invocation. The most important use of delegates is event handling. There are three steps in defining and using delegates: Declaration, Instantiation and invocation. Delegates can be declared as follows:- delegates void simple ( ); C# provides a special rule for instantiation their instances. A delegate creation expression is used to create new instance of a delegate. New delegate data type (expression ) C# provides a special rule for invoking a delegate. delegate_object (parameter list) Reflection: Reflection is the ability to find out information about objects the application details (assemblies). It is meta data at a runtime. In other words reflection is the feature in .NET which enables us to get some information about object in runtime. That information contains data of the class. It can also get the name of methods that are inside the class and constructors of that class. We can use reflection to dynamically create an instance of a type, bind the type to an existing object or get the type from an existing object and invokes its method or access its fields and properties. The system type is the main class for reflection. System reflection name space contains all the reflection related classes. These classes are used to get information from any number of class under .NET framework. We should use system reflection name space in our program. In which we are using reflection. In C# we use reflection in following situations:  When we need to access attributes in our program.  For examining and instantiating types in an assembly.  For building new types at runtime.  For performing late binding, accessing, methods on types created at run time.

.NET Programming 19 www.ashagroup.org UNIT- II Overview of ASP.NET Framework: ASP.NET is a part of the Microsoft .NET framework. Here ASP known as . It is developed by Microsoft Corporation. ASP.NET is a web development platform, which provides a programming model, a comprehensive IDE and various services. Using ASP.NET we can build powerful websites, web applications for PC as well as mobile and tablets devices. ASP.NET is a server technology that allows to build dynamic web-pages and to interact with data bases. It is easy to use, robust for developing websites. It provides new dimensions to the web experience. Understanding ASP.NET Controls: ASP.NET controls are the heart of ASP.NET framework. Every ASP.NET control is a .NET class that executes on the server and renders certain content to the browser. ASP.NET framework includes over 70 controls which enables us to do everything from displaying a list of database records, to display a randomly rotating banner advertisement. Various controls of ASP.NET framework can be divided into 8 groups:  Standard controls: Standard control enables us render standard form elements such as buttons, labels, text box, list box etc.  Validation controls: The validation controls enables us to validate form data before submit the data to the server. For example: We can use a required field validator control to check whether a user entered a value for a required input field.  Rich controls: These controls enable us to render things such as calendar, file upload buttons, rotating banner advertisements and multistep wizards.  Data controls: The data control enables us to work with data such as data-base –data. For example: We can use these controls to submit new records to a database table or display a list of database records.  Navigation controls: Navigation control enables us to display standard. Navigation elements such as menus, tree view and sitemap.  Login controls: The login control enables us to display login, change password and registration forms.  Web part control: The web part control enables us to build personalized portal applications.  HTML control: The HTML controls enable us to convert any HTML tag into a server site control.

.NET Programming 20 www.ashagroup.org All of these ASP.NET control excepting HTML controls. We can declare and use as same way as in visual basic. We should use the ID attribute to refer to the control in page with in our code. Every control must have a unique ID. Another important attribute marks the tag as representing a server side control. Understanding HTML controls: We declare a HTML control in a different way than we declare standard ASP.NET controls. The ASP.NET framework enables us to take any html tag and add a runat server attribute to the tag. This attribute will convert tag into server side ASP.NET control.

ASP.NET Applications: We can simply group a bunch of ASP.NET pages together and call it an application but the format definition extends a bit further. An ASP.NET application is defined as following: The sum of all files, pages, event handlers, modules, and executable code that is invoked or run within the scope of a given virtual directory on a server is called ASP.NET application. ASP.NET applications are completely separate entities. Each ASP.NET application is handled in its own .NET runtime application domain, which means that each application can maintain its own set of configuration values and properties. An ASP.NET application is created first time. A user makes a request from the server after that we are able to use various application events to control execution of our program.

Webserver: A computer that delivers webpages is called webserver. Every web server has an IP address and possibly a domain name. For example: If we enter the URL http:// www.ashagroup.org in our browser. The browser sends a request to the server whose domain name is www.ashagroup.org. Than the server fetches the page requested and sends it to our browser. Any computer can turned into a web server by installing server software and connecting the machine to the internet. There are many web server software application including public domain software from NCSA and Apache and commercial package from Microsoft, Netscape Navigator and other. The term webserver can mean of two things:-  A computer program that is responsible for accepting HTTP request from clients (web browser) serving them HTTP response along with optional data contents which usually are web pages.

.NET Programming 21 www.ashagroup.org  A computer that runs a computer programs known as server. Web server have some basic features: o HTTP. o Authentication. o Static And Dynamic Content. o Content Compression. o Virtual Hosting. o Large File Support. Installation of IIS server in windows: Window XP professional includes a limited feature version of internet information service (IIS) with it. We can setup our own website, setup a test website, develop an intranet for our organization. Since window XP professional is not a server class operating system. The limited functionality of its built in IIS prevents us from doing a lot of things which we can do with a full server version. However its limited functionality will still allow us to do a lot for free from our workstation. IIS is not installed by default on window XP professional you will need to install it and it will need our windows XP setup CD for this process. Go to control panel and add / remove programs then click on add / remove window components button on the left panel. The window component wizard will appear check IIS and click on details. This is all of the functionality being installed. Check the file transfer protocol service then click ok, click next. IIS will install. Once it is complete click finish. Close the add or remove program and the control panel. IIS is now installed. IIS is managed through a standard MMC (Microsoft Management Console) added. The interface for managing IIS is very similar to managing any other component is windows XP.

.NET Programming 22 www.ashagroup.org Creating and Running ASP.NET Website in Visual Studio

1. Start Visual Studio. 2. In the File menu, click New Web Site.

3. In the New Web Site dialog box, select the language to use Visual C#. 4. Select the ASP.NET Empty Web Site.

5. Click OK. 6. Click on Website menu then click on Add New Item. 7. Select Web Form from displayed dialog box.

8. Press add button. Now Default.aspx file will open. Here we can write asp tags to add controls on our form. 9. To write code for event functions Right click on page. 10. Select View Code from displayed list. 11. It will open Default.aspx.cs file, here we can write our event functions. 12. To run program press ctrl+F5.

.NET Programming 23 www.ashagroup.org Web-Forms: Web forms are similar to HTML forms. The only difference is that web forms are server side. It means we create the user element on the server. We can create objects known as server control that represent piece of UI (User Interface). Web forms are divided into two categories: 1. Using element 2. UI logic. These two components are completely separate from each other and they can be physically located anywhere. Both control parts are contained only in .aspx file. A web form on a webpage allows a user to enter data that is sent to a server for processing. Web forms resemble paper forms because internet users fill out the forms using check boxes, radio buttons or text fields. In addition to functioning as input template for new information, web forms can also be used to query and display existing data in a similar manner to mail marge forms with the same advantages. Web forms are defined in formal programming languages such as HTML, PERL, JAVA, or .NET. The implementation of these languages often automatically invoke user interface idioms such as grids, themes etc. Web Form Control: Web form controls are divided into two main categories: 1. Server control 2. Client control Server Control: Server controls are the user interface elements of a web form. They are divided into four types:  HTML Server Controls: They represent normal html form element such as text input boxes and buttons but they are created on the server.  Web Control: Web controls are similar but they provide more function to represent compiled user interface.  Validation Controls: These are used to validate user input.  User Controls: These are custom built controls that perform some function.

Client Control: Client controls are used on client side for example: A grid control that allows us to create new records, edit an existing record and delete an existing record. We can also create a control and events to these controls.

.NET Programming 24 www.ashagroup.org Button control: The button control renders a push button that we can use to submit a form to the server. For example:- when we click a button control. The click event occurs and perform the specific task.



protected void funclick(object sender, EventArgs e) { label1.Text="You have clicked on Command Button"; }

The button control supports the following attribute properties:- (this is not a complete list)  Access key: Access key enables us to specific a key that navigates to the button control.  Enabled: Enables us to disable the button control.  Tab index: Enables us to specify the tab order.  Text: Enables us to label of the button control.  ID: To make id name of the button control.  Runat: Enable us to send the control to the server. Methods / functions:-  Focus: Enables us to set initial form focus to button control.  OnClick: This method is raised when the button control is clicked. The command name and command argument are passes to this event. Link button control: The link button control renders a link instead of a push button. It enables us to post a form to the server.



protected void funclick(object sender, EventArgs e) { label1.Text = "You have clicked on Link Button"; } The link button control supports the following attributes:  Accesskey: Enables us to specify a key that navigates to the button control.  Enabled: Enables us to disable link button control.  Postbackurl: Enables us to post a form to a particular page.

.NET Programming 25 www.ashagroup.org  TabIndex: Enables us to specify the tab order.  Text: Enables us to label of the button control. The link button control supports the following methods:-  Focus: Enables us to set the initial form focus to the link button control. The link button control also supports the following events:  OnClick: Raised when the link button control is clicked. Image button control: The image button control enables us to post a form to the server. However the image button control always display an image. The image button can be used to create a server side image map. Server side image map are not accessible to the person with disabilities. The image button control supports the following properties:-  Accesskey: Enables us to specify a key that navigates to the button control.  Enabled: Enables us to disable link button control.  Post backurl: Enables us to post a form to a particular page.  Tab index: Enables us to specify the tab order.  AlternateText: To provide alternate text for the image. If image is not displayed.  DescriptionUrl: Enables us to provide a link to a page that contains a detailed description of the image.  Image align: To set the alignment of the image the possible values are abs bottom, abs middle, bottom, left, middle, notset, right, top and top text.  ImageUrl: To specify the path (url) of the image. The image button control supports the following methods:  Focus: The image button control also supports the following event:  OnClick:



protected void funclick(object sender, EventArgs e) { label1.Text = "You have clicked on Image Button"; }

.NET Programming 26 www.ashagroup.org Accepting user input: The ASP.NET framework includes several controls that we can use to gather user input. Some of the controls are text box, check box, radio button etc. Text box control: This control can be used to display three types of input fields depending on the value of its text mode property. The text mode property accepts the following three values:-  Single line: display a single line input field.  Multiline: display a multiline input field.  Password: displays a single line input in which the text is hidden. We can use the following properties of the text box control. Some other attributes of text box controls are given below:-  Accesskey: Enables us to specify a key that navigates to the button control.  Enabled: Enables us to disable link button control.  Postbackurl: Enables us to post a form to a particular page.  Tab index: Enables us to specify the tab order.  AutoCompleteType: To associate an autocomplete class with the text box control.  Columns: To specify the number of columns to display.  MaxLength: To specify the maximum length of data. That a user can enter in text box.  ReadOnly: To prevent users from changing the text in the text box.  Rows: to specify the number of rows to display.  Wrap: to specify whether word wrap is set or not. Text box control also supports the following method:-  Focus:- to set the initial form focus to the text box.  TextChanged : raised on the server when the content of the text box are changed. Example:





.NET Programming 27 www.ashagroup.org Label Control: Whenever we need to modify the text displayed in a page dynamically we can use the label control. Any string that we assign to the label controls text property is displayed by the label, when the control is rendered as an alternative tool assigning text to the text property. We can place the text between opening and closing tags of label control. This text will be assign to the text property. The label control supports the following attributes:- 1. BackColor:- to change background color of the label. 2. BorderColor:- to set the color of a border rendered around the label. 3. BorderStyle:- to display various type of border. The possible values are not set, none, dotted, dashed, solid, double, groove, ridge, inset and outset. 4. BorderWidth:- to set the size of border around the label. 5. Font:- to set the label font property. 6. ForeColor:- to set the color by the content rendered by the label. 7. ToolTip:- to set a label tittle attribute. 8. Cssclass:- to associate with a cascading style sheet class with the label. Literal control: The literal control is similar to label control. We can use the literal control to display text or HTML content in a browser. This control gives us a way of adding HTML in a webpage. We just assign text to a literal controls text property and that text is inserted directly into the web form because the content of a literal control are not contain in a span tag. The literal control does not support any of the formatting properties supported by the span tag. The mode property enables to encode HTML content. The mode property may have one of three values pass through, encode and transform. Check box control: This control enables us to display a check box and to take input from it. The check box includes a text property which is used to determine label of the check box. The most common attributes of check box control are given below:-  Access key  Enabled  Tabindex  Text  Textalign:- To align the label for the check box possible values are left or right.

.NET Programming 28 www.ashagroup.org This control supports the Focus method: Check box control also supports the following event. 1. CheckedChanged: Raised on the server when the check box is checked or unchecked. Example of CheckBox:


protected void CheckBox1_CheckedChanged(object sender, System.EventArgs e) { if (CheckBox1.Checked == true) { Image1.Visible = true; } else { Image1.Visible = false; } } Example of CheckBoxList:
Monitor Keyboard Mouse Speakar CPU


protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = "Your selected items are given below :
"; foreach (ListItem li in CheckBoxList1.Items) { if (li.Selected == true) { Label1.Text += li.Text + "
"; } } }

.NET Programming 29 www.ashagroup.org

Radio Button Control: We use radio button control in a group. Only one radio button in a group of radio button can be checked at a time. For example: The radio button control supports the following attributes:-  Accesskey: Enables us to specify a key that navigates to the button control.  Enabled: Enables us to disable link button control.  Post backurl: Enables us to post a form to a particular page.  Tab index: Enables us to specify the tab order.  Autopostback: To post the form containing the radio button back to the server automatically when the radio button is checked or unchecked.  Checked: Enables us to set whether the radio button is checked.  Group name: To group radio button controls.  Text align: To set the alignment to the right or left of the radio button. The radio button control supports following method:  focus The following event is supported by radio:  Checked changed:- raised on the server when the radio button is checked or unchecked.

protected void RadioButton_CheckedChanged(object sender,System.EventArgs e) { if (RadioButton1.Checked == true) { Response.Write("You Selected: Asp.Net"); } else { Response.Write("You Selected: ColdFusion"); } }

.NET Programming 30 www.ashagroup.org Displaying images: The ASP.NET framework includes two controls for displaying images. The image and image map control. The image control simply displays an image. Whereas the image map control enables us to create a client side, clickable image map. The image control supports following attributes:-  Alternate text: Enables us to provide alternate text for the image.  Description url: To provide a link to a page that contains a detailed description of the image.  Image align: To set alignment of image possible value are abs bottom, abs middle, base line, bottom, left, middle, notset, right etc.  Image url: Enables us to specify the URL of the image. The image control supports three methods of supplying alternate text. If we have an image for our company logo then we should assign the text “my company logo” to alternate text property. If an image represents any chart or graph then we should supply a value for description URL property. It will link to a page that contains a long textual description of the image. Finally if the image is used for decoration then we should set the generate empty alternate text property to the value true. Image map control: This control enables us to create a client side image map. In image map displays an image when we click different areas of the image things happen. We can use an image map as a fancy navigation bar. In that case clicking different areas of the image map navigates to different pages in our website. We can also use an image map as an input mechanism. For example: we can click different product images to add a particular product to a shopping cart. An image map control is composed of instances of the hot spot class. A hotspot defines the clickable region in an image map. The ASP.NET framework supports three hot spot classes: 1. CircleHotSpot: Enables us to define a circular region in an imagemap. 2. PolygonHotSpot: To define an irregularly shaped region in an imagemap. 3. RectangleHotSpot: To define a rectangular region in an imagemap.

.NET Programming 31 www.ashagroup.org List Box Control: As in we use web server list boxes to display a list of items that user can select. We can create both single selection and multiple selection list boxes. By default web server list boxes are single selection list boxes. The selection mode property can change single to multiple selection list boxes. Example:




AdRotator BulletedList CheckBox ListBox CheckBoxList RadioButton RadioButtonList DropDownList MultiView Wizard Xml
protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) { Label1.Text = "Your Favorite Control is: " + ListBox1.SelectedItem.Text.ToString(); } Drop Down List Box:- Drop down list box control is similar to the list box. Except that they can spot only single selection and they display their list in drop down manner. Some common properties of drop- down list control is:-  Selected index: Set the index of the selected item in the drop down list control.  Border color: Set the border color of the control.  Border style: To set border style of the control.  Border width: To set the size of border.

.NET Programming 32 www.ashagroup.org Bulleted List Control: We can use bulleted list control to create formatted list. In our web application we can also define different styles for the bulleted list using the bullet style property. The properties supported by bulleted list are given below:-  Bullet image url: Obtains or sets the path to an image to display for each bullet in a bulleted list control.  Bullet style: To set the bullet style possible values are circle, custom image, disk, lower alpha, lower roman, numbered, square etc.  Display mode: To set display mode of control possible values are hyperlink, link button and text.  First bullet number: Sets the value that start the numbering.  Target: Set the target window or frame in which to display the page content. The event supported by this control is:- OnClick:

Computer Smart Phone Tablet Camera
Hyperlink Control: We use the hyperlink control to create a link to another web page. That webpage may be in our web application or a page anywhere on the world wide web. We can specify the location of the linked page in absolute way where we use linked pages complete URL or in a relative way with respect to the current page. The properties supported by hyperlink control are given below:-  Image URL: Obtains the path to an image to display for the hyperlink control.  Navigate URL: Obtains the URL to link to when the hyperlink control is clicked.  Target: Obtains the target windows or frame in which to display the webpage content.

.NET Programming 33 www.ashagroup.org Table control: Table control correspond to table elements in webpage. To create an entire table we also need table row and table data cell controls. Some important properties of table control are given below:-  Back image URL: Obtains the URL of the background image to display behind the table control.  Caption: Obtains the text to render an html caption in a table control.  Caption align: Obtains the horizontal or vertical position of caption element.  Cell padding: Obtains the amount of space between the content of the cell and cell border.  Cell span: Obtains the amount of space between the cells.  Horizontal align: Obtain the horizontal alignment of the table control on the page. Table row control: To create table row in a table we use this controls. We can manage the cells in the row in code by using the cell collection. Some of attributes of table row are given below:- 1. Cells: Gets a collection of table cell object that represent the cells of a row in a table. 2. Horizontal align: To set the alignment of the content of the row. 3. Vertical align: To obtain vertical alignment of the content in the row. Table cell control:- To create table cell in a row of table we use this control. Some of attributes of table cell control are given below:-  Column span: Obtains the number of columns in the table control.  Horizontal align: To set horizontal alignment of cell content.  Row span: Obtains the number of rows in the table control that the cell span.  Text: The text content of the cell.  Vertical align: To set vertical alignment of cell content.  Wrap: To set text wrapping of cell content.

.NET Programming 34 www.ashagroup.org Running A Web Application: To run ASP.NET application with we have three classes of options:- 1. APACHE server hosting:- a. Use mod-mono: A module that allows apache to serve ASP.NET application. b. Fast CGI hosting: If we have a server that supports the fast CGI () protocol for extending the server. We may also use a web server that support only for CGI using CGI- FCGI. c. XSP( eXtensible Server Pages): This is a simple way to get started. A light weight and simple web server written in C#. For deploying applications we can use mod-mono or fast CGI approaches because it will give us all the configuration option and flexibility that come with using apache or a fast CGI server. For quickly getting started XSP is the ideal solution but it is a limited server and it is useful to get acquainted with ASP.NET. Multi-Forms: The multi-forms module is design for the collection of data from users. It can be used to easily author multipage forms which are published as nodes. The data collected by the forms can be exported in tab delimited format. The multiform supports the following features: 1. Multipage form support. 2. Ability to save or load form group of fields (snippets). 3. Duplicate submission prevention. 4. Ability to purge submitted data. 5. Closing date and message of application. 6. Integrated e-mail referrals. 7. Creation of draw entries upon successful completion. Creating a multiform:- To create a multiform we can follow the given steps:- 1. Visit the create content page (node/ add) and click multiform. 2. After adding a multiform click the setup tab and fill the fields as explained below: a. Fill the node title and body fields. b. Set the footer text that will be shown below the form. c. Closing date section allows an optional closing date to be specified. 3. Once these fields are complete click the update button.

.NET Programming 35 www.ashagroup.org Defining submission form fields: The submission form is the first form shown to the user. This form is meant for submission metadata. For example: contact information and questions and answers on this form. To edit the submission form click the forms tab then click the edit submission form. Clicking add new field will allows us to add a field. Each field has a name and type and optionally a description and validation type. Managing submission: Multiform submission can be managed via the submission tab. A list of submission in server chronological order will be shown. Submission can be viewed, purged, exported and randomly drawn. Submission e-mailing: Multiform submission can be e-mailed if the actions module is installed at the bottom of setup tab. There will be a section of the form labeled actions. In this section select the email action under multi forms. This action will e-mail each submission to the e-mail address of the creator of the multiform.

.NET Programming 36 www.ashagroup.org UNIT- III Form Validation: We can use the validation controls to prevent users from submitting the wrong type of data into a database table. For example: we can use validation control to prevent a user from submitting the value “mango” for date of birth field. The validation controls may be of two types:- the one is client side validation and the second is server side validation. Client Side Validation: Client site validation has the following benefits:  Immediate feedback: The user sees the errors right away and can correct it before he and she submits the request.  Behavioral interactivity: We can create responsiveness to our form that provides a wizard or steps and gives the user the sense of progression.  Maximize performance: This is a great reason to use flash forms. Since validating on the client reduces database and webserver traffic by intercepting request before they reach the server. On a busy server it may be very helpful. The user does not have to wait through the page refresh to see the error and correct it. Disadvantage:  Browser compatibility issues: On a very busy public site you may have do work around. Not all of browsers will handle our validation routine correctly.  Security settings: Some folks turn off scripting because they see it as a security risk for these clients, client site validation will not work.  Easily broken: Our client site validation can-not keep track of false data submitting to the server. Java script validation should not be the sole validation we use for this reason. Server Side Validation: We should allow validate only field with requirements on the server. For example: if it is supposed to be a date then make sure it is really a date. If it is supposed to be a number make sure, it is a number. There are various validation controls available at server side.  Compare validator: It uses the comparison operator to compare user enter data to a constant value or the value in another data entry control.  Custom validator: It makes sure that the user entered data passes validation criteria that we set our self.

.NET Programming 37 www.ashagroup.org  Range validator: It makes sure to check whether a value falls between a certain ranges of value.  Regular expression validator: It makes sure that the user entered data matches a regular expression pattern.  Required field validator: Enables us to require the user to enter a value in a form field.  Validation summary: It displays the list of all the validation errors on the webpage. Validation Controls Required field validator: This control enables us to require a user to enter a value into a form field before submitting the form. We must set two properties while using this control:  Control to validate: The id of the field being validate.  Text: Error message displayed when validation fails. By default this validator checks for non-empty string (space do not count). If we enter anything into the form field associated with the control then it will not display its validation error message.

Your name:


Compare Validator Control: It enables us to perform three different type of validation task. We can use the compare validator to perform a data type check. In other words we can use the control to determine whether a user has entered the proper type of value into a form field. We can also use this compare validator to compare value entered into a form field against a fixed value. We can use this validator to compare the value of one field against another field. This validator has six other properties. . Control to validate: The id of the form field being validated. . Control to compare: The id of a control against which to compare. . Value to compare: The fixed value against which to compare. . Text: The error message displayed when validation fails. . Type: The data type of value being compared possible values is string, integer, double, date, currency etc.

.NET Programming 38 www.ashagroup.org . Operator: The type of comparisons to perform possible values are data type, check, equal, greater then, greater than equal, less then, less than equal, not equal. Example Data Type Check

protected void Button1_Click(object sender,System.EventArgs e) { Label1.Text = "Form Submited. Your value is Integer"; } Example Two Field Compare



protected void Button1_Click(object sender,System.EventArgs e) { Label1.Text = "Form Submited and Password match."; }

Range Validator Control: This control enables us to check whether the value of a form field fully between a certain minimum and maximum value. We must set file attributes when we using this control. * Control validate: The id of the form being validated. * Text: The error message displayed when validation fails. * Minimum value: The minimum value of validation range.

.NET Programming 39 www.ashagroup.org * Maximum value: The maximum value of validation range. * Type: The type of comparison to perform. Possible values are string, integer, double, date and currency. By default the type property has the value string and the range validator performs a string comparison to determine whether a value fails between the minimum and maximum value. So we must set the type property when we using range validator.



protected void Button1_Click(object sender,System.EventArgs e) { Label1.Text = "You entered valid Number.
Your Number:" + TextBox1.Text.ToString(); } Calendar Control: We use the calendar control to display a single month of a calendar on a webpage. This control allows us to select dates and to move the next or previous month. We can choose whether the calendar control allows user to select a single day, week or month by setting the selection mode property. By default the control displays the day of the month, day heading for the days of week, a title of the month name and allows character for navigating to a next and previous month. We can customize the appearance of the calendar control. By setting the properties that control the style for different parts of the control. There are various attributes of this control as given below:- i. Cellpadding:- Sets the space used for cell padding in the calendar. ii. Cellspacing:- Sets the space between cell in calendar. iii. DayHeaderStyle:- Sets the style for the day of the week. iv. DayNameFormat:- Obtains the day of week name format. v. DayStyle:- To set the style for days. vi. SelectedDate:- Obtains the selected date.

.NET Programming 40 www.ashagroup.org vii. SelectedDates:- Obtains a collection of date time objects for the selected dates. viii. SelectionMode:- Sets the date selection mode determining if we can select a day’s week or month. ix. ShowTitle:- To display or un display title of calendar. There are some events related to calendar control. o DayRender:- It occurs when each day is display. o SelectionChanged:- It occurs when the user selects a date. o VisibleMonthChanged:- It occurs when the user moves to a different month from on currently displayed. Example Calendar Control:



protected void Page_Load(object sender, EventArgs e) { Calendar1.SelectedDate = DateTime.Now; } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox1.Text = "selected date is " + Calendar1.SelectedDate; }

Ad Rotator Control:- ASP.NET supports banner advertisement. These advertisements may be image files (gif, jpeg, png, etc.) or other animator objects. The user can click to cause the browser to navigate to advertiser’s website. Using an old ad rotator we can automatically cycle through a series of advertisement banners. The add rotator automates the cycling process, changing and displayed advertisement when the page is refreshed. This control may have the following properties:  Advertisement file: To specify the file path to an XML file that contains a list of banner advertisement.  Alternate text field:- To specify the name of the field for displaying alternate text for banner advertisement.  Data member:- To bind to a particular data member in the data source.  Data source:- To specify a data source programmatically for the list of advertisement.

.NET Programming 41 www.ashagroup.org  Image URL field: To specify the name of field for image URL.  Keyword filter: To filter advertisement by a single keyword.  Navigate URL field: To specify the name of the field for the advertisement link.  Target: To open a new window when a user clicks the banner advertisement. The following event is supported by ad rotator control. Add created: Raised after ad rotator control selects an advertisement but before the ad rotator control renders the advertisement. Internet Explorer Control: Microsoft internet explorer web controls are powerful collection of ASP.NET server control. These web controls implement a single source authoring solution for four popular user interface. 1. Tree View 2. Toolbar 3. Multipage 4. Tab Strip Tree View:- The tree view facilities the authoring of webpages containing hierarchical datasets, folder views and other similar structure. The tree view has the following attributes:  Auto generate data bindings: It obtains a value indicating whether tree view control automatically generates tree node bindings.  Checked nodes:- It obtains a collection of tree nodes objects.  Leaf node style: A reference to the tree node style that allows us to set the appearance of leaf nodes.  Level styles:- It obtains a collection of style objects that represent the node styles at the individual levels of the tree.  Node indent:- It obtains or sets the indentation amount in pixcels for the child node.  Select node:- It obtains a tree node object which is selected in this control.  Target:- It sets the target window or frame in which to display the web content that is associated with a node. The method supported by tree view control:- Find node:- It retrieves the tree node object in the tree view control. The events supported by this control:- o Selected node changed: It occurs when a node is selected in the tree view control. o Tree node check changed:- It occur when a check box in the tree view control changes state between post to be server.

.NET Programming 42 www.ashagroup.org Multi Page And Tab Strip: The tab strip is often used in combination with the multipage control. However each control can also be used separately. The multipage control is used as a container for pages of web content which are activated when a tab is selected. The multipage is a container for a collection of page view elements. Clicking the tab navigates to a new page view automatically.

Toolbar Control: The toolbar can be used to author user interface elements that render and function in ways similar to the toolbars in application. The toolbar may have rich interactive behavior it can dock with other elements in a webpage or the browser window and it can modify its orientation. The tool bar control exposes both a client and server object model.

State Management: Webpages rarely are stand alone. Web applications almost always need to track users who visit multiple pages whether to provide personalization, store information about a user or to track usage for reporting purpose. State management is the process by which we maintain state and page information over multiple requests for the same or different pages. We can categorize state management in two types: Client Side State Management: This stores information on the client’s computer by imbedding the information into a web page, URL or a cookie. The technique available to store the state information at the client end is listed below:-  View state: View state provides a dictionary objects for retaining values between multiple requests for the same page. We can add custom values to view state. When an ASP.NET page is processed the current state of the page and controls is hashed into a string and saved in the page as a hidden field automatically. It means when the page is posted one of the first task performed by page processing is to re-store view state.  Control state: If we create custom control that requires view state we can use control state property to store state information for our control. We should insure that other developer could not break our control by disabling view state. Control state allows us to persists property information that is specific to a control and can-not be turned off like the view state property. To use control state in custom control our control must override oninit() method and call the register requires

.NET Programming 43 www.ashagroup.org control state method during initialization and then override the save control state and load control state methods.  Hidden fields: Like view state hidden fields store data in an HTML form without displaying it in the user browser. The data is available only when the form is processed.  Cookies: Cookies are small string of data that stores a value in the user browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple web pages on a website.  Query strings: Query strings store values in the URL. That is visible to the user. Use query strings when we want a user to be able to email or instant message state data with a URL.

Server Side State Management: Application state: Application state information is available to all pages. Regardless of which user requests a page. ASP.NET allows us to save values using application state. A global storage mechanism that is accessible from all pages in the web application. Application state is stored in the application key value dictionary. Once we add our application specific information to application state the server manages it and it is never exposed to the client. Application state in a place to store information that is not user specific. By storing it in the application state all pages can access data from a single location in memory rather than keeping separate copies of the data. The data stored in the application object is not permanent and is lost any time when the application is restarted. Session state:- ASP.NET allows us to save values using session state, a storage mechanism that is accessible from all pages requested by a single web browser session. Therefore we can use session state to store user specific information. Session state is similar to application state accept that it is scoped to the current browser session. If different users are using our application and each user session has a different session state. In addition if a user leaves our application and then returns later after the session time out period session state information is lost and a new session is created for the user. We can use session state to accomplish the following tasks.  Uniquely identify browser or client device requests and map them to individual session.  Store session specific data on the server for use across multiple browser or client device requests during the same session.

.NET Programming 44 www.ashagroup.org Advantage of State Statement: Advantage of client side state management:  Better scalability: With server side state management each client that connects to the web server consumes memory on the web server if a website has 100 or 1000 of simultaneous users the memory consumed by storing state management information can become a limiting factor. Pushing this load to the clients removes the potential bottle lock.  Supports multiple webservers: With client site state management we can describe incoming request access multiple web servers with no changes in our because the client provides all the information. The webserver needs to process.

Advantage of server side state management:  Better security: In server side state management we can apply password and other security options to store confidential information. We can authenticate users to use selected data.  Reduced bandwidth: If we store large amount of state management information back and forth to the client. It may increase bandwidth limitations. So the server side state management helps in reducing bandwidth requirement.

.NET Programming 45 www.ashagroup.org UNIT- IV ADO.NET: ADO.NET is the set of classes and tools built into the .NET framework that allows us to create powerful, scalable and reliable data driven application. Using ADO.NET we can connect to data base of all types including MS-SQL Server, MS Access, Oracle SQL, MySql and even some others. When connected to a database we can query and manipulate data in a wide variety of ways. ADO.NET Architecture: Data accessing ADO.NET relies on two components DataSet and Data Provider.

Data set: Data set is a disconnected, in memory representation of data. It can be consider as a local copy of relevant and portion of the database. The data set is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this data set is finished, changes can be made back to the control database for updating. The data in data set can be loaded from any valid data source like My SQL, Oracle SQL, MS SQL or MS Access etc.

.NET Programming 46 www.ashagroup.org Data provider: Data provider is responsible for providing and maintaining the connection to the database. A data provider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET framework currently comes with two data providers, one is designed to work only with Microsoft Sql Server7.0 or later. The second is OLEDB (Object Linking & Embedding Data Base), this data provider allows us to connect other type of database like Oracle, MySql and Access etc. Each data provider consists of the following component classes:  The connection object: The connection object creates the connection to the database. Visual Studio .NET provides two types of connection classes: the SQLConnectionObject, which is designed specifically to connect to MS-SQL Server 7.0 and above. OleDbConnection object, which provide connection to a wide range of database like MS Access, Oracle etc. The connection object contains all of the information required to open a connection to the database.  The command object: It is represented by two corresponding classes. SqlCommand and OleDbCommand. Command objects are used to execute commands to a data base across a data connection. The command objects can be used to execute stored procedures on the database. SQL command can return complete tables directly. Command objects provide three methods that are used to execute commands on the database. ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE, or DELETE. ExecuteScalar: Returns a single value from a database query. ExecuteReader: Return a result set by way of a DataReader object.  The DataReader Object: It provides a forward only, read only, and connected stream record set from a database unlike other components of the data provider. Data reader object can-not be directly instantiated rather the data reader is returned as the result of command object ExecuteReader method. The data reader can provide rows of data directly to application logic, when you do not need to keep the data cached in memory. Data reader provides the lowest overhead in terms of system performance but requires the exclusive use of an open connection object for the life time of the data reader.  The DataAdapter object: The DataAdapter is the class at the core of ADO.NET disconnected data access. DataAdapter is used either to fill a data table or data sets with its fill method. The data adapter can save the

.NET Programming 47 www.ashagroup.org changes to the database by calling the update method. The data adapter provides four properties to represent database commands: o Select command. o Insert command. o Delete command. o Update command. Connected and disconnected database: XML (Extensible Markup Language) is a fundamental part of ADO.NET and webserver. Connected ADO.NET application can query SQL server to return an XML result and then use the XML reader class to initiate the rows of XML data. Disconnected ADO.NET applications can use to dataset object to pass data in XML format between the different tiers in a distributed system. Create Connection Using ADO.NET Object Model: In most cases when working with data ADO.NET we need to establish a connection to the data source. This data source can be SQL server, oracle, MS Access or other type of data including file type source such as Paradox files or MS Excel documents etc. The connection is maintained in several steps as given below:- * Building a connection string: Connection strings are often semicolon delimited strings and certain the info that tells an ADO.NET data provider how to establish a link to the database for example:

Initial catalog = “student” ; server = “local host”; user id = st; password = “pwd”;

That connection string will open student database on the default sql server instance running on the local computer and it will authenticate as the system administrator for the user. To make a connection string we can also use a tool system data command, DB connection string builder. We can either use the derivative classes, for creating connection data provider. * Connection classes: When we have a connection string we are ready to connect to our source. A connection represents a live connection to the data source. In most cases that connection is a network connection between the ADO.NET data provider and the RDBMS server. Many data providers support the notion of connection pooling. When pooling is used connection are placed a pool when they are first created. When a pooled connection is closed it is returned to the pool instead of being terminated completely this connection can be reused.

.NET Programming 48 www.ashagroup.org * Executing commands: The command is the basic unit of work. When communicating with a data source commands are used to execute simple SQL statements, stored procedures, update or delete data and retrieve complex result sets. All commands inherit from the DbCommand class whether they are for MS-Sql Server, Oracle Sql or any other ADO.NET data provider. The sequence of code when working with a DbCommand is as follows: o Create an instance of a DbCommand derivative. o Create command parameters and populate parameters values. o Execute the command. o Handle the output or results of the command. Data Adapter Class: We have studied about DataSets and DataAdapters. A typed DataSet is really just a class that derives from System.Data.DataSet in order to provide a developer with a DataSet that is specific to one schema. As a result of this, any existing code that works on standard DataSets will also work on a typed DataSet, including DataAdapter. Dataset Classes: Data set is a set of data structure which is known at compile time allowing visual studio to create strong type wrappers for the tables, rows, columns, and relationship contents with in the data set. We can create a typed data set in several ways. The schema (meta data) including columns, tables, keys and relationships for the typed data set is translated using XSD (Xml Schema Definition). We can also create a typed data set by supplying an XSD file as input to the XSD.Exe command line tool. Display Data on Data-Bound Controls: We use data bound controls to generate our applications user interface for working with data. The data bound controls can be used to display and edit database data, XML data or just about any other type of data that we can imagine. There are three main type of data bound control and hierarchical data bound control. Working with list controls: Display list controls are used to display simple option lists. The ASP.NET 2.0 includes following five list controls:-  Bulleted list: Display a bulleted list of item. Each item can be displayed as text, a link button or a hyperlink.  Check box list: Display a list of checkboxes multiple checkbox in the list can be selected.

.NET Programming 49 www.ashagroup.org  Drop down list: Display a dropdown list only one item in the drop down list can be selected.  List box: Display a list box we can configure this control so that only one item or multiple items can be selected from it.  Radio button list: Display a list of radio buttons only one radio button can be selected. All five controls inherit from the same base list control class. The bulleted list control includes a data source id attribute which points to the id of the SQL data source control. Working with tabular data bound control: The tabular data bound controls are the main set of controls that we use when working with database. These controls enable us to display and modify data retrieved from a database or other type of data source. There are five tabular data bound controls. These controls can be divided into two types. First that display multiple data items at a time and second that display a single data item at a time. Grid view: Display a set of data item in an HTML table. Example: we can use the grid view control to display all the records contained in the database table. This control enables us to display sort, page, select and edit data. Data list:- Display a set of data item in an HTML table. It can display more than one data item in a single row. Repeater:- Display a set of data item using templates unlike the grid view and data list control. It does not automatically render an HTML table. Detail view:- Display a single data item in an HTML table. Form view:- It uses a template to display a single data item. It enables us to make layout of a form using template. Data grid control:- Data grid was included in ASP.NET 1.0 framework but it no longer used in the toolbox of visual web developer. The data grid id officially deprecated. We should use the grid view control instead of data control of data grid because grid view’s compatibility reasons. The data grid is included in the ASP.NET 2.0. Database Accessing on Web Application: Data binding concept with web: When we bind a data bound to a data source control, we are taking advantage of declarative data binding. The ASP.NET framework handles all the detail of deciding when to retrieve the data represented by a data source control. In certain situation we will want to handle these details ourselves. For example: we might want to force a grid view control to refresh the data

.NET Programming 50 www.ashagroup.org it display. After we add new record to a database table we might want to bind a data bound control to a data source that can be easily represented by one of the existing data source controls. In these situations we will want to use programmatic data binding. Every data bound control has a data source property and a data bound method. By using this property and method we can programmatically associate a data bound control with a data source. Almost all the data bound control support templates. We can use a template to format the layout and appearance each of the data items that a data bound control displays within a template. We can use a data binding expression to display the value of a data item. Data grid control: The one of the most powerful server control in asp.NET is the data grid control. The data grid control is a multiple data item ASP.NET server control. We can display records from a data base using a variety of formats. We can also edit, update and delete records from the database using the data grid control. Creating data grid: In our default web form add a data grid control to change the format of the data grid control, right click on it and select auto format. These are two ways in which we can configure the data grid control. 1 Using the property builder. 2 Modifying the HTML codes manually. Binding standard webserver control: A data binding expression is a special type of expression such as not evaluated until runtime. We mark a data binding expression in a page by wrapping the expression in opening < % # and closing % > brackets. A data binding expression is not evaluated until a control data binding event is raised. When we bind a data bound control to a data source control declaratively, this event is raised automatically. When we bind a data bound control to a data source programmatically, the data binding event is raised when we call the DataBind() method. Display Data on Web Form Using DataBound Control: A hierarchical databound control can be used to display nested data items. For example, we can use hierarchical databound control to display the folder and page structure of our website, the contents of an XML file, or a set of master/detail database records. The ASP.NET 2.0 have two hierarchical databound control. Menu: to display data items in a static or dynamic menu

.NET Programming 51 www.ashagroup.org Treeview: to display data items in a tree.

.NET Programming 52 www.ashagroup.org UNIT – V Introduction to XML: XML is a text based format for describing data. XML stands for Extensible Markup Language. XML is a way of marking up data, adding metadata and separating structure from formatting and style. Web pages are just one of many users for XML. With XML we can store information of our document. Features of XML:  XML is extensible: it means we can easily extend it by adding our own custom tags.  It is text based, it means we can create or read XML with any text editor, such as notepad.  XML can be used with existing protocols.  XML supports wide variety of application.  XML is compatible with SGML (Standard General Markup Language).

Reading and Writing DataSets in XML: The main feature of ADO.NET is provided by the dataset object. This object reads the database and creates an in memory copy of that part of the database that our program needs. Usually a Dataset object will correspond to a real database table or view, but dataset is disconnected view of the database data. After ADO.NET creates the data set, there is no longer an active connection to the database. This helps a lot in scalability because our program only has to connect with a database server when reading or writing from the database. Some of advantages of the new dataset object are:  Read/Write  Connectionless  Contains one or more data table objects with relationships defined in a collection of DataRelation objects.  Supports filtering and sorting.  The contained DataView object can be bound to data aware forms controls.  Supports automatic XML serialization.

.NET Programming 53 www.ashagroup.org One of the biggest differences between DataSet and the old RecordSet is that data in ADO.NET is transported in XML format. That makes it a structured text document that can be read by anyone on any platform. This makes DataSet interoperable among a lot of computers. After we create an XML document using methods provided by DataSet, we can parse it in .NET programmatically using the System.Xml.XmlDocument object.

Remote Method Call Using XML: SOAP SOAP stands for Simple Object Access Protocol. SOAP is a protocol specification for exchanging structured information in the implementation of web services. SOAP provides mechanisms for requesting information from endpoints or from resources. SOAP has three major characteristics: extensibility (security and routing are among the extensions under development), neutrality (SOAP can be used over any transport protocol such as HTTP, SMTP, TCP, UDP, or JMS), and independence (SOAP allows for any programming model). SOAP Message: The SOAP is a new standard that allows clients to send data to servers. SOAP relies on XML to relay its information instead of http request message. It means that soap can send not only name pairs but more complex object such as various rich data type classes, objects and others. Soap information is transported via http. It can be used to send any type of message whether a client requested them or not. Soap is based on XML. So we can use it to transfer data around the web as pure text or including firewalls. This is default protocol that web services use to communicate with client. Web Services Overview: A is programmable application, logical accessible via standard web protocol. One of these protocols is the SOAP (Simple Object Access Protocol). SOAP is a W3C submitted note that uses standard based technologies to encode and transmit application data. Consumers of a web service do not need to know anything about the platform object model or performing language used to implement the service. They only need to understand how to send and receive SOAP messages. ASP.NET Web Services: Web services are simple and easy to understand, it is possible to author simple application that surfaces data as XML conforming to the soap specification. It would also be relatively state

.NET Programming 54 www.ashagroup.org forward to build an application capable of receiving soap messages over http and deriving meaning full value out of it from a developers point of view. If we have ever written application logic we have the required skills to author ASP.NET web services. Web Services Description Language (WSDL):- WSDL is an XML based language that provides a model to describe web services. The WSDL defines services as collection of network end points. The WSDL specification provides an XML format for documents for this purpose. The abstract definition of ports and messages is separated from their concrete use of instances definitions. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Messages are abstract descriptions of the data being exchanged and port types are abstract collection of supported operations. WSDL is often used in combination with soap and xml schema to provide web services over the internet. A client program connecting to web service can read the WSDL to determine what functions are available on the server. Any special data types used are embedded in the WSDL file in the form of XML schema. The client can then use soap to actually call on of the functions listed in the WSDL.

Binding and consuming a web service: Rather than jumping straight into the performance counters we should start with some very simple application logic so we can see what we need to do to expose our logic as a web service. In our example we will use add () method that accepts two integer and returns their sums. public class mymath { public add (int a, int b) { return a + b ; } }; To expose the above class mymath as an ASP.NET web services we need to move the application logic into a *.asmx file just as we use the extension *.aspx for ASP.NET pages. We use *.asmx to tell ASP.NET that the file is an ASP.NET web service. After we created the *.asmx source file and add our application logic we need to make few more small changes. These changes may include adding a web service directive that names both the

.NET Programming 55 www.ashagroup.org language as well as the class we are exposing as a web service. The web service directive is required as we must tell ASP.NET the class that contains the application logic. We can add an attribute to our add method. An attribute is a declarative code element that lets us change the behavior of our application logic without necessary writing more code.

Performance counter web service: We can declare a web service direction at the top of the file nothing both the language and the class. The class may contain web callable method. When we call that method it creates a new instance of the class and begins to set its public members. These public members should be implanted as properties.

Testing web service: After creating ASP.NET web service we need to test it. The consumer of a web service is another application but ASP.NET provides a simple browser interface to our web service that we can use for testing documentation purpose. Since our web service is represented as a resource available from our web server. We can simply open a browser and make a request for that resource. Doing so provides us with a nice HTML based web service help page.

Web Applications Deployment: After creating and testing our ASP.NET applications the next step is to deploy the application. Deployment is the process of distributing the finished application to be installed on other computer. We can use the built in deployment feature that commons with Visual Studio.NET. It create a window installer file (a .MSI file) for the purpose of deploying applications. Deploying Applications: To start open the web application project we want to deploy for example: if we have a project named deploy with ten web pages in it select file  add project  new project from the main menu. From project type pane select setup and deployment project from the template pane select the web setup project. Type web setup 1 for name and specify a location in the location box and click ok. When we click on ok button the project is added to the solution explorer window and also a file system editor window. The file system editor window has two panes. Select web application folder in the left pane in this window from the action menu select project output to open the add project output group dialog box. Make sure that the project name display is selected in the project dropdown list and click ok. We can

.NET Programming 56 www.ashagroup.org also select other options depending upon the users of our application. Now in the file system editor window select web application folder and open its property window. In this window set the virtual directory property to any name for example: Finished app will be the folder on the install this application. The name we set for this virtual directive property should not already exists on the target machine if it does the content in the folder will be overwritten also set the default document property to only page in the application. The page we set in this property will be default page for the web application. Once we are finished with the properties window built the solution by selecting built websetup1. After the solution is built successful web setup1 MSI file is created in the debug directory of web setup project. Installing the application: We can copy the web setup 1 MSI file to the target 1 MSI file to the target machine and double click to install the web application when we double click the setup file a wizard will start. We can click on next button. We can use default virtual directory specified by the installer or we can specify as our need.