Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Reusability Techniques (Style Sheets, User Controls, Communicating Between Web Forms) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. OBJECTIVES ............................................................................................................................................................... 2 CREATE NEW WEB APPLICATION .............................................................................................................................. 2 ADD WEBFORMS ........................................................................................................................................................ 3 SET START PAGE ........................................................................................................................................................ 3 ADD A STYLE SHEET TO YOUR PROJECT .................................................................................................................... 3 MAKE ALL WEB FORMS REFERENCE YOUR STYLE SHEET (THEN TEST).................................................................... 4 INCLUDE GRAPHIC IN YOUR WEB APPLICATION ........................................................................................................ 4 USE TABLE TO CREATE LAYOUT FOR YOUR HOME PAGE .......................................................................................... 5 CREATE A NAVIGATION BAR WITH A USER CONTROL............................................................................................... 7 REGISTER THE USER CONTROL IN THE HOME PAGE .............................................................................................. 8 VIEW USER CONTROL IN DESIGN MODE ............................................................................................................... 9 VIEW USER CONTROL (NAVIGATION BAR) RENDERED IN BROWSER ..................................................................... 9 ADD LAYOUT TO ALL WEB FORMS, TEST ........................................................................................................... 10 PASSING PARAMETERS TO ANOTHER WEB FORM................................................................................................ 10 READING PARAMETERS PASSED FROM ANOTHER WEB FORM ............................................................................ 12 COMMUNICATING BETWEEN WEB FORMS USING THE SESSION OBJECT .............................................................. 13 INSTALL SAMPLE CODE ON YOUR LAPTOP .......................................................................................................... 14 TRY IT YOURSELF................................................................................................................................................ 15 APPENDIX A – A SAMPLE STYLE SHEET .................................................................................................................. 16 1 1. Objectives In this tutorial, we will focus on code reuse (the opposite of copy/pasting). We achieve code reuse in various ways: You’ll create a web application with several web forms in it: a new home page, the validation page (that you created in a previous tutorial), and an “under construction” page. You’ll create a single style sheet that will be referenced by all web forms. All “look and feel” specifications (e.g., color and font choices) will be in your style sheet and none will be in your HTML code 1. You’ll create a navigation bar (implemented with a C# .NET user control) and each web form will include a reference to that navigation bar 2. You’ll also use the validation web form for two purposes: adding a new record and editing an old record3. You’ll accomplish this by passing parameters to the web form (telling it whether it should add or edit when the user clicks on the submit button). However, your web application will still not connect to the database – that will be covered in a future tutorial. You’ll also see how one web form can store values into the “Session” object and another web form can retrieve the values back from the “Session” object. However, scalable web applications should minimize the use of the “Session” object, keeping only information such as username and authorization level. The Session object will be used extensively in a future tutorial. 2. Create New Web Application From the Visual Studio menu, select Project, New C# Web Application. Name the web app something like “Lesson2Reuse” (so you’ll know what this application is later). If you name an application “Application1”, you’ll never be able to remember which application is which. There is a reason why you want to keep all “look and feel” specifications in the style sheet (and none in the web forms). If you put color and font choices “all over the place”, in all of the web forms, it becomes difficult (if not impossible) to ensure that all the pages of your site continue to look just the same. You could not easily change a color or font and be sure that this change is consistent throughout all the web forms of your web application. 1 2 Instead of copy/pasting a navigation bar to all web forms, you can create a reusable navigation bar by using a User Control. Then if the links of the site change (and this happens often), the web developer only needs to change those links in one place – the navigation bar (User Control). Otherwise, (without a reusable navigation bar), the web developer would have to copy and paste a changed navigation bar into each web form of the web application. Because the add and edit pages should look the same, you’ll use one web form for both purposes. This way, you won’t have to maintain two different web forms and try to ensure they always look the same. 3 2 3. Add Webforms To add web forms to your project, select Project – Add WebForm from the Visual Studio menu. Give your new webforms these names: Index.aspx, Products.aspx, and Promotions.aspx. 4. Set Start Page From the Solution Explorer window, right click on Index.aspx and select “Set as Start Page”. Delete WebForm1 (from Solution Explorer Window, right click on WebForm1 and select delete). 5. Add a Style Sheet to Your Project When you want to specify presentation (e.g., font, size, spacing, or color) in your Web Application, always have your HTML reference a style sheet instead of putting these specifications directly into your HTML code. If we make extensive use of style sheets and the client wants a certain color or font changed throughout the web application, all we need to do is make a single change in the style sheet – and the whole site changes immediately. Otherwise (if we didn’t use style sheets or a similar technique), we’d have to find and change code in each aspx file. We might miss some changes resulting in an inconsistent website. To add a style sheet, select Project – Add New Item – select the “Style Sheet” icon from the Templates on the right of the screen. Name your style sheet “mystyle.css”. Put this simple code into your style sheet (replacing the “body {}” that is put there for you initially). VS provides intellisense to help you remember Style Sheet syntax. You may type this in or copy/paste from here. body {background-color:darkkhaki; font-family:arial; border:thin solid black} td {vertical-align:top; padding:1.4ex; border:thin solid saddlebrown} .page {text-align:center; width:100%} .homeicon {text-align:center; padding:0em;} .title {vertical-align:middle; color:Maroon; background-color:khaki; font-weight:bold; font-size:large; text-align:center;width=100%; padding:0.1em;} .navbar {text-align:center; background-color:khaki;} .content {text-align:left; background-color:cornsilk;} .footer {text-align:center; background-color:khaki; font-size:xx-small; font-weight:bolder;color:Maroon;} 3 6. Make All Web Forms Reference Your Style Sheet (then Test) Click on the HTML view of each of your 3 web forms (the .aspx files) and put this code into the header of each web form: <head> <LINK href="mystyle.css" type="text/css" rel="stylesheet"> ... </head> Press F5 to run your application. Index.aspx (which you set as your start page) should show up – empty but with a light brown background if everything is OK so far. If you want to check your other two pages (Products.aspx and Promotions.axpx which not set as start page), right click on them from the Solution Explorer pane and select “View in Browser”. 7. Include Graphic in your Web Application Download my graphic from doc sharing (the book with gloves on it). Right click on your project name from the Solution Explorer window. Select Add – New Folder. Name the folder “images”. Next, add the graphic to your project by right clicking on the images folder (from the Solution Explorer pane) and selecting Add Existing Item. Select the graphic from wherever you downloaded it. 4 8. Use Table to Create Layout for Your Home Page To create your basic page layout in Index.aspx, you’ll add a 2 column, 3 row table inside the form. The cells of this table will hold your icon (upper left), title (upper right), nav bar (center left), content area (center right), and footer (bottom), as shown. You can add a table to the web form either (from the menu) by clicking on Table – Insert or by just editing the HTML from the HTML view of your webform. Once your table has been added in, however, you’ll have to edit from the HTML view, for example to add the class attributes. Your html should never contain any presentation specifications (fonts, sizes, colors), but it will reference the style sheet that contains the presentation specifications (for the whole site). 5 You may type this in or copy/paste from here. <body> <form id="Form1" method="post" runat="server"> This part is already there… <TABLE class="page"> <tr> <td class="homeicon"><img src="images\shoes.jpg" width="126" height="112"></td> <td class="title"> SHOES 'N BAGS EXPRESS</td> </tr> <td class="navbar">Navbar</td> <td class="content"> CONTENT AREA </td> <tr> <td colspan="2" class="footer"> located at the King of Prussia Mall </td> </tr> </TABLE> </form> This part is already there… </body> Here is a good Web Reference if you want to learn more about Style Sheets: http://www.w3schools.com/css/default.asp Click on “try-it-yourself” under “CSS Examples” to see easy examples of about 70 different techniques. Appendix A of this document shows “a complicated style sheet”. If you see anything used there that interests you, learn about it from the above website. 6 9. Create a Navigation Bar With a User Control Most web application environments have the facility for re-using visual components. For example, PHP and JSP have “include” directives. ASP .NET has User Controls. The following exercise will help you become familiar with User Controls. When you have completed this exercise, your web application will have a single file that is the left navigation bar. This file can be referenced by all (or most all) webforms within your application. Then, whenever you need to modify the nav bar, you only need to make a change in one place (not in every webform). 1. Add a user control to your web application (Project – Add User Control). You can name your user control “navbar.ascx” (the ascx extension is used on user controls). This is going to be our navigation bar. 2. Add three linkbuttons from the WebForms group of the Toolbox. (In design mode, click between the linkbuttons and click enter to put a newline between the buttons.) 3. Label and rename each of these linkbuttons. For example, the Text property of the first linkbutton could be “Home” and its name could be lnkHome. 4. In the link button click event for each of the three link buttons, add code to redirect to the proper page, like this: Response.Redirect("Index.aspx"); 7 10. Register the User Control in the Home Page As the second line of HTML for Index.aspx, you register the user control (see bolded text in the code sample below). Note that “Src” attribute (of this first line) must be the exact name of the ascx file name that holds your user control. The other two attributes (TagPrefix and TagName) can be set to whatever you like. Whatever name you select, you will reference later in the web form, at the place where you want to insert the user control (in the left middle cell of the table – see bolded code below). <%@ Page language="c#" Codebehind="Index.aspx.cs" AutoEventWireup="false" inherits="UserControl2.WebForm1" %> <%@ Register TagPrefix="navTagPrefix" TagName="navTagName" Src="navbar.ascx" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <LINK href="mystyle.css" type="text/css" rel="stylesheet"> <title>WebForm1</title> <LINK href="mystyle.css" type="text/css" rel="stylesheet"> <meta name=…> </HEAD> <body> <form id="Form1" method="post" runat="server"> <TABLE class="page"> <TR> <TD class="navbar"> <navTagPrefix:navTagName id="myNav" runat="server" /> </TD> <TD class="content"> CONTENT AREA – Webform1 </TD> </TR> </TABLE> </form> </body> </HTML> 8 11. View User Control in Design Mode When you look at WebForm1 in design mode, you’ll see a button-like image representing the user control. 12. View User Control (Navigation bar) Rendered in Browser When you run your web app, you should see the navigation bar in the left center cell like this: 9 13. Add Layout to All Web Forms, Test Copy the boiler plate layout (the table described in the previous section entitled “Register the User Control in the Home Page”) to the other web forms. Make sure that you also copied the second line of the HTML that registers the user control. Test that all links in the navigation bar work (that they get you to the correct URL). Test that all pages have the same look and feel (color, layout, navigation bar, etc). 14. Passing Parameters to Another Web Form Whenever two functions can be served by one Web Form, you can achieve this reuse by passing parameters to a Web Form. For example, you should use one web form to add a record into a database table and that same web form to edit a record of that database table. Otherwise, you’ll have twice as many web forms to maintain and you’ll have to change two web forms whenever you need to change one of them. Consider these links (just put on the Home page for convenience of demonstration) – one is supposed to add a product and the other two are supposed to edit a particular product. Because you want to have a single web form add and edit the products, you typed this code into the HTML of this page (or you could have had some class create this HTML for you by pulling information out of your database table): <a href="Products.aspx">Add a Product to Database</a> <br/> <a href="Products.aspx?id=11111">Edit Red Shoes</a> <br/> <a href="Products.aspx?id=22222">Edit Blue Purse</a> <br/> 10 If you hover your mouse over the “Edit Red Shoes” link, you can check to see if it’s well-formed by looking in the lower left corner of the browser. When you click on the “Edit Red Shoes” link, you’ll see that it did invoke the Products.aspx page, sending the id with value “11111” in the query string (note the URL in the Address bar): 11 Recall also, that if you wanted to pass more than one parameter, the syntax is like this: http://localhost/CRUD/frmAddModStock.aspx?id=33333&pref=blue The URL above passed a parameter named “id” with a value of “33333” AND a second parameter named “pref” with value of “blue” to the form named frmAddModStock. In your program, you only specify the form name (the .aspx file name) and the parameters – you don’t (and shouldn’t prefix this with server and application name). It’s best to use relative (not absolute) references. 15. Reading Parameters Passed From Another Web Form In the page_load event of the called WebForm, there should be code to check for the value of the input parameter (called “id” in our example), like this: string strId = Request.QueryString["id"]; If strId == null, then no parameter was sent and (in our example) the web form should display empty textboxes, ready to receive new data from the user. Otherwise, a parameter was sent (that identifies the record we should be editing), so read the record from the database and pre-populate data in the textboxes, ready for the user to edit these values. The only additional wrinkle is that when the user clicks any button (such as the Save button), the page load event is also fired, so we need to determine if this is the first display of the form or a subsequent display of the form. To check for first display versus subsequent display, we need to use the Page.IsPostBack property (its false on first displays and true on subsequent displays). Here is the code that is needed to determine whether we should add or edit (on first display) and then how we should save (insert or update) on subsequent display (i.e., user clicked on the Save button). private static string mode=""; // need to declare this static so that its value persists between page renderings. private void Page_Load(object sender, System.EventArgs e) { string strId = Request.QueryString["id"]; if (!Page.IsPostBack) { // This is first display of form if (strId == null) { this.lblMessage.Text = "First Display, Add (no id in query string)"; this.lblMessage.Text += "<br/> so just remember the mode (add) and leave the textboxes blank"; mode = "add"; // remember this for subsequent display } else { this.lblMessage.Text = "First Display, Edit, id is [" + strId + "]"; this.lblMessage.Text += "<br/> so read the record with the specifed id and prepopulate the textboxes"; mode = "edit"; // remember this for subsequent display } } 12 } else { // This is subsequent display -- user pressed save button if (mode.Equals("add")) { this.lblMessage.Text = "User must have pressed save button (mode is add). " + " Call insert code and indicate if record was saved or not"; } else { // must be "edit" this.lblMessage.Text = "User must have pressed save button (mode is edit)." + " Call update code and indicate if Record was saved or not"; } } 16. Communicating Between Web Forms using the Session Object If you want to store information for the duration of the session, or you want to pass data to a web form without using the query string method, you can use the session object. Suppose that one web form wanted to save some data somewhere so that other Web forms in the application could read that data. For example, suppose the user entered a product into a textbox on a web form. That web form could have this code which adds a name value pair into the Session Object. (The name in this case is “product” and the value is whatever the user entered into the product textbox.) Session.Add("product", this.txtProduct.Text); That same web form could redirect to another web form directly, or not. Response.Redirect("WebForm2.aspx"); The Page_Load code of WebForm2 (or any web form in the application) can pull the data back out of the Session like this: this.lblName.Text=Session["name"]; Now whatever name was entered in the first web form is displayed on the second web form – and nothing was displayed in the query string in the address bar of the browser. In a more sophisticated application, you might want to put an object (not just a string) into the session, so the button click code of WebForm1 could do this: Stock objStock = new Stock("12345”, "RainHat") Session.Add("sessionStock", objStock); // name, value pair Response.Redirect("WebForm2.aspx"); Then the Page_Load code of WebForm2 would do this: Stock objStock2 = (Stock)Session["sessionStock"]; 13 // pull value out by name Using the Session is more secure than using the query string. However, you don’t want to put too much data into the Session or your web application will not scale (because the Session uses up server memory whereas the query string approach does not). Always keep the Session data minimal and cleaned up afterwards using various Session methods such as Clear, Remove, Removeall, Abandon. The Session is a very good place to store username and role (we’ll do this in a subsequent lesson) because there is one Session object per user/browser that’s running the web application. 17. Install Sample Code on your Laptop You should have been able to follow the instructions without needing sample code this week. However, should you run into problems and want to have some sample code that you know works, you may download the Reuse sample code from doc sharing. Recall the instructions for installing a web app from a zip file: 1. Extract the zip file onto your computer. 2. Create a new web application (on your computer) using Visual Studio. If you give the application the same name it has from the zip file, you can save a step (below). 3. From Visual Studio, select Project – Add Existing Item. a. Browse to the spot where you extracted the files from the zip file. b. From the “files of type” dropdown list, select “all files” (at the bottom of the browse window). c. Using the control and/or shift key, select all the files you want to bring into your new projects. This would be 3 files per webform and all the .cs files (excluding AssemblyInfo and Global which we don’t need). Do not select any files with “.csproj” in them (since these are the original project files which we don’t want). 4. If your project name does not match the namespace name of the files in the zipped project, then you must change all the namespace references in the project. To do this, select Edit – Find and Replace – Replace. Find all occurrences of the zipped namespace name and change them to your new project name. Make sure to select “Current Project” and Replace All. It will give you a warning which you may dismiss. Then it will tell you that the files have changed outside the editor – do you want to reload the files. Say yes. The namespace occurs not only in the class files (.cs files), but also in the webforms, so remember to do the replace for the whole project. 14 18. Try it Yourself Search the internet and find one site that shows content you like. If you are trying to create one web application that incorporates all the tutorials, then make sure that the content (topic) that you have selected matches up with the database table you created in the previous tutorial. Next, browse the internet and find another site that has a “look and feel” that you like. Create a web application with a web form that will eventually be your home page. Type in content (text) that provides an overview of what you plan to include in your site (you can always change this later, but create something that gives you a clear direction). Give this home page a Look and Feel that resembles your goal site as much as possible, although you may deviate from it as long as you like the results and the site remains readable and usable. o Like you did in the exercise above, use a style sheet. Put all presentation specifications (e.g., color, size, alignment) in the style sheet, not in the HTML. The HTML references the style sheet and the style sheet gives the presentation specifications. Like you did in the exercise above, include a graphic for your layout. You can use Google, click on images, right click a picture you like, click “save picture as” and save the file. Since you probably want a small graphic, you may want to right click on the thumbnail versions of the images. I then usually open the image in MicroSoft Photo Editor, then click on Image – Resize just to see the width and height of the image in pixels so you can use these values for the height and width attributes of the img tag that references your graphic. Like you did in the exercise above, create a navigation bar from a user control and add this into your home page. Don’t use the exact names that I used for my user control. For example, select a different file name for the control, a different tag prefix, a different tag name and so forth. You will learn best by deviating (in a controlled manor) from the sample code. Your navigation bar should be complete, providing all links that you eventually would like to have in your web application. One link should point back to the home page (unless you choose to have your graphic do that.) Don’t worry about adding too many links. You will point the extra links to an “Under Construction” web form. o You may choose to create additional user controls, for items such as graphic, title, and footer. Include an “Under Construction” web form in your web application as mentioned above. Make sure that all of your nav bar links work – they should either point to a real web form or they should point to the under construction web form. Add the Validate web form that you created in a previous tutorial. So, your web application at this point, should have: A new home page that has your desired look and feel and has describes (with text) what content you plan to include in your web application. Your validate web form (from a previous tutorial) and an “Under Construction” web form. All three web forms should have the same look and feel (referencing the same style sheet) and they all should contain your navigation bar (created from a user control). 15 Appendix A – A Sample Style Sheet Note which CSS attributes are used most often. These are the attributes that help provide a professional look and feel to your web application. body {background-color:#A5C5AB; font-family:arial; border:thin solid black} .sk_wholepage { width:100%; background-color:#A5C5AB;} .sk_content {font-size:0.8em; background-color:#F7F9C4; color:black; font-weight:normal; border:thin solid saddlebrown; vertical-align:top; padding-top:1.4ex; padding-left:0.7ex; padding-right:0.7ex; padding-bottom:0.7ex; width:"100%"} .exp_content {font-size:0.8em; background-color:#F7F9C4; color:black; font-weight:normal; border:thin solid beige; vertical-align:top; padding-top:1.4ex; padding-left:0.7ex; padding-right:0.7ex; padding-bottom:0.7ex;} .exp_table {width=100%;} h1,h2,h3,h4,h5 {color:black;} h1 {font-size: 1.1em; text-indent:0ex} h2 {font-size: 1em; text-indent:2ex} #backtotop {float:right; font-size: 0.9 em} .moredetails {font-size:0.9em} a:hover {background-color:lemonchiffon;} .sk_navbar a {text-decoration: none} .sk_content a {text-decoration: underline;} .sk_image a {border:none; text-decoration:none} .image{float:right;border:thin solid tan; margin:0.5em} .sk_headtitle {vertical-align:middle; color:saddlebrown; font-family:times new roman,century,georgia; text-align:center;width=100%; padding:0.2em;} .sk_cybername {font-size:36px; font-weight:bolder; color:black; vertical-align:text-top;} .sk_cyberwhat {font-size:20px; color:darkred; letter-spacing:5px} .sk_smallcyberwhat {font-size: 19px; letter-spacing:2px;color:darkred;} .sk_navbar { padding-right:1ex; text-align:center; vertical-align:text-top} .sk_navlink {background-color:khaki; border:thin solid maroon; padding-top:0.2ex; padding-bottom:0.2ex; padding-left:0.5ex; padding-right:0.5ex; margin-top:0.5ex; font-size:.795em; font-weight:bolder; text-align:center} .sk_error {font-weight:600;color:red} .sk_sql_table {padding:0.6ex; font-size:1.0em; text-align:center;vertical-align:top} 16 .sk_sql_table td {border:thin solid tan} #sk_input_area {text-align:center} .sk_input_table {padding:0.6em; margin:1.5em;} .sk_input_border {padding:0.6em; margin:1.5em; border:thin solid tan} .sk_input_header {padding-left:0.5ex;padding-right:0.5ex; padding-bottom:1.5ex; padding-top:1.5ex; border-bottom:thin solid tan;border-top:thin solid tan; font-size:0.8em;font-weight:bold; text-align:center} .sk_input_footer {padding-left:0.5ex;padding-right:0.5ex; padding-top:1.5ex; font-size:0.8em; font-weight:bold; text-align:center} .sk_left_td {padding:0.6ex; font-size:0.7em; text-align:left;vertical-align:top} .sk_right_td {padding:0.6ex; font-size:0.7em; text-align:center; vertical-align:top} .sk_footer {color:darkred; font-family:times new roman,century,georgia; text-align:center; font-size:0.7em;font-weight:600;} .sk_footer_span {letter-spacing:4px} 17