50
ASP.net Foundations ASP.net Foundations Walid Ward Senior .Net Developer [email protected]

Asp.net Foundation

Embed Size (px)

Citation preview

Page 1: Asp.net Foundation

ASP.net FoundationsASP.net Foundations

Walid WardSenior .Net [email protected]

Page 2: Asp.net Foundation

.Net Framework

Page 3: Asp.net Foundation

Contents

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

Page 4: Asp.net Foundation

Introducing ASP.NET

Asp.net History

Page 5: Asp.net Foundation

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

VersionVersion Number

Release Date Visual StudioDefault in Windows

1.0 1.0.3705.0 2002-02-13 Visual Studio .NET

1.1 1.1.4322.573 2003-04-24Visual 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-06Windows Vista, Windows Server 2008

3.5 3.5.21022.8 2007-11-19 Visual Studio 2008Windows 7, Windows Server 2008 R2

4.0 Beta 1 2009-05-20 Visual Studio 2010

Asp. Net Versions

Page 6: Asp.net Foundation
Page 7: Asp.net Foundation

Common Language Runtime

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files

Page 8: Asp.net Foundation

MSILMSIL

C# complierC# complierVB.net complierVB.net complier

Page 9: Asp.net Foundation

Requirements to learn Asp.net:You don’t need to have experience with a previous version of ASP.NET.1.Understanding one of the programming language (C#, VB.net, …).2.The basics of .NET Framework.

Differences between ASP.NET and earlier web development platforms :1.ASP.NET features a completely object-oriented programming model.2.ASP.NET gives you the ability to code in any supported .NET languages.3.ASP.NET is dedicated to high performance, components are compiled on demand, tuned data access model and flexible data caching .

Asp.net Facts :1.ASP.NET Is Integrated with the .NET Framework.2.ASP.NET Is Compiled, Not Interpreted .3.ASP.NET Is Multilanguage.4.ASP.NET Is Hosted by the Common Language Runtime.5.ASP.NET Is Object-Oriented.6.ASP.NET Is Multidevice and Multibrowser.7.ASP.NET Is Easy to Deploy and Configure.

Page 10: Asp.net Foundation

Visual Studio IDE

The Visual Studio IDE:

Visual Studio’s advantages:

1.An integrated web server.2.Multilanguage development.3.Less code to write:4.Intuitive coding style.5.Faster development time.6.Debugging.7.Multitargeting.8.IntelliSense and Outlining.

Page 11: Asp.net Foundation

Visual Studio interface :

Page 12: Asp.net Foundation

Choosing code Model

Page 13: Asp.net Foundation

The ASP.NET File Types

Serial File Type Description

1 Aspx.

2 .ascx

3 .asmx

4 web.config

5 global.asax

6 .VB, .Cs

The Toolbox Tabs

Serial File Type Description

1 Standard

2 Data

3 Validation

4 Navigation

5 Login

6 Web Parts

7 HTML

8 General

Page 14: Asp.net Foundation

Error List

Task List

Page 15: Asp.net Foundation

Migrating a Website from a Previous Version of Visual Studio

Page 16: Asp.net Foundation

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

Page 17: Asp.net Foundation

Simple HTML web Form

Page 18: Asp.net Foundation

Asp.Net Pages Requests

Page 19: Asp.net Foundation

ASP.Net 3.5 XHTML Compliance:1.Tag and attribute names must be in lowercase.2.All elements must be closed, either with a dedicated closing tag (<p></p>) or using an empty tag that closes itself (<br />).3. All attribute values must be enclosed in quotes (for example, runat="server").4.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.

Page 20: Asp.net Foundation

Web Forms Processing Stages:

Page 21: Asp.net Foundation

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 .

if (!IsPostBack){

// It's safe to initialize the controls for the first time.FirstName.Text = "Enter your name here";

}

ValidationASP.NET includes validation controls that can automatically validate other user input controls and display error messages.

Event HandlingAt 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:

I.Immediate response events.II.Change events.

Page 22: Asp.net Foundation

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:

1.• Session2.• Application3.• Cache4.• Request5.• Response6.• Server7.• User8.• Trace

1.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 requests2.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.

Page 23: Asp.net Foundation

HttpRequest Properties:# Property Description

1 AnonymousID This uniquely identifies the current user if you’ve enabled anonymousaccess. You’ll learn how to use the anonymous accessfeatures in Chapter 24.

2 ApplicationPath andPhysicalApplicationPath

ApplicationPath gets the ASP.NET application’s virtual directory(URL), while PhysicalApplicationPath gets the “real” directory.

3 Browser This provides a link to an HttpBrowserCapabilities object, whichcontains properties describing various browser features, such assupport for ActiveX controls, cookies, VBScript, and frames

4 ClientCertificate This is an HttpClientCertificate object that gets the security certificatefor the current request, if there is one.

5 Cookies This gets the collection of cookies sent with this request.

FilePath andCurrentExecutionFilePath

These return the real file path (relative to the server) for thecurrently executing page. FilePath gets the page that started theexecution process. This is the same as CurrentExecutionFilePath,unless you’ve transferred the user to a new page without a redirect

6 Form This represents the collection of form variables that were postedback to the page. In almost all cases, you’ll retrieve this informationfrom control properties instead of using this collection

7 Headers andServerVariables

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.

Page 24: Asp.net Foundation

Continued HttpRequest Properties:# Property Description

8 IsAuthenticated andIsSecureConnection

These return true if the user has been successfully authenticatedand if the user is connected over SSL (Secure Sockets Layer).

9 QueryString This provides the parameters that were passed along with thequery string.

10 IsLocal This returns true if the user is requesting the page from the localcomputer.

11 Url and UrlReferrer These provide a Uri object that represents the current address forthe page and the page where the user is coming from (the previouspage that linked to this page).

12 UserAgent This is a string representing the browser type. Internet Explorerprovides the value “MSIE” for this property. ASP.NET uses this informationto identify the browser and, ultimately, to determine thefeatures the browser should support (such as cookies, JavaScript,and so on). This, in turn, can influence how web controls renderthemselves

13 UserHostAddress andUserHostName

These get the IP address and the DNS name of the remote client.You could also access this information through the ServerVariablescollection

14 User Languages This provides a sorted string array that lists the client’s language preferences. This can be useful if you need to create multilingual pages.

Page 25: Asp.net Foundation

# Member Description

1 BufferOutput When set to true (the default), the page isn’t sent to the clientuntil it’s completely rendered and ready to be sent

2 Cache This references an HttpCachePolicy object that allows you toconfigure output caching.

3 Cookies This is the collection of cookies sent with the response. You canuse this property to add additional cookies.

4 Expires and ExpiresAbsolute

You can use these properties to cache the rendered HTML for thepage, improving performance for subsequent requests.

5 IsClientConnected This is a Boolean value indicating whether the client is stillconnected to the server. If it isn’t, you might want to stop a timeconsumingoperation.

6 Redirect() This method transfers the user to another page in your applicationor a different website

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

HttpResponse Members:

Page 26: Asp.net Foundation

4. Server:The Server object is an instance of the System.Web.HttpServerUtility class. It provides a handful of miscellaneous helper methods and properties.

HttpServerUtility Members:

# Member Description

1 MachineName() A property representing the computer name of the computer onwhich the page is running. This is the name the web server computeruses to identify itself to the rest of the network.

2 GetLastError() Retrieves the exception object for the most recently encounterederror (or a null reference, if there isn’t one). This error must haveoccurred while processing the current request, and it must not havebeen handled. This is most commonly used in an application eventhandler that checks for error conditions

3 HtmlEncode() andHtmlDecode()

Changes an ordinary string into a string with legal HTML characters(and back again).

4 UrlEncode() andUrlDecode()

Changes an ordinary string into a string with legal URL characters(and back again).

5 UrlTokenEncode() andUrlTokenDecode()

Performs the same work as UrlEncode() and UrlDecode(), except theywork on a byte array that contains Base64-encoded data.

6 MapPath() Returns the physical file path that corresponds to a specified virtualfile path on the web server.

7 Transfer() Transfers execution to another web page in the current application.This is similar to the Response.Redirect() method, but it’s faster. Itcannot be used to transfer the user to a site on another web server orto a non-ASP.NET page (such as an HTML page or an ASP page).

Page 27: Asp.net Foundation

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

Page 28: Asp.net Foundation

Trace Log Information: # Member Description

1 Request Details 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.

2 Trace Information

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

3 Control Tree 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.

4 Session State andApplication State

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.

5 Cookies Collection

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

6 Headers Collection

This section lists all the HTTP headers associated with the request

7 Forms Collection

This section lists the posted-back form information

8 QueryString Collection

This section lists the variables and values submitted in the querystring.

9 Server Variables

This section lists all the server variables and their contents

Page 29: Asp.net Foundation

Basic Trace Information:

Page 30: Asp.net Foundation

Types of Server Controls :

• HTML server controls• Web controls• Rich controls• Validation controls• Data controls• Navigation controls• Login controls• Web parts controls• ASP.NET AJAX controls• ASP.NET mobile controls

Server Controls

Page 31: Asp.net Foundation
Page 32: Asp.net Foundation
Page 33: Asp.net Foundation

ASP.NET Applications:is a combination of files, pages, handlers, modules, and executable code thatcan 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)•Code-behind files•A configuration file (web.config)•global.asax•Other components

