Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamentals of a Web Form

Similar presentations


Presentation on theme: "Fundamentals of a Web Form"— Presentation transcript:

1 Fundamentals of a Web Form
ITEC 420

2 Anatomy of an ASP.NET Application
ASP.NET applications are almost always divided into multiple web pages. This division means a user can enter an ASP.NET application at several different points or follow a link from the application to another part of the website or another web server. Every ASP.NET application shares a common set of resources and configuration settings. Web pages from other ASP.NET applications don’t share these resources, even if they’re on the same web server. Every ASP.NET application is executed inside a separate application domain. Application domains are isolated areas in memory.

3 Anatomy of an ASP.NET Application
The standard definition of an ASP.NET application describes it as a combination of files, pages, handlers, modules, and executable code that can be invoked from a virtual directory (and, optionally, its subdirectories) on a web server. In other words, the virtual directory is the basic grouping structure that delimits an application.

4 ASP.NET File Types A list of essential ingredients (image is from 2008 Textbook) Additional folders could be created - HTML, css, image files could be kept.

5 ASP.NET Application Directory
Every web application should have a well planned directory structure. Along with the directories you create, ASP.NET also uses a few specialized subdirectories, which it recognizes by name . Keep in mind that you won’t see all these directories in a typical application. Visual Studio will prompt you to create them as needed.

6 Server Controls Server controls are created and configured as objects. They run on the web server and they automatically provide their own HTML output. Server controls behave like their Windows counterparts by maintaining state and raising events that you can react to in code. ASP.NET actually provides two sets of server- side controls that you can incorporate into your web forms. These two different types of controls play subtly different roles:

7 Server Controls HTML Server controls:
These are server-based equivalents for standard HTML elements. These controls are ideal if you prefer to work with familiar HTML tags. They are also useful when migrating ordinary HTML pages or ASP pages to ASP.NET, because they require the fewest changes.

8 Server Controls Web controls:
These are similar to the HTML server controls, but they provide a richer object model with a variety of properties for style and formatting details. They also provide more events and more closely resemble the controls used for Windows development. Web controls also feature some user interface elements that have no direct HTML equivalent, such as the GridView, Calendar, and validation controls.

9 They generate their own interface:
HTML Server Controls They generate their own interface: You set properties in code, and the underlying HTML tag is created automatically when the page is rendered and sent to the client. They retain their state: Because the Web is stateless, ordinary web pages need to do a lot of work to store information between requests. HTML server controls handle this task automatically. if your code changes the text in a button, the new text sticks the next time the page is posted back to the web server.

10 HTML Server Contorls They fire server-side events:
For example, buttons fire an event when clicked, text boxes fire an event when the text they contain is modified, and so on. Your code can respond to these events, just like ordinary controls in a Windows application. HTML server controls are ideal when you’re performing a quick translation to add server- side code to an existing HTML page.

11 Converting an HTML Page to an ASP.NET Page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" " <html xmlns=" <head><title>Currency Converter</title></head> <body> <form method="post"> <div> Convert:  <input type="text" />  U.S. dollars to Euros. <br /><br /> <input type="submit" value="OK" /> </div> </form></body></html>

12 Converting an HTML Page to an ASP.NET Page
Create a new website From default.aspx file delete everything except the page directive. Copy all the content from the html to default.aspx Now you need to add the attribute runat="server" to each tag that you want to transform into a server control. You should also add an ID attribute to each control that you need to interact with in code. The ID attribute assigns the unique name that you’ll use to refer to the control in code.

13 Converting an HTML Page to an ASP.NET Page
Page Language="C#" AutoEventWireup="true" CodeFile="CurrencyConverter.aspx.cs" Inherits="CurrencyConverter" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" " <html xmlns=" <head><title>Currency Converter</title></head> <body> <form runat="server"> <div> Convert:   <input type="text" ID="US" runat="server" />   U.S. dollars to Euros. <br /><br /> <input type="submit" value="OK" ID="Convert" runat="server" /> </div> </form></body></html> Now you need to add the attribute runat="server" to each tag that you want to transform into a server control. You should also add an ID attribute to each control that you need to interact with in code. The ID attribute assigns the unique name that you’ll use to refer to the control in code. In the currency converter application, it makes sense to change the input text box and the submit button into HTML server controls. In addition, the <form> element must be processed as a server control to allow ASP.NET to access the controls it contains.

