Beginning asp net 2.0 with c phần 5 ppsx

77 395 0
Beginning asp net 2.0 with c phần 5 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

saveFile = Path.Combine(savePath, FileUpload1.FileName); FileUpload1.SaveAs(saveFile); // Displays status of success StatusLabel.Text = “Your file was uploaded successfully.”; } catch(Exception exUpload) { // display status of error StatusLabel.Text = exUpload.Message; } } else // probably file was not selected { // Display status of failure StatusLabel.Text = “You did not specify a file to upload.”; } In the following Try It Out, you give users a way to add pictures to the gallery. Try It Out Uploading Files— Basic 1. Using VWD, create a new page named GalleryUpload.aspx using the Web Form template. As you have with most pages up to this point, use the site.master as the Master page, use Visual C#, and enable the option to place the code on a separate page. 2. In Design View, add a FileUpload control from the Toolbox and a Label control that will have an ID of FileUploadReport with an empty text property. Also add a button control with the text property set to “Upload”. 3. Double-click the button to go to its code. Add the following shaded code to the Sub: using System; using System.IO; using public partial class GalleryUpload : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { string ImagesFolder = “MatchImages”; string savePath; string saveFile; if (FileUpload1.HasFile) { try { // perform the upload savePath = Path.Combine(Request.PhysicalApplicationPath, ImagesFolder); saveFile = Path.Combine(savePath, FileUpload1.FileName); FileUpload1.SaveAs(saveFile); // Displays status of success FileUploadReport.Text = “Your file was uploaded successfully.”; } catch(Exception exUpload) 276 Chapter 8 11_042583 ch08.qxd 4/4/06 2:46 PM Page 276 { // display status of error FileUploadReport.Text = exUpload.Message; } } else // probably file was not selected { // Display status of failure FileUploadReport.Text = “You did not specify a file to upload.”; } } } 4. Save the page and view it in your browser (see Figure 8-11). You probably won’t have pictures of the hapless Wrox United fumblers, but you can try uploading any jpeg or gif you have on your hard drive. Figure 8-11 How It Works The FileUpload control itself is a simple drag-and-drop. The browsing capability is built in. However, there is no built-in means to execute the upload. So you added a button to fire the SaveAs method of the FileUpload control. That method needs an argument specifying where to put the file on the server. You hard-coded a literal for the path and then appended the name of the file the user entered into the FileUpload control. You have done some embellishments beyond the basic control. The FileUpload control has a handy property called HasFile. When there is a valid file name in the text box, the HasFile property will be TRUE. The IF statement determines whether the user actually typed or browsed to a file to upload. If not, the code hops down to the ELSE statement to display an error message. Other things could go wrong, like the Wrox United webmaster (even more hapless than the team) changes the name of the folder in which to store images. So you encapsulated the execution of the SaveAs within a Try Catch block. 277 Writing Data 11_042583 ch08.qxd 4/4/06 2:46 PM Page 277 Improving the Upload of Pictures You finish this chapter with an improvement to the page that uploads photos and, in the process, review some ideas from this chapter and Chapters 6 and 7. You will add a feature that creates an entry in the database table of photos when a photo is uploaded. In other words, you will both upload the file and create a new record. The following few paragraphs give an overview of your tasks and the Try It Out gives exact directions. Start by using the Data Explorer to take a look at the structure of the Gallery table as in Figure 8-12. Each record represents an image a fan has uploaded, with fields for the fan’s name, URL of the picture file, date, and opponent. Figure 8-12 Now you need to add inputs to the page to get the information you need for the fields of the Gallery table. Whenever possible, avoid letting users type information. In this case, the number of matches is reasonably small, so you will create a ListBox control for that input. The SelectCommand that provides data for the ListBox will display the date of the match to the user. The FixtureID will be the ListBoxValue. You will also want to gather the user’s name and comments with text boxes. The page will end up looking like Figure 8-13. Now the trick will be inserting a new record into the table. You do this by setting up a SqlDataSource control that is enabled for inserting. But you do not need to render any data, so this data source control will not have a data-bound control. Built into the SqlDataSource is the Insert method, which you can invoke from your button-click code. 278 Chapter 8 11_042583 ch08.qxd 4/4/06 2:46 PM Page 278 Figure 8-13 In this Try It Out, you enhance the gallery upload so that it performs the upload of the image file and then creates a record for the image file in the Gallery table. Try It Out Uploading Files with Record Creation 1. Using VWD, open the Solution Explorer and make a copy of the GalleryUpload.aspx pages following these instructions. Find in the file list, but do not open, the GalleryUpload.aspx page. Right-click it and select Copy. Right-click the root of the site and select Paste. Now find the nascent file that named Copy of GalleryUpload.aspx. Rename it GalleryUpload Enhanced.aspx. This procedure ensures proper copying and renaming of the associated code file. 2. Working with GalleryUploadEnhanced.aspx in Design View, move the insertion bar (cursor) below the FileUpload control, add a ListBox, and from the smart task panel, click Choose Data Source. Select a new data source, use a database source, and name the control SqlData SourceFixtures . Use the WroxUnited connection string and set it to display from the Fixtures table only the FixtureID and FixtureDate fields, ordered by date ascending. After finishing the Wizard, you can set the ListBox properties to display the date and field for the value to FixtureID (see Figure 8-14). 279 Writing Data 11_042583 ch08.qxd 4/4/06 2:46 PM Page 279 Figure 8-14 3. Add to the page two TextBox controls for the fan’s name and notes about the picture. In the Properties window, set the ID of the boxes to TextBoxMemberName and TextBoxNotes. Give them some labels with text that identifies what the user should type in the box. 4. Add a second SqlDataSource to the page that you will configure to create the record in the Gallery table for the new uploaded photo. Name it SqlDataSourceCreateGalleryRecord. Using its smart task panel, configure the data source and choose the WroxUnited connection string. Use the Gallery table and select all of the fields. In the Advanced panel, check the creation of the INSERT, DELETE, and UPDATE commands. Click the Next and Finish buttons. If you want, switch to Source View and delete the commands and parameters for the UPDATE and DELETE functions. They will not be used, so deleting them cleans up the code to make maintenance eas- ier, but they don’t interfere if you want to leave them. Be careful not to delete any end-of-prop- erty double quotes or any end-of-tag > symbols. 5. Switch to Source View and find the set of <InsertParameters>. Modify them so that they come from the four input controls, as per the shaded lines in the following listing of the entire .aspx page’s code: <%@ Page Language=”C#” MasterPageFile=”~/site.master” AutoEventWireup=”false” CodeFile=”GalleryUpload-Enhanced.aspx.cs” Inherits=”GalleryUpload” title=”Untitled Page” %> <asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”Server”> <h2>Upload your photos from matches</h2> <br /><br />Please enter the name of the photo file: <asp:FileUpload ID=”FileUpload1” runat=”server” /> <br /><br /> Match Date: <asp:ListBox ID=”ListBox1” runat=”server” DataSourceID=”SqlDataSource1” DataTextField=”FixtureDate” 280 Chapter 8 11_042583 ch08.qxd 4/4/06 2:46 PM Page 280 DataValueField=”FixtureID”> </asp:ListBox> <asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:WroxUnited2 %>” SelectCommand=”SELECT [FixtureID], [FIxtureDate] FROM [Fixtures]”> </asp:SqlDataSource> <br /><br /> User Name: <asp:TextBox ID=”TextBoxMemberName” runat=”server”></asp:TextBox> <br /><br /> Comments: <asp:TextBox ID=”TextBoxNotes” runat=”server”></asp:TextBox> <br /><br /> <asp:Button ID=”Button1” runat=”server” Text=”Upload” /><br /> <asp:Label ID=”FileUploadReport” runat=”server”></asp:Label><br /> <asp:SqlDataSource ID=”SqlDataSource2” runat=”server” ConflictDetection=”CompareAllValues” ConnectionString=”<%$ ConnectionStrings:WroxUnited2 %>” InsertCommand=”INSERT INTO [Gallery] ([FixtureID], [UploadedByMemberName], Notes], [PictureURL]) VALUES (@FixtureID,@UploadedByMemberName,@Notes,@PictureURL)” OldValuesParameterFormatString=”original_{0}” > <InsertParameters> <asp:ControlParameter Name=”FixtureID” ControlID=”ListBox1” PropertyName=”SelectedValue” Type=”Int64” /> <asp:ControlParameter Name=”UploadedByMemberName” ControlID=”TextBoxMemberName” PropertyName=”Text” Type=”String” /> <asp:ControlParameter Name=”Notes” ControlID=”TextBoxNotes” PropertyName=”Text” Type=”String” /> <asp:ControlParameter Name=”PictureURL” ControlID=”FileUpload1” PropertyName=”FileName” Type=”String” /> </InsertParameters> </asp:SqlDataSource> </asp:Content> 6. Now you just need to modify the GalleryUpload-Enhanced.aspx.cs code page (shown here). In Design View, double-click the Upload button and add the following shaded line of code: using System; using System.IO; protected void Button1_Click(object sender, EventArgs e) try catch(Exception exUpload) 281 Writing Data 11_042583 ch08.qxd 4/4/06 2:46 PM Page 281 { // display status of error FileUploadReport.Text = exUpload.Message; } SqlDataSourceCreateGalleryRecord.Insert(); } else // probably file was not selected { 7. Save the page and test it in your browser by uploading any picture (you can use My Pictures/ Samples) along with picking a match and your name and a comment. Figure 8-15 shows the screen prior to clicking the Upload button. Figure 8-15 8. Confirm your success by closing the browser, returning to VWD, opening the Database Explorer, and expanding WroxUnited and then Tables. Right-click Gallery and select Show Table Data. Observe your new record as in the bottom line of Figure 8-16. Figure 8-16 282 Chapter 8 11_042583 ch08.qxd 4/4/06 2:46 PM Page 282 How It Works The objective here was to create a new record in the Gallery table whenever a user uploaded an image. You started by setting up inputs so the user could enter data needed for the record. The ListBox offered a choice of games and two TextBox controls took in the user’s name and notes. In order to populate the ListBox, you created a SqlDataSource that picked up two fields from the Fixtures table. In order to create a new record, you need to add a SqlDataSource control that holds the INSERT func- tionality. When you asked VWD to add commands for insert, you got a lot, and it wasn’t what you wanted. You deleted the commands and parameters for SELECT, UPDATE, and DELETE because you won’t use them. Then within <InsertParameters>, you changed to use the input controls as sources. Last, you wanted to actually tell the SqlDataSource to perform the insert of a new record. You did that with a single line of code in the Button_Click event that invoked the Insert() method. This enhanced page brings together several ideas from the last few chapters. You used code in an event (Chapter 6) to catch problems with the FileUpload and to invoke the data source control’s Insert() method. You read from a database (Chapter 7) to stock the ListBox. And, last, you wrote to a database (in this chapter) to create a new record to represent the uploaded picture. Summary Writing data includes creating entire new records (called inserting), changing values in existing records (updating), and removing entire records (deleting). Both data source and data-bound controls contain code for behavior to write to databases. This chapter explained how to turn on and use these behaviors. Most, but not all, data controls support writing. Selection lists ( DropDownList and ListBox) do not support writing. GridView can update and delete, but not insert. DetailsView or FormView are ideal for all forms of writing. Any database front-end that updates data can run into problems when a value is simultaneously changed and needed for identifying a unique record. ASP.NET 2.0 manages a dictionary of old and new values. The fields to be included in the dictionary are listed in the DataKeyNames property of the data- bound control. The pattern for inserting, updating, and deleting is to make three changes to the data controls. In the data source control, you must add the appropriate command with the value of a valid SQL statement. You must also include a set of parameters that feed values into the SQL statement. In the data-bound control, you must include a CommandField of the type equal to the writing operation you want to per- form. All three of these changes are made through VWD with check-offs in wizards or the Common Tasks panels. The parameters can be a little tricky until you gain some experience. Simple parameters will hold the existing values that came from the database. ControlParameters will hold values that were entered by the user into controls other than the data-bound control that holds the parameter. Reference to a value in a parameter is made in a command by placing an at symbol (@) before the parameter’s name. Parameters are organized into sets for each kind of writing command. So when performing an INSERT, ASP.NET 2.0 will look up values in the parameter set within <InsertParameters>. 283 Writing Data 11_042583 ch08.qxd 4/4/06 2:46 PM Page 283 Keep in mind two caveats when writing data: ❑ Writes can lead to logical and organizational errors. For example, your database administrator will not let you delete a customer if that customer has an order (otherwise the order would be shipped to a non-existent customer). It behooves you to limit your user requests and then also be prepared to handle a rejection from your database. ❑ Writing commands opens your data to a number of types of attacks. Whenever possible, present the user with a list of options rather than allowing typed input. When typing is absolutely nec- essary, use the ASP.NET 2.0 validation controls. The capability to transfer files from the user to the server enhances many business objectives. A single, simple control provides the functionality to identify a file. However, the actual transfer requires the use of a button to actually execute the uploading behavior. As demonstrated in the final exercise, that button can also trigger the execution of writing behavior in a data source control that has no data-bound con- trol. The data source control can use control parameters to gather values and create an insert in a table. Over the last eight chapters you have seen how powerful ASP.NET 2.0 can be with the use of practically no code. You have solved many common business scenarios such as logging on, personalization, and working with data. But in some more advanced cases, you will be forced to write custom code, and for those techniques, carry on to Chapter 9. Exercises 1. Enabling the capability to write to a database requires changes to the properties of a data source control, a data-bound control, or both? 2. Describe the difference between an asp:Parameter and an asp:ControlParameter. 3. What problem does the DataKeyNames property solve? 4. A page needs to delete the date of birth value from one record. Which command should be used? 5. What tags must be added to a page to allow a GridView to create new records? 284 Chapter 8 11_042583 ch08.qxd 4/4/06 2:46 PM Page 284 9 Code You’re now getting to the stage where the site is getting more features, and you need to start learn- ing more about code. Some of the code used in previous chapters might not have been explained fully — that’s because what the code was doing was more important than the actual code itself. It’s not that the code wasn’t important, but rather that the technique being taught was the key; under- standing how the actual code worked could come later. Now it’s time to learn about the basics of writing code, what makes good code, and how you put all that code together. In particular, this chapter looks at the following topics: ❑ What data types and variables are and how they are used ❑ How you make decisions in your code ❑ How you repeat lines of code ❑ What object-oriented programming means and why it’s important ❑ How to think about structuring your code so it’s well organized and easy to maintain ❑ How one of the new language features in ASP.NET 2.0 eases working with collections of objects There’s a lot to cover, and although some of it might sound difficult, it’s actually quite easy. You start with finding out about data types. Variables and Data Types When you use applications, you don’t really care how the application stores your data, just that it does. As a programmer, however, you have to think about this. What sort of data is the user enter- ing? Is it text, numbers, dates, or something else? This matters because how you store data inter- nally in your application affects not only how you deal with the data, but also what you can do with that data. To store data internally, variables are used (variables are simply names, used to store information during code), and variables have types; there is a type for each type of data. For exam- ple, there is a data type called string, unsurprisingly used for strings, or text data. There is a data 12_042583 ch09.qxd 4/4/06 2:47 PM Page 285 [...]... are occasions where you need to explicitly deal with a database, and this becomes truer as you gain experience and write more complex applications The checkout for Wrox United is one case, where the items from the shopping cart are written to the database For this a SqlConnection object is used, which provides a way to connect to a specific database For example: SqlConnection conn = new SqlConnection(“... ”); conn.Open(); // insert the checkout items conn.Close(); This code fragment opens a database connection, inserts the checkout items, and then closes the connection However, if there is an error when opening the connection, the conn variable wouldn’t contain an active connection, so the Close would fail This is where object tests are used, so the Close could be modified to the following: if (conn... value is false ❑ byte is used for a single byte of data This can be a single character or a number from 0 to 255 The default value is 0 ❑ char is used for two bytes of data This can be a character or a number from 0 to 65, 5 35 Because it is bigger than a byte, char can store double-byte characters like those used by foreign character sets such as Chinese The default value is 0 ❑ DateTime is used to store... know much about it now, although it’s definitely worth learning about as you become more experienced The reason that the CLR has data types and the language has data types is that the CLR is common to all languages in NET Whether you use Visual Basic NET, C# , or even COBOL NET, underneath you are using the CLR However, languages have history (apart from C# , which was new for NET, but C# has a C and C+ +... are what drive your code Statements are what allow you to structure your code, to make decisions, and to repeat actions a number of times For example, to make a decision, you use the if statement, which can be used to allow the code to react to external criteria Take the Wrox United checkout page, where members of the fan club receive a discount This is done with a decision, which goes something like... following: if (conn != null) conn.Close(); If an error occurs, conn wouldn’t be assigned a value and would be null, so conn is tested before being closed If it is not null, the connection can be closed You’ll learn more about this topic in Chapter 15 309 Chapter 9 Logical Operators Logical operators allow the combination of expressions The operators are as follows: Operator Actiond && True if both sides... Difference; Difference = Date1.Subtract(Date2); Label1.Text = Difference.ToString(); 294 Code This code creates two dates, March 10 and March 5, and then declares a variable of type TimeSpan, which will hold the difference between the dates The difference is calculated by using the Subtract method of the date — because the Date1 variable is a Date type the Subtract method can be used, and Date2 is passed... preference, because there’s no real difference between them Collections Another way of storing multiple items is to use collections Collections differ from arrays in that they are always dynamically allocated, which makes them more suitable for situations where the amount of data changes frequently There are different collections for different purposes, stored in the System.Collections namespace (more... first off ❑ StringCollection provides a collection of strings There are other collections, but these are the ones you’ll probably use most frequently Data is added to collections by calling an Add method, the parameters of which depend upon the collection being used For the StringCollection, you simply supply the string to be added For example: StringCollection Names = new StringCollection(); Names.Add(“Dave”);... pros and cons of using both arrays and collections, and the decision of which to use can sometimes be confusing In general, if the number of elements isn’t going to change, an array is best — it’s efficient and fast, and it provides easy access to the elements If you need to change the number of elements, or insert elements between others, then a collection is best Both arrays and collections can, like . Date ( 20 05, 3, 10) ; DateTime Date2 = new Date ( 20 05, 3, 5) ; TimeSpan Difference; Difference = Date1.Subtract(Date2); Label1.Text = Difference.ToString(); 29 4 Chapter 9 12_ 0 4 25 83 ch09.qxd 4/4 /06 2: 47. 5) ; 29 3 Code 12_ 0 4 25 83 ch09.qxd 4/4 /06 2: 47 PM Page 29 3 ❑ Replace replaces characters within the string. For example, to replace abc with def you would use this: MyNewString = MyString.Replace(“abc”,. source control will not have a data-bound control. Built into the SqlDataSource is the Insert method, which you can invoke from your button-click code. 27 8 Chapter 8 11 _0 4 25 83 ch08.qxd 4/4 /06 2: 46

Ngày đăng: 09/08/2014, 18:22

Tài liệu cùng người dùng

Tài liệu liên quan