Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
20
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Writing Data

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 line. The file that the user indicated (either by typing or browsing) will be transferred to the server:

FileUpload1.SaveAs(FileUpload1.FileName)

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:

FileUpload1.SaveAs(“MyServer\MyWebsite\MyImageFolder\” & FileUpload1.FileName)

When the FileUpload.SaveAs method has been 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(“C:\BegASPNET2\WroxUnited\MatchImages\” & FileUpload1.FileName) Label1.Text = “File uploaded to WroxUnited from: <br/>” & _

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 FileUpload1.HasFile Then

FileUpload1.SaveAs(“C:\BegASPNET2\WroxUnited\MatchImages\” & FileUpload1.FileName)

Else

Label1.Text = “Please select a file before clicking the ‘Upload’ button”

End If

Other errors can occur, so you should encase the FileUpload method in an error catching routine as follows:

If FileUpload1.HasFile Then

Try

FileUpload1.SaveAs(“C:\BegASPNET2\WroxUnited\MatchImages\” & _

FileUpload1.FileName)

Catch ex As Exception0

Label1.Text = “Failed because: <br/>” & ex.Message

End Try

Label1.Text = “File uploaded to WroxUnited from: <br/>” & _

FileUpload1.PostedFile.FileName

Else

Label1.Text = “Please select a file before clicking the ‘Upload’ button”

End If

In the following Try It Out you give users a way to add pictures to the gallery.

279

Chapter 8

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 Basic, and enable the option to place the code on a separate page.

2.In Design View, add a FileUpload control from the toolbar 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:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

If FileUpload1.HasFile Then Try

FileUpload1.SaveAs(“C:\BegASPNET2\Chapters\Begin\Chapter08\MatchImages\” & _ FileUpload1.FileName)

Catch ex As Exception

FileUploadReport.Text = “Failed because: <br/>” & ex.Message End Try

FileUploadReport.Text = “File uploaded to WroxUnited from: <br/>” & _ FileUpload1.PostedFile.FileName

Else

FileUploadReport.Text = “Please select a file before clicking “ & _ “the ‘Upload’ button”

End If End Sub

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

280

Writing Data

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 of where to put the file on the server. You hardcoded a literal for the path and then appended the name of the file as the user entered in the FileUpload control.

But 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.

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 when a photo is uploaded, an entry is created in the database table of photos. 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

281

Chapter 8

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.

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.

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 will be named Copy of GalleryUpload.aspx. Rename it GalleryUploadEnhanced.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 below the FileUpload control, add a ListBox, and from the smart task panel invoke the Configure

282

Writing Data

Data Source wizard. Use a Database source and name the control SqlDataSourceFixtures. Use the WroxUnited connection string and set it to display from the Fixtures table only the FixtureID and FixtureDate fields, ordered by date. In the end of the wizard you can set the ListBox properties of the DataTextField to the date and the DataValueField to the FixtureID (see Figure 8-14).

Figure 8-14

3.Add 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 identify 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 Gallery for the new uploaded photo. Name it SqlDataSource2. Using its smart task panel, configure the data source and choose the Wrox United connection string. Use the Gallery table and select all of the fields. In the Advanced panel, check on 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 and makes it mountains easier, but they don’t interfere if you want to leave them. Be careful not to delete any end-of-property 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=”VB” MasterPageFile=”~/site.master” AutoEventWireup=”false” CodeFile=”GalleryUpload-Enhanced.aspx.vb” Inherits=”GalleryUpload” title=”Untitled Page” %>

283

Chapter 8

<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” 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=”Int32” />

<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.APX.VB code page (shown here). In Design View, double-click the Upload button and add one line to the code, as follows:

284

Writing Data

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

If FileUpload1.HasFile Then Try

FileUpload1.SaveAs(“C:\BegASPNET2\Chapters\Begin\Chapter08\MatchImages\” & _ FileUpload1.FileName)

Catch ex As Exception

FileUploadReport.Text = “Failed because: <br/>” & ex.Message End Try

FileUploadReport.Text = “File uploaded to WroxUnited from: <br/>” & _ FileUpload1.PostedFile.FileName

SqlDataSource2.Insert() Else

FileUploadReport.Text = “Please select a file before clicking “ & _ “the ‘Upload’ button”

End If End Sub

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

285

Chapter 8

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

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 functionality. 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 the <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.

Summar y

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

286

Writing Data

values. The fields to be included in the dictionary are listed in the DataKeyNames property of the databound 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 perform. 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>.

Keep in mind two caveats when writing data:

First, 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.

Second, 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 necessary, 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 control. 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?

287