ASP.NET Applications

Page 34: Asp.net Foundation

Application Updates :

Being able to update any part of an application at any time without interruptingexisting requests is a powerful feature. (shadow copy c:\Windows\Microsoft.NET\v2.0.50727\Temporary 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:

• Bin• App_Code• App_GlobalResources• App_LocalResources• App_WebReferences• App_Data• App_Browsers• App_Themes

Page 35: Asp.net Foundation

Application Events:

Page 36: Asp.net Foundation

ASP.NET Configuration:

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:\Windows\Microsoft.NET\Framework\v2.0.50727\Config.

• 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

Page 37: Asp.net Foundation

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.

Page 38: Asp.net Foundation

The web.config File :

Every web application inherits the settings from the machine.config file and the root web.config file.

Page 39: Asp.net Foundation

New Configuration Sections for ASP.NET 3.5

Page 40: Asp.net Foundation

.

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

Page 41: Asp.net Foundation

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

Page 42: Asp.net Foundation

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:-

• RSA• DPAPI

Others

• Programmatic Encryption• Command-Line Encryption

Page 43: Asp.net Foundation

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

Page 44: Asp.net Foundation

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 informationbetween 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=WalidThe 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

Page 45: Asp.net Foundation

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.

Page 46: Asp.net Foundation

How ViewStates Looks Like

Page 47: Asp.net Foundation

State Management Options Compared:

Page 48: Asp.net Foundation

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.

Page 49: Asp.net Foundation

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.

Page 50: Asp.net Foundation

References:

•Pro ASP.NET 3.5 in C# 2008 Second Edition .

About the Authors:

MATTHEW MACDONALD

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

MARIO SZPUSZTA

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