ASP Net Lecture

16

Click here to load reader

description

asp safdg tgdyf yrryur gdhfh gdgdghf dhfdhfh yrutyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuryyfyyyyyyyyyyyyyyyyyyyytdgggggggggggggggggggggggggghfhhm dhhhhhhhhhhhhhhhhhhhhhhdfghbhbbbbfhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhdgghghhhhdhjfjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjghdhhfuuffhfxhfghfghjgfjgjgjgjggfjjjjf

Transcript of ASP Net Lecture

Page 1: ASP Net Lecture

Helloworld Demo

Demo Single pageDemo code behindDemo compiled code

POST back and View state

ASP.NET controls automatically retain their data when a page is sent to the server in response to an event (such as a user clicking a button). Microsoft calls this persistence of data view state.

Demo 1 -> viewstate.aspDemo 2 -> viewstate.aspx

ASP.NET pages maintain view state by encrypting the data within a hidden form field.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTEwNDY1Nzg0MQ9…0fMCR+FN5P6v5pkTQwNEl5xhBk" />

This is a standard HTML hidden form field. All information that’s relevant to the view state of the page is stored within this hidden form field as an encrypted string. View state is enabled for every page by default. If you don’t intend to use view state, you can turn it off, which will result in a slight performance gain in your pages.

To do this, set the EnableViewState property of the Page directive to false:

<%@ Page EnableViewState="False" %>

View state can also be disabled for particular controls in a page: simply set theirEnableViewState property to false

Page Events

Whenever you request an ASP.NET page, a particular set of events is raised in a particularsequence. This sequence of events is called the page execution lifecycle.For example, we have already used the Page Load event in previous code samples in thischapter. You normally use the Page Load event to initialize the properties of controlscontained in a page. However, the Page Load event is only one event supported by thePage class.Here is the sequence of events that are raised whenever you request a page:1. PreInit2. Init3. InitComplete4. PreLoad5. Load6. LoadComplete7. PreRender8. PreRenderComplete

Page 2: ASP Net Lecture

9. SaveStateComplete10. Unload

Demo Showevents.aspx

Event Arguments Demo

Demo ShowEventArgs.aspx

Page.IsPostBack Property

The Page class includes a property called the IsPostBack property, which you can use todetect whether the page has already been posted back to the server.Because of View State, when you initialize a control property, you do not want to initializethe property every time a page loads. Because View State saves the state of control propertiesacross page posts, you typically initialize a control property only once, when the pagefirst loads.

Demo ispostback.aspx (comment if and see effect)

Tracing Page Execution

If you want to output trace messages while a page executes, then you can enable tracingfor a particular page or an entire application. The ASP.NET Framework supports both pageleveltracing and application-level tracing

Demo pagetrace.aspx

WebForms

There are several types of controls in ASP.NET:

■HTML server controls■web server controls■web user controls■master pages

HTML Server ControlsHTML server controls are outwardly identical to plain old HTML tags, but include a runat="server" attribute. This gives the ASP.NET runtime control over the HTML server controls, allowing us to access them programmatically. For example, if we have an <a> tag in a page and we want to be able to change the address to which it links dynamically, using VB or C# code, we use the runat="server" attribute. A server-side HTML server control exists for each of HTML’s most common elements. Creating

Page 3: ASP Net Lecture

HTML server controls is easy: we simply stick a runat="server" attribute on the end of a normal HTML tag to create the HTML control version of that tag.

All the HTML server control classes are contained within the System.Web.UI.Htm-lControls namespace. As they’re processed on the server side by the ASP.NETruntime, we can access their properties through code elsewhere in the page

Demo : HTMLControls.aspx

Web Server ControlsWeb server controls can be seen as advanced versions of HTML server controls. Web server controls are those that generate content for you—you’re no longer in control of the HTML being used. While having good knowledge of HTML is useful, it’s not a necessity for those working with web server controls.

Page 4: ASP Net Lecture

