Вы находитесь на странице: 1из 34

Module 7

Writing Server-Side Code for Web Forms

Module Overview
Overview of the Structure of a Web Application Controlling View State

Localizing a Web Application


Persisting Data on a Web Forms Page Validating User Input

Lesson 1: Overview of the Structure of a Web Application


Structure of a Web Application Web Application File Types

Web Application Compilation Methods

Structure of a Web Application


Every web application created in Visual Studio 2010 has the

following special folders:


App_Data (created by default) App_GlobalResources App_LocalResources App_Browsers App_Themes

Website projects have three extra folders:

App_Code

App_WebReferences
Bin

Web Application File Types


In a deployed web application or website, the following file

types can be found:


.aspx .ascx .ashx .config .master .svc .resx

Global.asax

Web Application Compilation Methods


Automatic compilation

Application is compiled the first time a user requests a resource from the website.

One assembly for each directory, including root directory. If there are files in more than one programming language, there will be one assembly per folder and language.

To avoid long waits, applications can be precompiled.

Dynamic compilation

After the first compilation, the files are cached. Any change to the source files will trigger a recompilation of the application. The compiled files are placed in the following location:
%SystemRoot%\Microsoft.NET\Framework\versionNumber\Temporary ASP.NET Files

Lesson 2: Controlling ViewState


What is View State Controlling View State

Using ViewStateMode
Using Control State View State Best Practices

What is View State?


View state is a repository used to overcome the stateless nature of the web applications

View state can store:


Page and controls property values between postbacks Values between postbacks without storing them in session state or user profile

Performance Implications:
By using the view state, the ASP.NET infrastructure can recreate

the state of the page when it is posted back, so the users get the feel of running a stateful application considerably

By using view state, the size of the page increases

Controlling View State


View state is first serialized into XML and then encoded

using base-64 encoding

The result: a large amount of data is sent to the client as hidden

data called __VIEWSTATE

If the size of the view state exceeds MaxPageStateFieldLength,

the data is split into several hidden fields

Turn off view state for read only pages, or controls


Set EnableViewState to false Set ViewStateMode to Disabled

Using ViewStateMode
If you set EnableViewState to false, view state will be

turned off for the page/control and all their child controls controlled by ViewStateMode:

If EnableViewState is set to true, view state behavior is Enable The Page/Control is using view state Disable The Page/Control has its view state turned off

Inherit(Default) The control inherits the view state of the parent control

Using Control State


Control state is always on Should be used only for the control properties that are

necessary

Two methods need to be overridden from the base class:

protected override object SaveControlState() protected override void LoadControlState(object state)


The control needs to be registered with the ASP.NET for the

control state.

protected override void OnInit(EventArgs e) { base.OnInit(e); Page.RegisterRequiresControlState(this); }

View State Best Practices


Turn off view state for read-only pages Turn off view state for the controls that do not need it

If view state for a page is too big, consider compressing

the view state, or move it to the end of the page functioning of the control

Use control state only when it is required for the proper

Lesson 3: Localizing a Web Application


What is Localization? Working with Resource Files

Reading Data from Resource Files


Demonstration: Localize a Website

What is Localization?
Globalization Process of designing and developing an

application that supports localized user interfaces and regional data for users in multiple cultures application is ready for localization

Localizability Process for verifying that a globalized


An application is ready for localization if the application's executable code has been clearly separated from the application's localizable resources

Localization Process of translating an application's

resources into localized versions for each culture that the application will support

Working with Resource Files


Resource (.resx or .resource) files are compiled into

satellite assemblies automatically

There are two kinds of resource files:

Local resources

Reside in App_LocalResources One resource file per ASP.NET file and language

Global resources

Reside in App_GlobalResources Contains resources accessible to all ASP.NET files

Reading Data from Resource Files


There are two methods to read from the resource files:

Implicit localization Any control that has an attribute called meta:resourcekey set will read the values for the properties that are Localizable from the local resource file

Localizable is a design attribute which is set by the designer of the control to mark it as localizable

<asp:Button runat="server" Text="Submit" meta:resourcekey="btnCategoryResource1"> </asp:Button>

Explicit localization By using expressions that reads the data from a local or a global resource file

<asp:Literal runat="server" Text="<%$ Resources: LiteralResource1 %>"> </asp:Literal>

Demonstration: Localize a Web application


Generate local resource files Translate the resources in different languages Use local and global resources in markup

Test localized page

Lesson 4: Persisting Data on a Web Forms Page


