BeginningASP.NET 2.0 with C# PHẦN 5 potx

76 365 0
BeginningASP.NET 2.0 with C# PHẦN 5 potx

Đ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

DeleteCommand=”DELETE FROM [Fixtures] WHERE [FixtureID] = @original_FixtureID AND [FixtureDate] = @original_FixtureDate AND [FixtureType] = @original_FixtureType AND [GoalsFor] = @original_GoalsFor AND [GoalsAgainst] = @original_GoalsAgainst AND [Notes] = @original_Notes AND [Opponents] = @original_Opponents “ 5. Save the page and test it in your browser. It should look like Figure 8-10. Figure 8-10 Note that if you try to actually delete a fixture you will get an error message. Many other aspects of the site rely on the list of fixtures, so deleting one will leave those data hanging with- out a fixture. This situation is called a reference constraint as mentioned in the error. How It Works The pattern is the same as for other means of changing data. The data source control must have a DeleteCommand. When you checked the option in the Advanced step of the Configure Data Source wiz- ard, VWD created the DeleteCommand for you. VWD also created a set of DeleteParameters that will be used by the WHERE clause to identify the record to delete. As with UPDATE, VWD tries to match every field in the DeleteParameters list for DetailsView. This may be necessary in some cases, but for now a simple match of the FixtureID is sufficient. You then enabled deleting on the data-bound control, which instructed VWD to add a CommandField of the type Delete to the data-bound control. The term “field” here is a little odd because there is no con- nection to a field in the data table, but it is an addition to the data-bound control that is rendered simi- larly to a field. One thing you may have noticed while running through the exercises in this chapter is that you have two ways of showing and editing the fixtures: GridView and DetailsView. When you edited data in one, the changes weren’t reflected in the other. To get around this, you need to add code to the data 273 Writing Data 11_042583 ch08.qxd 4/4/06 2:46 PM Page 273 source controls, and although you only need a single line of code, it has to be entered in several places. This is because there are several ways the data can change: you can insert new fixtures, edit existing fix- tures, or delete fixtures. Each of these causes the SqlDataSource control to raise an event, and it is within that event that you have to rebind the data for the other control. The code for this is shown here: protected void SqlDataSource1_Deleted(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e) { DetailsView1.DataBind(); } protected void SqlDataSource1_Inserted(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e) { DetailsView1.DataBind(); } protected void SqlDataSource1_Updated(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e) { DetailsView1.DataBind(); } protected void SqlDataSource2_Deleted(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e) { GridView1.DataBind(); } protected void SqlDataSource2_Inserted(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e) { GridView1.DataBind(); } protected void SqlDataSource2_Updated(object sender, System.Web.UI.WebControls.SqlDataSourceStatusEventArgs e) { GridView1.DataBind(); } You can see that there are three events for each control. The Deleted event is raised after a record is deleted, the Inserted event is raised after a record is added, and the Updated event is raised when a record is updated. Even through you are using a GridView control to display one set of data, and a DetailsView control for the other, the events look the same because it is the SqlDataSource control that raises the event. For the GridView, which is bound to SqlDataSource1, the DetailsView needs to be refreshed, so the DataBind() method is called on the DetailsView, which instructs it to re-fetch the data. A similar procedure is done for the events of SqlDataSource2, which is used by the DetailsView, but this time the DataBind() method is called on the GridView1 control. It’s a simple procedure —when data in one control changes, you refresh the data in the other control. Uploading Pictures ASP.NET 2.0 offers an easy way to upload pictures (or other files) from the browser to the server. Although not strictly a database issue, the topic is covered here. The toolbar offers the FileUpload tool, which can be added to the page to produce a text box with a browse button. You, as the designer, must also add a button to give the user the capability to actually execute the upload. In the button’s click code, the simplest option is shown in the following code. The file that the user indi- cated (either by typing or browsing) will be transferred to the server: FileUpload1.SaveAs(FileUpload1.FileName); 274 Chapter 8 11_042583 ch08.qxd 4/4/06 2:46 PM Page 274 But this code is too simplistic because the file will be plopped into the root of the web site. You can add a literal string to be appended in front of the file name that will direct the file into an appropriate folder on the server. Note that when you open the page in your browser you can view the source, but the path on your server is not revealed. The following code places the file in MyImageFolder: using System.IO string ImagesFolder = “MyImageFolder”; string savePath; string saveFile; savePath = Path.Combine(Request.PhysicalApplicationPath, ImagesFolder); saveFile = Path.Combine(savePath, FileUpload1.FileName); FileUpload1.SaveAs(saveFile); When the FileUpload.SaveAs method is invoked, ASP.NET 2.0 creates an object named FileUpload .PostedFile with several properties about the operation. The most obvious are FileName and ContentLength. So if you create a label named Label1 you can display in its text the name of the file that was uploaded as follows: FileUpload1.SaveAs(saveFile); Label1.Text = FileUpload1.PostedFile.FileName; What if the user clicks the button without first selecting a file? You can avoid this problem with an IF THEN statement as follows (code structures such as IF THEN are explained in Chapter 9): // If a file was selected, then upload the file if (FileUpload1.HasFile) // perform the upload { FileUpload1.SaveAs(saveFile); // Displays status of success Label1.Text =”Your file was uploaded successfully.”; } else // probably no file selected { // Display status of failure Status.Text = “You did not specify a file to upload.”; } Other errors can occur, so you should encase the FileUpload method in an error-catching routine as follows: protected void ButtonUsingTryCatch_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); 275 Writing Data 11_042583 ch08.qxd 4/4/06 2:46 PM Page 275 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 [...]... lowercase Plenty of other string methods exist, some of which are described here: ❑ EndsWith returns true if the string ends with a given string For example: if (MyString.EndsWith(“ate”)) ❑ StartsWith returns true if the string starts with a given string For example: if (MyString.StartsWith(“wha”)) ❑ IndexOf returns the position within the string of a given character or string, or -1 if the item isn’t found... that doesn’t use that format For example, take the date 03/ 05/ 20 05 — does this represent March 5 or May 3? You could easily assume the format, but that leads to potential errors Instead of using literals to initialize dates, C# uses the DateTime object to create a new instance on a date, like so: DateTime Birthday = new DateTime(20 05, 3, 5) ; The parameters are in year, month, and day order, and because... either true or false The default 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... example, to pad a string to a total of 15 characters, you would use the following: MyNewString = MyString.PadLeft( 15) ❑ Remove removes a section of a string For example, to remove five characters starting at position 4, you would use this: MyNewString = MyString.Remove(4, 5) ; 293 Chapter 9 ❑ Replace replaces characters within the string For example, to replace abc with def you would use this: MyNewString... this: MyNewString = MyString.SubString(4, 5) ; For a full list of string methods, you should consult the documentation The String type has a couple of properties, but the only one you will probably use is Length, which returns the number of characters within the string Working with Dates In C#, you can place dates as literals into your code, but one problem with this is that it has to be in the MM/DD/YYYY... string) data The default value is null in C# ❑ uint is the unsigned equivalent of an int Because it is unsigned it can only store positive num- bers, giving a range of 0 to 4,294,967,2 95 The default value is 0 ❑ ulong is the unsigned equivalent of a long Because it is unsigned it can only store positive numbers, giving a range of 0 to 18,446,774,073,709 ,55 1,6 15 The default value is 0 ❑ ushort is the... method The result is that Date2 is subtracted from Date1, and in this case the result would be 5. 00:00:00, which represents 5 days, 0 hours, 0 seconds, and 0 milliseconds Now that you have a good base of knowledge to work with, the following Try It Out has you work with simple data types Try It Out Working with Simple Types 1 Open the directory for the Chapter 9 samples, called Chapter09 and located... DateTime.Parse(TextBox3.Text).ToString(); 5 Save both the Web Form and the code-behind file, and set the Web Form to be the start page (right-click the page in the Solution Explorer) 6 Press F5 to run the page and enter 3 into the first text box, enter 4 into the second text box, and enter 12/2/ 05 into the third text box 7 Press the button and observe the results On a machine configured with UK regional settings, you’ll see Figure 9-2 2 95. .. 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++ base in terms of the language syntax), and so have data types of their own For compatibility reasons, it makes sense to keep these specific language types This enables users of the language to work with familiar data types, and... object, filled with data from a database What happens if, while fetching the data, there is some sort of error? There will probably be an exception thrown (these are covered in Chapter 15) , but the method still might return, only there’s no data for you — the value returned might be null In C# the null value is represented by the keyword null You look at how you test for null values later Working with Strings . is 0. ❑ int is used for whole numbers between 2, 147,483,648 and 2, 147,483,647. The default value is 0. ❑ long is used for whole numbers between –9 ,22 3,3 72, 03 6, 854 ,7 75, 808 and 9 ,22 3,3 72, 03 6, 854 ,7 75, 807 not be important to you if you intend to stick with one language. 29 0 Chapter 9 12_ 0 4 25 83 ch09.qxd 4/4 /06 2: 47 PM Page 29 0 Converting Data Types with Casting Another way of converting between. performing an INSERT, ASP .NET 2. 0 will look up values in the parameter set within <InsertParameters>. 28 3 Writing Data 11 _0 4 25 83 ch08.qxd 4/4 /06 2: 46 PM Page 28 3 Keep in mind two caveats

Ngày đăng: 09/08/2014, 14:20

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan