ASP.Net Unit 1 .pdf
Document Details
Uploaded by Deleted User
Full Transcript
1. Introduction to ASP.NET 1.1. What is ASP.NET? ASP.NET is a server-side web technology developed by Microsoft to build dynamic, interactive and database-driven web applications. ASP.NET is a subset of Microsoft.NET framework. ASP.NET is the successor version to classic ASP (Active Server Pages)....
1. Introduction to ASP.NET 1.1. What is ASP.NET? ASP.NET is a server-side web technology developed by Microsoft to build dynamic, interactive and database-driven web applications. ASP.NET is a subset of Microsoft.NET framework. ASP.NET is the successor version to classic ASP (Active Server Pages). ASP.NET is a mix of HTML and Server-side scripting to generate dynamic and interactive web pages and applications. ASP.NET is a technology, which works on the.Net framework that contains all web-related functionalities. The.Net framework is made of an object-oriented hierarchy. An ASP.NET web application is made of pages. When a user requests an ASP.NET page, the IIS delegates the processing of the page to the ASP.NET runtime system. The ASP.NET application codes can be written in any of the following languages: C#.Net Visual Basic.Net JScript.NET J#.Net Disadvantages of ASP Poor Re-usability – ASP pages are interpreted and executed on the Web server, line-by-line, from top to bottom. Each page is therefore written in a sequential manner to meet specific objectives, which makes it difficult to re-use the page in another ASP application. Supports only scripting languages – Scripting languages are limited in functionality when compared to programming languages. Most developers who have worked with programming languages wish to use the full functionality of a programming language to develop complex Web applications. Moreover, scripting languages are interpreted and not compiled. This affects performance as the ASP scripts must be parsed and executed every time a request is made. No separation of code and presentation – Scripts in ASP pages are mixed with the HTML code and executed in-line with it. This makes it very difficult to read and understand an ASP application written by somebody else. So, project development, involving multiple team members and project maintenance are both made difficult. Poor support for state management – ASP does not provide built-in support for retaining the state of HTML forms. Developers have to write additional code to save the data entered by users in form fields during post-backs and restore the data in the form before returning the form to the users. Poor support for multiple browsers – Different browsers support ASP to different extents. In order to support multiple browsers, developers have to explicitly write different versions of the code. ASP.NET attempts to overcome these drawbacks and makes the web applications easy and efficient Advantages of ASP.NET Support for.NET Framework – ASP.NET is a part of the.NET Framework. The.NET Framework provides almost 13,000 classes that can be used in ASP.NET pages. Support for programming languages. Platform Independent. Web services. Client platform Independence. Characteristics of ASP.NET ASP.NET Web Forms Pages ASP.NET Controls Cross-Language Support. Event-Driven Programming Model Data Access: ASP.NET supports ADO.NET provided by the.NET Framework. Session State Management Deployment: ASP.NET applications can be deployed by simply copying the files to the appropriate directory on the Web server. Error handling, Debugging, and Tracing. Security Management: To secure an ASP.NET application, you must perform the three fundamental functions, authentication, authorization, and impersonation. Authentication: such as name and password are validated. Authorization: It limits access rights by granting or denying specific permissions to an authenticated identity. 1.2..Net framework 2.0 After the success of.Net Framework 1.1, Microsoft released the compact version of the framework and named as.Net Framework 2.0. This version focuses primarily on increasing the developer’s productivity. The version was updated with new features in ADO.NET like asynchronous database operations, XML data types, user-defined types (UDT), and snapshot isolation. In addition, it includes significant advancements in all areas of ASP.Net like new data controls, enhanced code-behind model, caching features and many more. Features of.Net Framework 2.0: 64-Bit Platform Support The new generation of 64-bit computers enables the creation of applications that can run faster and take advantage of more memory than is available to 32-bit applications. New support for 64-bit applications enables users to build managed code libraries or easily use unmanaged code libraries on 64-bit computers. Access Control List Support An access control list (ACL) is used to grant or revoke permission to access a resource on a computer. ADO.NET New features in ADO.NET include support for user-defined types (UDT), asynchronous database operations, XML data types, large value types, snapshot isolation, and new attributes that allow applications to support multiple active result sets (MARS) with SQL Server 2005. ASP.NET The Microsoft.NET Framework 2.0 includes significant enhancements to all areas of ASP.NET. For Web page development, new controls make it easier to add commonly used functionality to dynamic Web pages. Data Protection API The new Data Protection API (DPAPI) includes four methods that allow applications to encrypt passwords, keys, connections strings, and so on, without calling platform invoke. Debugger Display Attributes The.NET Framework 2.0 reintroduces the Edit and Continue feature that enables a user who is debugging an application in Visual Studio to make changes to source code while executing in Break mode. After source code edits are applied, the user can resume code execution and observe the effect. FTP Support Applications can now access File Transfer Protocol resources using the WebRequest, WebResponse, and WebClient classes. I/O Enhancements Improvements have been made to the usability and functionality of various I/O classes. It is now easier for users to read and write text files and obtain information about a drive. Ping The Ping class allows an application to determine whether a remote computer is accessible over the network. This class provides functionality similar to the Ping.exe command-line tool, and supports synchronous and asynchronous calls. Programming Languages Four Microsoft programming languages explicitly target the.NET Framework: Visual C#, Microsoft C/C++, Visual J#, and Visual Basic. Security Exceptions The System.Security.SecurityException class has been expanded to provide additional data that facilitates investigation into the cause of security exceptions. Visual Basic Compiler and Language Language improvements in Visual Basic simplify source code and enable interaction with components that use advanced features. 1.3. Compile Code In order for application code to service requests by users, ASP.NET must first compile the code into one or more assemblies. Assemblies are files that have the file name extension.dll. You can write ASP.NET code in many different languages, such as Visual Basic, C#, J#, and others. When the code is compiled, it is translated into a language-independent and CPU-independent representation called Microsoft Intermediate Language (MSIL). At run time, MSIL runs in the context of the.NET Framework, which translates MSIL into CPU-specific instructions for the processor on the computer running the application. There are many benefits to compiling application code including: Performance The execution of the compile code is faster than the scripts such as VBScript which is much similar to the machine code. Stability When the code is compiled, it is checked for syntax error, type safety, etc so that many errors can be eliminated from the later stage. Security Compile code is difficult to read. So no one can convert compiled code into source code. Interoperability We are Able to use assemblies written in different languages as MSIL supports any.NET language. 1.3.1. Code Behind and Inline Coding What is Code Behind? Code Behind refers to code for ASP.NET page which is contained within a separate class file. It is composed in a different class record that can have the extension of.aspx.cs or.aspx.vb relying upon the language used. It allows a clean separation of HTML from the presentation logic. In the code-behind file, you create a class (which can be any class derived from the Page class) that serves as the base class for the web page you create in the.aspx file. This relationship between your class and the web page is established by a Page directive at the top of the.aspx file The inherits attribute identifies the class created in the code-behind file from which this.aspx file will derive. One major point of Code Behind is that the code for all the Web pages is compiled into a DLL file that allows the web pages to be hosted free from any Inline Server Code. What is Inline Code? Inline Code is embedded directly within the ASP.NET page that has an extension of.aspx. It permits the code to be composed along with the HTML source code using a < Script > tag. When the page is deployed, the source code is deployed along with the Web Forms page, because it is physically in the.aspx file. However, you do not see the code, only the results are rendered when the page runs. 1.4. The Common Language Runtime The heart of.NET Framework is a run-time environment called the common language runtime (CLR). The CLR manages the life cycle and executes.NET applications (code). It also provides services that make the development process easier. Key attributes of.NET CLR As part of the Microsoft.NET Framework, the Common Language Runtime (CLR) is the programming (Virtual Machine component) that manages the execution of programs written in any language that uses the.NET Framework, for example C#, VB.Net, F# and so on. Programmers write code in any language, including VB.Net, C# and F# yhen they compile their programs into an intermediate form of code called CLI in a portable execution file (PE) that can be managed and used by the CLR and then the CLR converts it into machine code to be will executed by the processor. The information about the environment, programming language, its version and what class libraries will be used for this code are stored in the form of metadata with the compiler that tells the CLR how to handle this code. The CLR allows an instance of a class written in one language to call a method of the class written in another language. Functions of.NET CLR Convert code into CLI Exception handling Type safety Memory management (using the Garbage Collector) Security Improved performance Language independency Platform independency Architecture independency Components of.NET CLR The key components of CLR include the following: Class Loader - Used to load all classes at run time. MSIL to Native code - The Just In Time (JTI) compiler will convert MSIL code into native code. Code Manager - It manages the code at run time. Garbage Collector - It manages the memory. Collect all unused objects and reallocate them to reduce memory. Thread Support - It supports multithreading of our application. Exception Handler - It handles exceptions at run time. Benefits of.NET CLR The runtime provides the following benefits: Performance improvements. The ability to easily use components developed in other languages. Extensible types provided by a class library. Language features such as inheritance, interfaces, and overloading for object-oriented programming. Support for explicit free threading that allows creation of multithreaded, scalable applications. Support for structured exception handling. Support for custom attributes. Garbage collection. Use of delegates instead of function pointers for increased type safety and security. 1.5. Object Oriented Concepts OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re- usability by means of four main object-oriented programming concepts. Below are object oriented programming concepts : Object Object is representative of the class and is responsible for memory allocation of its data members and member functions. An object is a real world entity having attributes (data type) and behaviors (functions). An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object behavior. For example, the hand can grip something or a Student (object) can give the name or address Class Class is a data structure that contains data members (constants files, events), member function methods, properties, constructor, destructor, indexers and nested type.Basically It is a user defined data type. It is a reference type. In fact class is a tag or template for object. Encapsulation Encapsulation is a mechanism of binding the data member & member function into a single unit known as class. Encapsulation provides a way for abstraction. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. Data abstraction Data abstraction is a mechanism to provide the essential features without describing the background details. Means provide the functions to access the hidden (private) data. The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs. Data Hiding Data hiding is a mechanism to hide the internal structure of an object from rest of the program.In a class private members are hidden from the rest of the program, hence it supports data hiding. Data hiding is also a way to implement data abstraction. Polymorphism Polymorphism means one thing in many form. Basically polymorphism is capability of one object to behave in multiple ways. Example : A man role changes at home, college, and outside the home. There are following types of polymorphism : 1. Static polymorphism (compile time) : It is achieved using function overloading and operator overloading. 2. Dynamic polymorphism (runtime time) : It is achieved using function overriding means using virtual function. 1.6. Event Driven Programming There are two programming approaches: Linear and Event Driven. Any identifiable occurrence that has significance for system hardware or software is called the Event. So we can say that, Event is the action or the occurrence that is declared by the program. User-generated events include keystrokes & mouse clicks, among a wide variety of other possibilities. The programming approach, which response to the event or handle the event is called Event Driven Programming. Windows operating system is the Event Driven Program (EDP). ASP.NET Event Model Traditional ASP uses the Linear Model. It means that the code on the page is executed from top to bottom, whenever the page is loaded. But ASP.NET uses Event Driven Model. User can add controls on the page and according to the need we can decide which event will respond. Here each event handler is the separate method. ASP.NET works as follows: 1. When the page is executed for the first time, it creates the page and control objects. Along with, the initialization code is executed and the page is rendered. 2. After the page is served to the user, any events can be triggered due to the action performed by the user. 3. If the Button Click () event generates the postback of the form. ASP.NET responds the page by re-creating it. 4. Then it raises the appropriate event which has triggered the postback. 5. At last the modified page is rendered to HTML and served to the client. Application and Session Events The most important application events are: Application_Start - It is raised when the application/website is started. Application_End - It is raised when the application/website is stopped. Similarly, the most used Session events are: Session_Start - It is raised when a user first requests a page from the application. Session_End - It is raised when the session ends. Page and Control Events Common page and control events are: DataBinding - It is raised when a control binds to a data source. Disposed - It is raised when the page or the control is released. Error - It is a page event, occurs when an unhandled exception is thrown. Init - It is raised when the page or the control is initialized. Load - It is raised when the page or a control is loaded. PreRender - It is raised when the page or the control is to be rendered. Unload - It is raised when the page or control is unloaded from memory. When a page is requested, it is loaded into the server memory, processed, and sent to the browser. Then it is unloaded from the memory. At each of these steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code. The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives, are part of this control tree. You can see the control tree by adding trace= "true" to the page directive. We will cover page directives and tracing under 'directives' and 'event handling'. The page life cycle phases are: Initialization Instantiation of the controls on the page Restoration and maintenance of the state Execution of the event handler codes Page rendering Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view- state data and run control behavior code. Following are the different stages of an ASP.NET page: Page request - When ASP.NET gets a page request, it decides whether to parse and compile the page, or there would be a cached version of the page; accordingly the response is sent. Starting of page life cycle - At this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set. Page initialization - At this stage, the controls on the page are assigned unique ID by setting the UniqueID property and the themes are applied. For a new request, postback data is loaded and the control properties are restored to the view-state values. Page load - At this stage, control properties are set using the view state and control state values. Validation - Validate method of the validation control is called and on its successful execution, the IsValid property of the page is set to true. Postback event handling - If the request is a postback (old request), the related event handler is invoked. Page rendering - At this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Response property of page. Unload - The rendered page is sent to the client and page properties, such as Response and Request, are unloaded and all cleanup done. ASP.NET Page Life Cycle Events At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle. Following are the page life cycle events: PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls, and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler. Init - Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler. InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state tracking. LoadViewState - LoadViewState event allows loading view state information into the controls. LoadPostData - During this phase, the contents of all the input fields are defined with the tag are processed. PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler. Load - The Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler. LoadComplete - The loading process is completed, control event handlers are run, and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler PreRender - The PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered. PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase. SaveStateComplete - State of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler. UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.