Introduction to State Management Options for State Management

Options for Saving Session State


Using SQL Server to Store Session State

Introduction to State Management


State management is a process of saving information between page requests and postbacks on the server
Without State Management
Please enter your logon information: First Name: Last Name: Jesper Aaberg

With State Management


Please enter your logon information: First Name: Last Name: Jesper Aaberg

SUBMIT Sorry! I forgot who you are!

SUBMIT Hello Jesper!

Options for State Management


State data can be saved in two different places:
Server side:

Client side:

Application state

View state Control state

Session state
User profile Caching

Posted data
Cookies Query String

Options for Saving Session State


Session state can be configured in different modes:

InProc Data is kept in memory (the default)

StateServer Data is saved in an external State Server


SQLServer Data is saved in a database Custom Your own custom implementation for session state Off No session state

Except for InProc, all other modes require the data saved

in the session state to be serializable

InProc mode is not suitable for web farm scenarios

Using SQL Server to Store Session State


Session state data is stored in a SQL Server database Data will be saved in a database called ASPState

To create the database run aspnet_regsql.exe -ssadd

To use the database, configure your website as follows: <configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString="Integrated Security=SSPI; data source=SampleSqlServer;" /> </system.web> </configuration>

Lesson 5: Validating User Input


Why Validate? Validation Controls

Validation Controls Properties


Validation Groups Displaying Validation Errors

Regular Expressions Validation


Custom Validation

Why Validate?
Validation should be a requirement in all applications, to provide:
Security, to protect against injection attacks Correctness, to ensure that the data is valid and business

rules are enforced

Responsiveness flags for invalid data before sending it to

the server

Validation Controls
ASP.NET has a set of predefined validation controls

RequiredFieldValidator Requires user input

CompareValidator Compares input values against other values or controls


RangeValidator Compares input values to a range RegularExpressionValidator Compares input values to a regular expression pattern CustomValidator Compares input values to custom logic

Validation Controls Properties


All validation controls have the following properties:

ControlToValidate Which control to validate

ErrorMessage Error message to be displayed in the ValidationSummary


Text Error message to be displayed next to the control Display How to display the error message

Static Space is always allocated in the page layout


Dynamic Space is allocated in the page layout on error None No validation message

ValidationGroup The validation group to which this control belongs


EnableClientScript Specifies whether client-side validation is enabled

Validation Groups
Validation groups allow you to organize validation controls

on a page as a set

Each validation group can perform validation independently

from other validation groups on the page

To create a validation group, set ValidationGroup

property to the same value for all controls that belongs to the same group validation group, then a value of IsValid will be determined based only on the validity of the controls belonging to that group

If the control that caused the postback belongs to a

Displaying Validation Errors


When a control contains invalid data there are four options

to show the error message:

Inline Displays the message next to the control that contains the invalid input Summary Displays the message in a ValidationSummary control Inline and Summary Provides combination of the Inline and Summary options Custom Allows you to write script or custom code when an error is not in the norm (for example, to check for certain values); uses the Page.IsValid property to determine whether an error has occurred

Regular Expressions Validation


ASP.NET provides a built-in control for validating regular

expressions the RegularExpressionValidator

It includes patterns for


Phone numbers Postal codes Email addresses URLs SSNs

Custom Validation
If none of the existing controls can be used to validate a

certain type of data, you can use your own validation logic with the CustomValidator control. properties of interest:

Besides the properties mentioned earlier, it has two


ClientValidationFunction Specifies the java script to be run on the client side

OnServerValidate Specifies the event handler to be run on the server side


void ccValidator_ServerValidate(object source, ServerValidateEventArgs args) { if (IsValueValid(args.Value)) { args.IsValid = true; } }

Lab: Writing Server-Side Code for Web Forms


Exercise 1: Modifying a Web Forms Page to Display

Localized Content

Exercise 2: Persisting data on Web Forms Pages Exercise 3: Utilizing View State Effectively Exercise 4: Adding Validation to Web Forms Pages

Logon information

Virtual machine User name Password

10264A-GEN-DEV Student Pa$$w0rd

Estimated time: 60 minutes

Lab Scenario

Lab Review
Why did you use mainly local resources for localizing the

Web Forms page and the Site.Master master page? Session state? view state?

Why and when would you use SQL Server as storage for What did you notice about the effects of turning on and off

Module Review and Takeaways


Module Review Real-world Issues and Scenarios

Best Practices

Вам также может понравиться