Unlike HTML server controls, web server controls don’t have a direct, one-to-one correspondence with the HTML elements they generate. For example, we can us eeither of two web server controls—the DropDownList control, or the ListBox con-trol—to generate a select element.Web server controls follow the same basic pattern as HTML tags, but the tag nameis preceded by asp:, and is capitalized using Pascal Casing. Pascal Casing is a formthat capitalizes the first character of each word (such as TextBox). The object IDsare usually named using Camel Casing, where the first letter of each word exceptthe first is capitalized (e.g. usernameTextBox).

To sum up, the key points to remember when you’re working with web servercontrols are:■Web server controls must be placed within a <form runat="server"> tag tofunction properly.■Web server controls require the runat="server" attribute to function properly.■We include web server controls in a form using the asp: prefix.

There are more web server controls than HTML controls. Some offer advanced fea-tures that simply aren’t available using HTML alone, and some generate quitecomplex HTML code for you. We’ll meet many web server controls as we workthrough this and future chapters.

Standard Web Server ControlsThe standard set of web server controls that comes with ASP.NET mirrors the HTML server controls in many ways. However, web server controls offer some new refinements and enhancements, such as support for events and view state, a more consistent set of properties and methods, and more built-in functionality

Page No : 107-126 website using asp.net + VB

User ControlsAs you build real-world projects, you’ll frequently encounter pieces of the user interface that appear in multiple places—headers or footers, navigation links, and login boxes are just a few examples. Packaging their forms and behaviors into your own controls will allow you to reuse these components just as you can reuse ASP .NET’s built-in controls.A web user control is represented by a class that inherits from System.Web.UI.UserControl, and contains the basic functionality that you need to extend to create your own controls.

Demo Smartbox.ascxControlTest.aspx

Page 5: ASP Net Lecture

Validation ControlsThe beauty of ASP.NET validation controls is that they determine whether or not the browser is capable of supporting client-side validation. If it is, ASP.NET automatically includes the necessary client-side JavaScript; if not, it’s omitted and the form is validated on the server.

A nice feature of ASP.NET is that we can make it set the focus automatically to the first input control that causes a validation error. We activate this feature by setting the SetFocusOnError property of the validation control to True.

Page.isValid property

Display property of validation control

i. NoneNone makes the validator invisible—no space is reserved, and the error messageis never shown. You may want to set this option when using theValidationSummary control

ii. StaticStatic is the default display mode. With this mode, the validator occupiesspace on the generated form even if it doesn’t display anything.

iii. DynamicThe Dynamic mode causes the validation control to display if any validationerrors occur, but ensures that it doesn’t generate any output

Demo Required.aspx (Enable and disable java script and see results)

<asp:RequiredFieldValidator id="passwordReq" runat="server" ControlToValidate="passwordTextBox" ErrorMessage="Password is required!" SetFocusOnError="True" Display="Dynamic" />

<asp:CompareValidator id="comparePasswords" runat="server" ControlToCompare="passwordTextBox" ControlToValidate="confirmPasswordTextBox" ErrorMessage="Your passwords do not match up!" Display="Dynamic" />

<asp:RangeValidator id="birthDateRangeTest" runat="server" Type="Date" ControlToValidate="birthDateTextBox" MinimumValue="1/1/1970" MaximumValue="12/31/1979" ErrorMessage="You must've been born in the 1970s to use this web site!" />

<asp:ValidationSummary id="vSummary" runat="server" showmessagebox=”true” />

<asp:RegularExpressionValidator id="emailValidator" runat="server" ControlToValidate="emailTextBox" ValidationExpression="^\S+@\S+\.\S+$" ErrorMessage="You must enter a valid email address!" />

Page 6: ASP Net Lecture

<asp:CustomValidator ID="usernameUnique" runat="server" ControlToValidate="usernameTextBox" OnServerValidate="CheckUniqueUserName" ErrorMessage="This username already taken!" />

