ASP.net Foundations Walid Ward Senior .Net Developer [email_address]
CHAPTER 1 Introducing ASP.NET
CHAPTER 2 Visual Studio
CHAPTER 3 Web Forms
CHAPTER 4 Server Controls
CHAPTER 5 ASP.NET Applications
CHAPTER 6 State Management
Introducing ASP.NET Asp.net History
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. What Is Asp.net Asp. Net Versions Version Version Number Release Date Visual Studio Default in Windows 1.0 1.0.3705.0 2002-02-13 Visual Studio .NET 1.1 1.1.4322.573 2003-04-24 Visual Studio .NET 2003 Windows Server 2003 2.0 2.0.50727.42 2005-11-07 Visual Studio 2005 3.0 3.0.4506.30 2006-11-06 Windows Vista, Windows Server 2008 3.5 3.5.21022.8 2007-11-19 Visual Studio 2008 Windows 7, Windows Server 2008 R2 4.0 Beta 1 2009-05-20 Visual Studio 2010
Common Language Runtime C:WindowsMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET Files
MSIL C# complier VB.net complier
Requirements to learn Asp.net:
You don’t need to have experience with a previous version of ASP.NET.
Understanding one of the programming language (C#, VB.net, …).
The basics of .NET Framework.
Differences between ASP.NET and earlier web development platforms :
ASP.NET features a completely object-oriented programming model.
ASP.NET gives you the ability to code in any supported .NET languages .
ASP.NET is dedicated to high performance , components are compiled on demand, tuned data access model and flexible data caching .
Asp.net Facts :
ASP.NET Is Integrated with the .NET Framework.
ASP.NET Is Compiled, Not Interpreted .
ASP.NET Is Multilanguage.
ASP.NET Is Hosted by the Common Language Runtime.
ASP.NET Is Object-Oriented.
ASP.NET Is Multidevice and Multibrowser.
ASP.NET Is Easy to Deploy and Configure.
Visual Studio IDE
The Visual Studio IDE:
Visual Studio’s advantages:
An integrated web server.
Less code to write:
Intuitive coding style.
Faster development time.
IntelliSense and Outlining.
Visual Studio interface :
Choosing code Model
The ASP.NET File Types The Toolbox Tabs Description File Type Serial Aspx . 1 .ascx 2 .asmx 3 web.config 4 global.asax 5 .VB, .Cs 6 Description File Type Serial Standard 1 Data 2 Validation 3 Navigation 4 Login 5 Web Parts 6 HTML 7 General 8
Error List Task List
Migrating a Website from a Previous Version of Visual Studio
Web Forms: ASP.NET pages (officially known as web forms) are a vital part of an ASP.NET application. They provide the actual output of a web application—the web pages that clients request and view in their browsers. Web applications execute on the server: For example, suppose you create a form that allows the user to select a product record and update its information (updating the database), your code needs to run on the web server. Postback: which sends the page (and all user-supplied information) to the server when certain actions are performed. Web applications are stateless: In other words, before the rendered HTML page is sent to the user, your web-page objects are destroyed and all client-specific information is discarded. ASP.NET includes several tools to help you bridge this gap; most notable is a persistence mechanism called view state, which automatically embeds information about the page in a hidden field in the rendered HTML. Web forms
Simple HTML web Form
Asp.Net Pages Requests
ASP.Net 3.5 XHTML Compliance:
Tag and attribute names must be in lowercase.
All elements must be closed, either with a dedicated closing tag (<p></p>) or using an empty tag that closes itself (<br />).
All attribute values must be enclosed in quotes (for example, runat="server").
The id attribute must be used instead of the name attribute. (ASP.NET controls render both an id and name attribute.)
View State Chunking: The size of the hidden view state field has no limit. However, some proxy servers and firewalls refuse to let pages through if they have hidden fields greater than a certain size. To circumvent this problem, you can use view state chunking, which automatically divides view state into multiple fields to ensure that no hidden field exceeds a size threshold you set.
Web Forms Processing Stages:
User Code Initialization:
At this stage of the processing, the Page.Load event is fired. Most web pages handle this event to perform any required initialization .
// It's safe to initialize the controls for the first time.
FirstName.Text = "Enter your name here";
ASP.NET includes validation controls that can automatically validate other user input controls and display error messages.
At this point, the page is fully loaded and validated. ASP.NET will now fire all the events that have taken place since the last postback. ASP.NET events are of two types:
Immediate response events.
The Page Class:
All web forms are actually instances of the ASP.NET Page class, which is found in the System.Web.UI namespace deriving from the Page class, any page depending on these objects:
Session: The Session object is an instance of the System.Web.SessionState.HttpSessionState class. It’s designed to store any type of user-specific data that needs to persist between web-page requests
Request: The Request object is an instance of the System.Web.HttpRequest class. This object represents the values and properties of the HTTP request that caused our page to be loaded. It contains all the URL parameters and all other information sent by a client.
HttpRequest Properties: Description Property # This uniquely identifies the current user if you’ve enabled anonymous access. You’ll learn how to use the anonymous access features in Chapter 24. AnonymousID 1 ApplicationPath gets the ASP.NET application’s virtual directory (URL), while PhysicalApplicationPath gets the “real” directory. ApplicationPath and PhysicalApplicationPath 2 This provides a link to an HttpBrowserCapabilities object, which contains properties describing various browser features, such as support for ActiveX controls, cookies, VBScript, and frames Browser 3 This is an HttpClientCertificate object that gets the security certificate for the current request, if there is one. ClientCertificate 4 This gets the collection of cookies sent with this request. Cookies 5 These return the real file path (relative to the server) for the currently executing page. FilePath gets the page that started the execution process. This is the same as CurrentExecutionFilePath, unless you’ve transferred the user to a new page without a redirect FilePath and CurrentExecutionFilePath This represents the collection of form variables that were posted back to the page. In almost all cases, you’ll retrieve this information from control properties instead of using this collection Form 6 These provide a dictionary collection of HTTP headers and server variables, indexed by name. These collections are mostly made up of low-level information that’s sent by the browser along with its web request (such as the browser type, its support for various features, its language settings, its authentication credentials, and so on). Usually, you can get this information more effectively from other properties of the HttpRequest object and higher-level ASP.NET classes. Headers and ServerVariables 7
Response: The Response object is an instance of the system.Web.HttpResponse class, and it represents the web server’s response to a client request.
Description Member # When set to true (the default), the page isn’t sent to the client until it’s completely rendered and ready to be sent BufferOutput 1 This references an HttpCachePolicy object that allows you to configure output caching. Cache 2 This is the collection of cookies sent with the response. You can use this property to add additional cookies. Cookies 3 You can use these properties to cache the rendered HTML for the page, improving performance for subsequent requests. Expires and ExpiresAbsolute 4 This is a Boolean value indicating whether the client is still connected to the server. If it isn’t, you might want to stop a timeconsuming operation. IsClientConnected 5 This method transfers the user to another page in your application or a different website Redirect() 6
Server: The Server object is an instance of the System.Web.HttpServerUtility class. It provides a handful of miscellaneous helper methods and properties.
Description Member # A property representing the computer name of the computer on which the page is running. This is the name the web server computer uses to identify itself to the rest of the network. MachineName() 1 Retrieves the exception object for the most recently encountered error (or a null reference, if there isn’t one). This error must have occurred while processing the current request, and it must not have been handled. This is most commonly used in an application event handler that checks for error conditions GetLastError() 2 Changes an ordinary string into a string with legal HTML characters (and back again). HtmlEncode() and HtmlDecode() 3 Changes an ordinary string into a string with legal URL characters (and back again). UrlEncode() and UrlDecode() 4 Performs the same work as UrlEncode() and UrlDecode(), except they work on a byte array that contains Base64-encoded data. UrlTokenEncode() and UrlTokenDecode() 5 Returns the physical file path that corresponds to a specified virtual file path on the web server. MapPath() 6 Transfers execution to another web page in the current application. This is similar to the Response.Redirect() method, but it’s faster. It cannot be used to transfer the user to a site on another web server or to a non-ASP.NET page (such as an HTML page or an ASP page). Transfer() 7
User : The User object represents information about the user making the request of the web server, and it allows you to test that user’s role membership. Trace: The Trace object is a general-purpose tracing tool (and an instance of the System.Web.TraceContext class). It allows you to write information to a log that is scoped at the page level. This log has detailed timing information so that not only can you use the Trace object for debugging but you can also use it for performance monitoring and timing. Additionally, the trace log shows a compilation of miscellaneous information, grouped into several sections
Trace Log Information: Description Member # This section includes some basic information about the request context, including the current session ID, the time the web request was made, and the type of web request and encoding. Request Details 1 This section shows the different stages of processing the page went through before being sent to the client. Each section has additional information about how long it took to complete, as a measure from the start of the first stage (From First) and as a measure from the start of the previous stage (From Last). Trace Information 2 The control tree shows you all the controls on the page, indented to show their hierarchy, similar to the control tree example earlier in his chapter. One useful feature of this section is the Viewstate column, which tells you how many bytes of space are required to persist the current information in the control. This can help you gauge whether enabling control state could affect page transmission times. Control Tree 3 These sections display every item that is in the current session or application state. Each item is listed with its name, type, and value. If you’re storing simple pieces of string information, the value is straightforward. If you’re storing an object, .NET calls the object’s ToString() method to get an appropriate string representation. Session State and Application State 4 This section displays all the cookies that are sent with the response, as well as the content and size of each cookie in bytes. Even if you haven’t explicitly created a cookie, you’ll see the ASP.NET_SessionId cookie, which contains the current session ID. If you’re using formsbased authentication, you’ll also see the security cookie Cookies Collection 5 This section lists all the HTTP headers associated with the request Headers Collection 6 This section lists the posted-back form information Forms Collection 7 This section lists the variables and values submitted in the query string. QueryString Collection 8 This section lists all the server variables and their contents Server Variables 9
Basic Trace Information:
Types of Server Controls :
HTML server controls
Web parts controls
ASP.NET AJAX controls
ASP.NET mobile controls
ASP.NET Applications: is a combination of files, pages, handlers, modules, and executable code that can be invoked from a virtual directory (and its subdirectories) on a web server. Unlike a Windows application, the end user never runs an ASP.NET application directly. Instead, a user launches a browser such as Internet Explorer and requests a specific URL (such as http://www.mysite.com/mypage.aspx) over HTTP. This request is received by a web server.
The Application Domain ( lazy initialization ):
An application domain is a boundary enforced by the CLR that ensures that one application can’t influence (or see the in-memory data) of another .
All the web pages in a single web application share the same in-memory resources, such as global application data, per-user session data, and cached data. ASP.NET applications can include all of the following ingredients:
Web pages (.aspx files)
Web services (.asmx files)
A configuration file (web.config)
Application Updates : Being able to update any part of an application at any time without interrupting existing requests is a powerful feature. ( shadow copy c:WindowsMicrosoft.NET v2.0.50727Temporary ASP.NET Files.)
Application Directory Structure:
Every web application should have a well-planned directory structure. Independently from the directory structure you design, ASP.NET defines a few directories with special meanings like:
Configuration in ASP.NET is managed with XML configuration files. All the information needed to configure an ASP.NET application’s core settings, as well as the custom settings specific to your own application, is stored in these configuration files.
They are never locked.
They are easily accessed and replicated.
They are easy to edit and understand.
The machine.config File
The configuration starts with a file named machine.config that resides in the directory c:WindowsMicrosoft.NETFrameworkv2.0.50727Config.
Defines supported configuration file sections,
Configures the ASP.NET worker process
Registers providers that can be used for advanced features such as profiles, membership, and role-based security
Machine Key: This section allows you to set the server-specific key used for encrypting data and creating digital signatures. You can use encryption in conjunction with several ASP.NET features. ASP.NET uses it automatically to protect the forms authentication cookie, and you can also apply it to protected view state data.
The web.config File : Every web application inherits the settings from the machine.config file and the root web.config file.
New Configuration Sections for ASP.NET 3.5
. Configuration Inheritance : ASP.NET uses a multilayered configuration system that allows you to use different settings for different parts of your application. http://localhost/A/B/C/MyPage.aspx , 1 . The default machine.config settings are applied first. 2. The web.config settings from the computer root are applied next. 3. If there is a web.config file in the application root A, these settings are applied next. 4. If there is a web.config file in the subdirectory B, these settings are applied next. 5. If there is a web.config file in the subdirectory C, these settings are applied last
The Website Administration Tool (WAT): This tool is called the WAT, and it lets you configure various parts of the web.config file using a web-page interface. To run the WAT to configure the current web application in Visual Studio, select Website ➤ ASP.NET Configuration (or Project ➤ ASP.NET Configuration if you’re using project based development).
Encrypting Configuration Sections:
ASP.NET never serves requests for configuration files, because they often contain sensitive information. However, even with this basic restriction in place, you may want to increase security by encrypting sections of a configuration file.
ASP.NET supports two encryption options:-
HTTP Handlers : Every request into an ASP.NET application is handled by a specialized component known as an HTTP handler. The HTTP handler is the backbone of the ASP.NET request processing framework. ASP.NET uses different HTTP handlers to serve different file types HTTP modules: participate in the processing of a request by handling application events, much like the global.asax file. A given request can flow through multiple HTTP modules, but it always ends with a single HTTP handler The ASP.NET request processing architecture
ASP.NET State Management: No web application framework, no matter how advanced, can change the fact that HTTP is a stateless protocol . After every web request, the client disconnects from the server, and the ASP.NET engine discards the objects that were created for the page. This architecture ensures that web applications can scale up to serve thousands of simultaneous requests without running out of server memory. The drawback is that your code needs to use other techniques to store information between web requests and retrieve it when needed View state: View state should be your first choice for storing information within the bounds of a single page . View state is used natively by the ASP.NET web controls. It allows them to retain their properties between postbacks. You can add your own data to the view state collection using a built-in page property called ViewState. The type of information you can store includes simple data types and your own custom Objects. The Query String : Example : http://www.google.ca/search?Name=Walid The query string is the portion of the URL after the question mark. In this case, it defines a single variable named q , which contains the “ Walid ” string. State Management
Cookies: Custom cookies provide another way you can store information for later use. Cookies are small files that are created on the client’s hard drive , also can be easily used by any page in your application and even retained between visits.
How ViewStates Looks Like
State Management Options Compared:
Session State: Session state is the heavyweight of state management. It allows information to be stored in one page and accessed in another, and it supports any type of object, including your own custom data types.
Application State: Application state allows you to store global objects that can be accessed by any client. Application state is based on the System.Web.HttpApplicationState class, which is provided in all web pages through the built-in Application object.
Pro ASP.NET 3.5 in C# 2008 Second Edition .
About the Authors:
He is an author, educator, and Microsoft MVP. He’s a regular contributor to programming journals and the author of more than a dozen books about .NET programming, including Pro WPF: Windows Presentation Foundation in .NET 3.0 (Apress, 2007), Beginning ASP.NET 3.5 in C# 2008 (Apress, 2007), and Pro .NET 2.0 Windows Forms and Custom Controls in C# (Apress, 2006).
works as an architect in the Developer and Platform Group of Microsoft Austria, and helps software architects of top enterprise and web customers with establishing new Microsoft technologies. For several years