14 Converting an HTML Page to an ASP.NET Page
When you run your application and check the source you will realize that : The HTML that was sent to the browser is slightly different from the information in the .aspx file. First, the runat="server" attributes are stripped out. Second, and more important, an additional hidden field has been added to the form. This hidden field stores information, in a compressed format, about the state of every control in the page. It allows you to manipulate control properties in code and have the changes automatically persisted across multiple trips from the browser to the web server. This is a key part of the web forms programming model. Even though the currency converter program doesn’t yet include any code, you’ll already notice one change. If you enter information in the text box and click the submit button to post the page, the refreshed page will still contain the value you entered in the text box. (In the original example that uses ordinary HTML elements, the value will be cleared every time the page is submitted.) This change occurs because ASP.NET controls automatically retain their state.

15 The HTML Control Classes
All the server controls are defined in the System.WEB.UI.HtmlControls namespaces. Each kind of control has a seperate class. Here is the list that describes the basic html server controls and shows you the related HTML element

16 Important HTML Control Properties

17 Lets make currency control run
Before you continue, it makes sense to add another control that can display the result of the calculation. In this case, you can use a <p> tag named Result. The <div> tag is one way to insert a block of formatted text into a web page. Here’s the code: <p style="font-weight: bold" ID="Result" runat="server"> ... </p> Add the click event for the button: <input type="submit" value="OK" runat="server" id="Convert" onserverclick="Convert_Click"/> decimal USAmount = Decimal.Parse(US.Value); decimal euroAmount = USAmount * 0.85M; Result.InnerText = USAmount.ToString() + " U.S. dollars = "; Result.InnerText += euroAmount.ToString() + " Euros."; US and Result are id’s for text and div controls.

18 Lets make currency control run
Unlike with web controls, you can’t create event handlers for HTML server controls using the Properties window. Instead, you must type the method in by hand. You must also modify the control tag to connect your event handler. For example, to connect the Convert button to the method named Convert_ServerClick, you must add OnServerClick="Convert_ServerClick" to the control tag. And create in .cs file protected void Convert_Click(object sender, EventArgs e)

19 Error Handling Improving
When user types invalid numbers the error will be raised to avoid: decimal USAmount; // Attempt the conversion. bool success = Decimal.TryParse(US.Value, out USAmount); // Check if it succeeded. if (success){ // The conversion succeeded. decimal euroAmount = USAmount * 0.85M; Result.InnerText = USAmount.ToString() + " U.S. dollars = "; Result.InnerText += euroAmount.ToString() + " Euros."; } else{ // The conversion failed. Result.InnerText = "The number you typed in was not in the " + "correct format. Use only numbers.";

20 Notes However, even without these abilities you can rework the code that responds to the ServerClick event to avoid potential errors. One good approach is to use the Decimal.TryParse() method instead of Decimal.Parse(). Unlike Parse(), TryParse() does not generate an error if the conversion fails—it simply informs you of the problem. TryParse() accepts two parameters. The first parameter is the value you want to convert (in this example, US.Value). The second parameter is an output parameter that will receive the converted value (in this case, the variable named USAmount). What’s special about TryParse() is its Boolean return value, which indicates if the conversion was successful (true) or not (false).