Demo Customvalidator.aspx

Validation Groups

validation groups allow us to validate individual parts of a web page independently of its other sections. This capability proves particularly handy when you’re working with complex pages that contain many functional components. For example, consider the scenario of a single page that contains a login form and a quick registration form, each with its own Submit button and its own set of validation controls. Certainly we don’t want the functionality of the login form’s Submit button to be affected by the data in the registration form; nor can we allow the login form’s data to affect submission of the registration form.

Page 7: ASP Net Lecture

Master Pages

Unleashed book ch-5 page 238

A Master Page enables you to share the same content among multiple content pages in a

website. You can use a Master Page to create a common page layout. For example, if you want all the pages in your website to share a three column layout, you can create the layout once in a Master Page and apply the layout to multiple content pages. You also can use Master Pages to display common content in multiple pages. For example, if you want to display a standard header and footer in each page in your website,then you can create the standard header and footer in a Master Page. By taking advantage of Master Pages, you can make your website easier to maintain, extend, and modify. If you need to add a new page to your website that looks just like the other pages in your website, then you simply need to apply the same Master Page to the new content page. If you decide to completely modify the design of your website, you do not need to change every content page. You can modify just a single Master Page to dramatically change the appearance of all the pages in your application.

Demo SimpleMaster.masterSimpleContent.content

Demo (Master page with default content)DefaultMaster.masterDefaultContent.aspx

Demo (Nester Master pages) Site.masterSectionProducts.masterSecrionServices.masterProducts.aspxServices.aspx

Demo (Exposing master page properties)PropertyMaster.masterPropertyContent.aspx

Demo (dynamic master pages)Dynamic1.masterDynamic2.masterDynamiccontent.aspx

ThemesCh-6 unleashed book page 270

An ASP.NET Theme enables you to apply a consistent style. You use a Theme to control the

appearance of both the HTML elements and ASP.NET controls that appear in a page. Themes are different than Master Pages. A Master Page enables you to share content across multiple pages in a website. A Theme, on the other hand, enables you to control the appearance of the content.

Page 8: ASP Net Lecture

Demo (simple skin applicable to all controls)Simple folder in App_ThemesShowskin.aspx

Demo (named skin)Simple2 folder in App_ThemesShoenamedskin.aspx

Demo (Themes Versus StyleSheetThemes) Showskintheme.aspx (theme overrides page level attribute)Showskinstylesheettheme.aspx (theme overridden in page)

See difference between page directives in PAGE directiveEnable and disable theming in control

Demo (Simple CSS in themes folder)StyleTheme folder in app_themesShowSimpleCSS.aspx

Because an ASP.NET control renders HTML, the Style Sheet also styles the HTML rendered by the ASP.NET Label, TextBox, and Button controls. An ASP.NET Label control renders an HTML <label> tag and the Style Sheet formats all <label> tags in bold. Both a TextBox control and a Button control render HTML <input> tags. The Style Sheet modifies the border and background color of the <input> tag. Notice that the Button control includes a CssClass attribute. By providing a control with a CssClass attribute, you can target a particular control (or set of controls) in a Cascading Style Sheet. In this case, the background color of the <input> tag rendered by the Button control is set to the value #eeeeee (light gray).

I recommend that you do all your web page design by using the method discussed in this section. You should place all your page design in an external Cascading Style Sheet located in a Theme folder. In particular, you should not modify the appearance of a control by modifying its properties. Furthermore, you should avoid using Skin files. The advantage of using Cascading Style Sheets is that they result in leaner and faster loading pages. The more content that you can place in an external Style Sheet, the less content must be loaded each time you make a page request. The contents of an external Style Sheet can be loaded and cached by a browser and applied to all pages in a web application. If, on the other hand, you modify the appearance of a control by modifying its properties, then additional content must be rendered to the browser each time you make a page request. For

Page 9: ASP Net Lecture