21 Adding Multiple Currencies
Improving the Page Adding Multiple Currencies Add : <select ID="Currency" runat="server" /> to our aspx file. Add the following to the onload event of page. protected void Page_Load(Object sender, EventArgs e) { if (this.IsPostBack == false) // The HtmlSelect control accepts text or ListItem objects. Currency.Items.Add(new ListItem("Euros", "0.85")); Currency.Items.Add(new ListItem("Japanese Yen", "110.33")); Currency.Items.Add(new ListItem("Canadian Dollars", "1.2")); }

22 Improving the page Before adding any items to this list, you need to make sure this is the first time the page is being served to this particular user. Otherwise, the page will continuously add more items to the list or inadvertently overwrite the user’s selection every time the user interacts with the page. To perform this test, you check the IsPostBack property of the current Page. In other words, IsPostback is a property of the CurrencyConverter class, which CurrencyConverter inherits from the generic Page class. If IsPostBack is false, the page is being created for the first time, and it’s safe to initialize it.

23 Improving the Page For the click event of the button, use the following code: protected void Convert_ServerClick(object sender, EventArgs e) { decimal amount = Decimal.Parse(US.Value); // Retrieve the selected ListItem object by its index number. ListItem item = Currency.Items[Currency.SelectedIndex]; decimal newAmount = amount * Decimal.Parse(item.Value); Result.InnerText = amount.ToString() + " U.S. dollars = "; Result.InnerText += newAmount.ToString() + " " + item.Text; } It is also possible to change the styles setting like: if (amount <= 0) { Result.Style["color"] = "Red"; Result.InnerText = "Specify a positive number"; }else { Result.Style["color"] = "Black"; Result.InnerText += newAmount.ToString() + " " + item.Text;}}

24 HTML Control Events HTML server controls also provide one of two possible events: ServerClick or ServerChange. The ServerClick is simply a click that’s processed on the server side. It’s provided by most button controls, and it allows your code to take immediate action. The ServerChange event responds when a change has been made to a text or selection control. This event isn’t as useful as it appears because it doesn’t occur until the page is posted back (for example, after the user clicks a submit button). At this point, the ServerChange event occurs for all changed controls, followed by the appropriate ServerClick. The Page.Load event is the first to fire, but you have no way to know the order of events for other controls.

25 HTML Control Events

26 HTML Control Classes (HTMLContainerControl)
Any HTML control that requires a closing tag inherits from the HtmlContainer class (which in turn inherits from the more basic HtmlControl class). For example, elements such as <a>, <form>, and <div> always use a closing tag, because they can contain other HTML elements.

27 HTML Control Classes (The Page Class)
Here is an overview of some of the more fundamental properties

28 Sending the User to a New Page
Click <a href="newpage.aspx">here</a> to go to newpage.aspx. Another option is to send the user to a new page using code. This approach is useful if you want to use your code to perform some other work before you redirect the user. It’s also handy if you need to use code to decide where to send the user. For example: Response.Redirect("newpage.aspx"); When you use the Redirect() method, ASP.NET immediately stops processing the page and sends a redirect message back to the browser. Any code that occurs after the Redirect() call won’t be executed. When the browser receives the redirect message, it sends a request for the new page. You can use the Redirect() method to send the user to any type of page. You can even send the user to another website using an absolute URL (a URL that starts with as shown here: Response.Redirect(" ASP.NET gives you one other option for sending the user to a new page. You can use the HttpServerUtility.Transfer() method instead of Response.Redirect(). An HttpServerUtility object is provided through the Page.Server property, so your redirection code would look like this: Server.Transfer("newpage.aspx"); The advantage of using the Transfer() method is the fact that it doesn’t involve the browser. Instead of sending a redirect message back to the browser, ASP.NET simply starts processing the new page as though the user had originally requested that page. This behavior saves a bit of time, but it also introduces some significant limitations. You can’t use Transfer() to send the user to another website or to a non-ASP.NET page (such as an HTML page). The Transfer() method only allows you to jump from one ASP.NET page to another, in the same web application. Furthermore, when you use Transfer() the user won’t have any idea that another page has taken over, because the browser will still show the original URL. This can cause a problem if you want to support browser bookmarks.

29 HTML Encoding As you already know, there are certain characters that have a special meaning in HTML. For example, the angle brackets (< >) are always used to create tags. This can cause problems if you actually want to use these characters as part of the content of your web page. For example, imagine you want to display this text on a web page: Enter a word <here> If you try to write this information to a page or place it inside a control, you end up with this instead: Enter a word The solution is to use HTMLEncode

30 HTML Encoding // Will output as "Enter a word <here>" in the HTML file, but the // browser will display it as "Enter a word <here>". ctrl.InnerHtml = Server.HtmlEncode("Enter a word <here>"); Or consider this example, which mingles real HTML tags with text that needs to be encoded: ctrl.InnerHtml = "To <b>bold</b> text use the "; ctrl.InnerHtml += Server.HtmlEncode("<b>") + " tag.";

31 HTML Encoding The HtmlEncode() method is particularly useful if you’re retrieving values from a database and you aren’t sure whether the text is valid HTML. You can use the HtmlDecode() method to revert the text to its normal form if you need to perform additional operations or comparisons with it in your code. Along with the HtmlEncode() and HtmlDecode() methods, the HttpServerUtility class also includes UrlEncode() and UrlDecode() methods. Much as HtmlEncode() allows you to convert text to valid HTML with no special characters, UrlEncode() allows you to convert text into a form that can be used in a URL. This technique is particularly useful if you want to pass information from one page to another by tacking it onto the end of the URL.

32 Application Events Although server controls are the most common source of events, there’s another type of event that you’ll occasionally encounter: application events. Application events aren’t nearly as important in an ASP.NET application as the events fired by server controls, but you might use them to perform additional processing tasks. For example, using application events you can write logging code that runs every time a request is received, no matter what page is being requested. Basic ASP.NET features like session state and authentication use application events to plug into the ASP.NET processing pipeline. You can’t handle application events in the code behind for a web form. Instead, you need the help of another ingredient: the Global.asax file.

33 The Global.asax File The Global.asax file allows you to write code that responds to global application events. These events fire at various points during the lifetime of a web application, including when the application domain is first created (when the first request is received for a page in your website folder). To add a Global.asax file to an application in Visual Studio, choose Website -> Add New Item, and select the Global Application Class file type. Then, click OK. The Global.asax file looks similar to a normal .aspx file, except that it can’t contain any HTML or ASP.NET tags. Instead, it contains event handlers. For example, the following Global.asax file reacts to the Application.EndRequest event, which happens just before the page is sent to the user:

34 The Global.asax file <%@ Application Language="C#" %>
<script language="c#" runat="server"> protected void Application_OnEndRequest() { Response.Write("<hr />This page was served at " + DateTime.Now.ToString()); } </script> This event handler uses the Write() method of the built-in Response object to write a footer at the bottom of the page with the date and time that the page was created. Each ASP.NET application can have one Global.asax file. Once you place it in the appropriate website directory, ASP.NET recognizes it and uses it automatically. For example, if you add the Global.asax file shown previously to a web application, every web page in that application will include a footer.

35 Additional Application Events
Application.EndRequest is only one of more than a dozen events you can respond to in your code. To create a different event handler, you simply need to create a subroutine with the defined name. Below lists some of the most common application events that you’ll use.

36 ASP.NET Configuration Every web application includes a web.config file that configures fundamental settings— everything from the way error messages are shown to the security settings that lock out unwanted visitors. You’ll consider the settings in the web.config file throughout this book.

37 ASP.NET Configuration The ASP.NET configuration files have several key advantages: They are never locked: You can update web.config settings at any point, even while your application is running. If there are any requests currently under way, they’ll continue to use the old settings, while new requests will get the changed settings right away. They are easily accessed and replicated: Provided you have the appropriate network rights, you can change a web.config file from a remote computer. You can also copy the web.config file and use it to apply identical settings to another application or another web server that runs the same application in a web farm scenario. The settings are easy to edit and understand: The settings in the web.config file are humanreadable, which means they can be edited and understood without needing a special configuration tool.

38 The web.config File The web.config file uses a predefined XML format. The entire content of the file is nested in a root <configuration> element. Inside this element are several more subsections, some of which you’ll never change, and others which are more important. Here’s the basic skeletal structure of the web.config file, with the three most important sections highlighted in bold: <?xml version="1.0" ?> <configuration> <configSections>...</configSections> <appSettings>...</appSettings> <connectionStrings>...</connectionStrings> <system.web>...</system.web> <system.codedom>...</system.codedom> <system.webServer>...</system.webServer> </configuration> Note that the web.config file is case-sensitive, like all XML documents, and starts every setting with a lowercase

39 The web.config File There are three sections in the web.config file that you’ll work with. The <appSettings> section allows you to add your own miscellaneous pieces of information. The <connectionStrings> section allows you to define the connection information for accessing a database. Finally, the <system.web> section holds every ASP.NET setting you’ll need to configure. Inside the <system.web> element are separate elements for each aspect of website configuration. You can include as few or as many of these as you want. For example, if you need to specify special error settings, you would add the <customErrors> element in the <system.web> section. If you wanted to control how ASP.NET’s security works, you’d add the <authentication> and <authorization> sections.

40 Storing Custom Settings in the web.config File
ASP.NET also allows you to store your own settings in the web.config file, in an element called <appSettings>. Note that the <appSettings> element is nested in the root <configuration> element. Here’s the basic structure: <?xml version="1.0" ?> <configuration> ... <appSettings> <!-- Custom application settings go here. --> </appSettings> <system.web> <!-- ASP.NET Configuration sections go here. --> </system.web> </configuration>

41 Storing Custom Settings in the web.config File
The custom settings that you add are written as simple string variables. You might want to use a special web.config setting for several reasons: To centralize an important setting that needs to be used in many different pages: For example, you could create a variable that stores a database query. Any page that needs to use this query can then retrieve this value and use it. To make it easy to quickly switch between different modes of operation: For example, you might create a special debugging variable. Your web pages could check for this variable and, if it’s set to a specified value, output additional information to help you test the application. To set some initial values: Depending on the operation, the user might be able to modify these values, but the web.config file could supply the defaults.

42 Storing Custom Settings in the web.config File
You can enter custom settings using an <add> element that identifies a unique variable name (key) and the variable contents (value). The following example adds a variable that defines a file path where important information is stored: <appSettings> <add key="DataFilePath" value="e:\NetworkShare\Documents\WebApp\Shared" /> </appSettings> You can add as many application settings as you want, although this example defines just one.

43 Storing Custom Settings in the web.config File
You can create a simple test page to query this information and display the results, as shown in the following example (which is provided with the sample code as ShowSettings.aspx and ShowSettings.aspx.cs). You retrieve custom application settings from web.config by key name, using the WebConfigurationManager class, which is found in the System.Web.Configuration namespace. This class provides a static property called AppSettings with a collection of application settings. using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Configuration; public partial class ShowSettings : System.Web.UI.Page { protected void Page_Load() lblTest.Text = "This app will look for data in the directory:<br /><b>"; lblTest.Text += WebConfigurationManager.AppSettings["DataFilePath"]; lblTest.Text += "</b>"; }

44 The Website Administration Tool (WAT)
ASP.NET includes a graphical configuration tool called the Website Administration Tool (WAT), which lets you configure various parts of the web.config file using a web page interface. To run the WAT to configure the current web project in Visual Studio, select Website  ASP.NET Configuration. A web browser window will appear Internet Explorer will automatically log you on under the current Windows user account, allowing you to make changes. You can use the WAT to automate the web.config changes you made in the previous example. To try this, click the Application tab. Using this tab, you can create a new setting (click the Create Application Settings link). If you click Manage Application Settings, you’ll see a list with all the applications settings that are defined in your application. You can then choose to remove or edit any one of them. This is the essential idea behind the WAT. You make your changes using a graphical interface (a web page), and the WAT generates the settings you need and adds them to the web.config file for your application behind the scenes. Of course, the WAT has a number of settings for configuring more complex ASP.NET settings.


Download ppt "Fundamentals of a Web Form"

Similar presentations


Ads by Google