example, if you modify a Label control’s BackColor property, then an additional Style attribute is rendered when the Label control is rendered.

Using Skins is no different than setting control properties. Skins also result in bloated pages. For example, if you create a Skin for a Label control, then the properties of the Label Skin must be merged with each Label control on each page before the Label is renderedCSS versus Skin files

o CSS usually deals with HTML code. You cannot apply CSS to certain ASP.NET specific server controls which are not present in HTML.

o You can apply Themes and skins to all ASP.NET controls with less effort. Themes and skins can be uniformly applied on both windows and asp.net applications.

o You can apply single theme to each page where as multiple style sheets can be applied to each page.

o Themes don't override or cascade style definitions by default the way CSS generally do. But you can selectively override local property settings for a control using style Sheet Time attribute in Themes.

o You can include CSS files in Themes which is applied as part of Theme structure but not vice-versa.

You can apply theming for only those properties that have ThemeableAttribute attribute set to true in their control class.

Skins

Generally, Themes contain skins. A skin file contains style definitions for the individual server controls. You can define skin settings for a control using similar markup which we use to add server controls to web page. Only difference you may find between skinned versions of control is that skinned version do not include ID attribute for control. You should retain properties for which you want to configure through Themes. We create .skin files in Theme folder. We can also mix all server controls style definition in a single skin file. Make sure all style definition files like CSS, skin files, Image files and other resources are included in Themes folder in your application directory. <asp:button runat="server" BackColor="lightblue" BorderColor="AliceBlue" Font-Bold ="true" ForeColor="black"/> Skin file There are two types of control skins based on their scope. They are: Default Skins: Control skin for which SkinID attribute is not set which means control skin is applied automatically for the controls of same type. For example: if you create a

Page 10: ASP Net Lecture

default skin for button then default button control skin will be applied for all the buttons on the page. The scope of default skin depends on where you define default skin. Named Skins: Named Skins will have SkinID property set which means you can use named skins with a control only by setting control's SkinID property to specific named skinID. Named Skins do not apply for the controls by type.

Demo:Dynamically loading thems (code folder)

Page 11: ASP Net Lecture

State Management (Ch 24 unleashed)

Cookies

Demo Setcookie.aspxGetcookie.aspx

DemoSetpersistentcookie.aspx

(location at C:\Documents and Settings\admin\ApplicationData\Mozilla\Firefox\Profiles\c4q3qqwa.default in firefox)

Getcookie.aspxDemo

Deletecookie.aspx

DemoSetcookievalues.aspx (preferences)getcookievalues.aspx

Sessions (ch 24 Unleashed)Demo (In process session state)

Sessionset.aspxDemo

Sessionget.aspx (retrieve session value and session id and call abandon method)

DemoSession timeout in web.config fileSessionset.aspxSessionget.aspx

Demo Session in SQL server Sessionset.aspxSessionget.aspxUsing SqlServer studio check tables and rows created

c:\Program Files\Microsoft Visual Studio 9.0\VC>aspnet_regsql.exe -S chirag\sqlexpress -E -ssadd -sstype p

DemoSession in State Server- start aspnetstate server process from services- set registry key properly for remote connectionHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\

Port set to 1

Page 12: ASP Net Lecture

Check port no as well

- pause service and see effect

ProfilesASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

Demo : showprofile.aspx (create profile)Open aspnet database and see rows of dbo.aspnet_profile table

Demo:Showanonymounsidentification.aspx

Page 13: ASP Net Lecture

ADO .NET

Steps to write database program

1. Import the necessary namespaces.2. Define a connection to your database with an SqlConnection object.3. When you’re ready to manipulate your database, set up the appropriate queryin an SqlCommand object.4. Open the connection and execute the SQL query to return the results into aSqlDataReader object.5. Extract relevant database data from the SqlDataReader object and display it onyour web page.6. Close the database connection.

Demo : connectedDB.aspx

Demo : disconnectedDB.aspx