+ All Categories
Home > Documents > mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe...

mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe...

Date post: 25-Mar-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
27
Lab 6 – CS 3340, Spring 2016 Lab Objectives: 1. Be able to describe what these are: database, table, row, record, column, field, AutoNumber. 2. Configure a DataSource object. 3. Use the Query Builder. 4. Bind a DataSource to a GridView 5. Use Connection, Command, and DataReader objects to connect to a database manually 6. Copy a web form 7. Connect to an Access database 8. Configuring your database application so that it will work on Lucius There are 7 stages to complete Lab 6. Stag e Description 0 Database Primer 1 Create Lab 6 Home Page 2 Becoming One with the DataSource 3 Binding Data to the GridView 4 Manual Database 5 Copying a Page 6 Working with an Access DB 7 Wrapping Up and Posting to Lucius Follow the directions below to complete the lab. The completed Lab should work like this: https://lucius.valdosta.edu/dgibson/labs/lab6_sp15/Default.aspx 1
Transcript
Page 1: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

Lab 6 – CS 3340, Spring 2016

Lab Objectives:

1. Be able to describe what these are: database, table, row, record, column, field, AutoNumber.2. Configure a DataSource object.3. Use the Query Builder.4. Bind a DataSource to a GridView5. Use Connection, Command, and DataReader objects to connect to a database manually6. Copy a web form7. Connect to an Access database8. Configuring your database application so that it will work on Lucius

There are 7 stages to complete Lab 6.

Stage Description0 Database Primer1 Create Lab 6 Home Page2 Becoming One with the DataSource3 Binding Data to the GridView4 Manual Database5 Copying a Page6 Working with an Access DB7 Wrapping Up and Posting to Lucius

Follow the directions below to complete the lab. The completed Lab should work like this:

https://lucius.valdosta.edu/dgibson/labs/lab6_sp15/Default.aspx

1

Page 2: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

Stage 0 – Database Primer

This stage is will briefly explain what a database is, terminology, and explore one.

1. Download players.zip from the Schedule, unzip anywhere and you will find players.mdb, the Players database in MS Access format. To do the following steps, you will need MS Access installed on your computer. It is on the lab machines. It may be on Dreamspark.

2. Do the following:

a. Double-click players.mdb to open.

b. As shown on the right, double-click the Players table to open it.

3. A database is a set of (usually) related tables that store information about something of interest. For example, below we have the Players Table as shown below and what is open in Access. Note the following:

a. A database table is organized as rows and columns. Each row (record) represents data about a player. Each column (field) is an attribute about a player. For instance, we see familiar fields: LName and FName the represent the last name and first name of a player.

b. The PNumber field is poorly named. It stands for player number, but would be clearer with the name JerseyNum.

c. Every database table we consider will have a Primary Key field. The value of this field for any row is unique and thus uniquely identifies the row. This is very important and we will discuss this in class along with the Foreign Key.

Figure 1 – Players Table

2

Page 3: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

4. We can obtain more information on the fields, such as data type. Do the following:

a. Choose: View, Design View b. As shown below, the PlayerID field is of type AutoNumber. This datatype means that we will never supply a value for this field; Access will automatically assign a unique value. We will discuss this in class. Select some of the other fields and see their Field Properties.

c. Choose: View, Datasheet View to return to displaying the data.

5. We will add a row (Player) to the Players table to see how the PlayerID field is “automatically” (e.g. AutoNumber) filled. Do the following:

a. Scroll to the bottom of Players table, click in the TeamID field, type the value: 2.

b. Note that the PlayerID value is automatically supplied. Add values for the rest of the fields.

c. Change some field values in a row. Try to supply bad data. For example, type “a” for PNumber.

d. Delete a row.

3

Page 4: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

6. A convenient way to show all the tables and fields in a database is to display a relationship diagram.

a. Choose: Database Tools, Relationships b. You will see a diagram of the tables in this database. You will probably need to stretch them to make the look as below. We will discuss the link between the Players table and the Teams table in class. For homework and tests I will give you a diagram like this so that you will know how the database is organized.

c. We are done with this stage. You can close Access if you want. I find it convenient to leave it open when I am working with database programming as we will do in the next stage.

Stage 1 – Create Lab 6 Home Page

1. Log on to a campus machine . For this lab you will need to be logged on to a campus machine with your Active Directory credentials. Otherwise, you cannot access the database server, narcissa.

2. Create a Web Site named Lab6 .

a. Create Lab6 folder on a flash (or hard) drive. b. Open VS and choose: File, New Website, navigate to Lab6 folder.

3. Add a Web Form.

a. Add a web form named: Default.aspx

b. Add the HTML title: “Lab 6 – FirstName LastName”, substituting your name.

c. Add a level 2 header that reads: “Lab 6 – FirstName LastName”, substituting your name.

You might choose to do the next two steps (d and e) at the very end when you have posted to Lucius.

d. Make the text “FirstName LastName” a link to your course homepage.

e. Open your course home page. Add the text, “Lab 6” to the page and make it a link to your Lab 6 home page.

f. Add a multi-line TextBox and provide the ID: txtMsg.

4

Page 5: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

Stage 2 – Becoming One with the DataSource

Data-bound controls display data that is bound to a relational database, XML, or an object. They can be used to retrieve, insert, update, and delete data from the underlying source. Here, we will consider the SqlDataSource which can be used to connect to a MS SQL Server database.

4. Open the Toolbox, choose the Data tab, and add SqlDataSource to your page as shown on the right:

5. From the Flyout menu, choose: Configure Data Source, and then New Connection

a. Note the “Data source”b. Supply the Server name,

“narcissa.valdosta.edu”c. Make sure “Use Windows

Authentication” is selected.d. Use the drop down to select your

database (e.g. yourID)e. Test the connectionf. Choose OK.

5

Page 6: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

6. Choose Next.

7. Note the name of your connection string. It will probably be: yourIDConnectionString. You will need to type this value in a later step.

8. Choose the data to access.

a. Make sure Specify columns… is selected.b. Select the Players table from the drop down.c. Note the fields (columns) available in the table. The

“*” is selected which means that all fields are chosen.d. Note the SQL statement. This is the statement that

will be issued to the database server. In this case it instructs that database server to return all rows and columns from the Players table.

9. Choose Next and then Test Query. You should see the data displayed. Choose Finish.

10. Open Web.config. Note the items shown below.

11. Display your page in Source mode. Note the ConnectionString and SelectCommand. The ConnectionString value is read from Web.config.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dgibsonConnectionString %>" SelectCommand="SELECT * FROM [Players]"> </asp:SqlDataSource>

6

Page 7: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

12. Display your page (Default.aspx) in Design model. Select the data source and view the Properties Window. Note the items show below. You will need the ID value later so make a mental note of it – it is probably named SqlDataSource1 as shown below.

13. Expand the SelectQuery choice.

7

Page 8: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

14. Choose Query Builder… This is a very useful tool to build more complex queries. Inspect the items there and then choose Cancel and then Cancel again.

Stage 3 – Binding Data to the GridView

GridView is a data-bound control that displays data from a data source in a table.

15. Drag a GridView control from the Data tab in the ToolBox onto your page between the header and the TextBox.

16. Choose the data source that you created earlier (probably named SqlDataSource1)

8

Page 9: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

17. The display should look like as shown on the right. Note that the field names for the Players table are now displayed

18. Build and run your application (Ctrl+Shift B, Ctrl+F5). The resulting page should look as shown below (the data may be different).

19. Open your page in Source view. Identify the GridView and note it’s structure. Find the following attributes in the markup shown on your page and note the definitions:

ID – the name of this instance of the GridView DataKeyNames – the key field in the database table.

This will be discussed in class. DataSourceID – the ID of the data source Columns – the GridView has a collection of columns BoundField – the type of column (we will study other

types later). Used to bind a field in the database to this field in the GridView

DataField – The name of the field in the database that is being bound

9

Page 10: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

Stage 4 – Manual Database

The approach we used in the Stages 2 and 3 is very easy to do. I call this the Wizard approach as we used wizards to do all the work. Sometimes this approach is sufficient. However, sometimes we need to have more control over the configuration, or the ability to directly touch the data with code. I call this the manual approach. In this stage we will work with the same Players table; however, we will not use the DataSource. Instead, we will use classes from the .NET API to connect to the database and read data manually.

20. Set-Up New Page – Do the following:

a. Create a new web form named: Page2.aspx

b. Add a link from your Lab 6 homepage (Default.aspx) to this new page as shown on the right.

c. Return to Page2.aspx in Design mode. Add a Button with ID set to: btnReadData as shown on the right.

d. Add a multiline TextBox with ID set to: txtMsg as shown on the right.

21. Create Event-Handler for Button – Do the following:

a. Double-click the button to create the event-handler stub.

b. Study the code below and then add it to the event-handler.

// Create connection objectIDbConnection con = new SqlConnection();// Create command objectIDbCommand cmd = new SqlCommand();

// Get connection string from web.config. Change the name of the connection string!!!string conn = ConfigurationManager.ConnectionStrings["dgibsonConnectionString"].ConnectionString;

// Attach connection string to connection object.con.ConnectionString = conn;

// Attach the connection object to the command object cmd.Connection = con;

// Display information about the connection.txtMsg.Text = "***Connection String: \n" + con.ConnectionString + "\n";txtMsg.Text += "***Connection State: " + con.State + "\n\n";

c. Change the connection string (highlighted in yellow) to the value used in step 7 above. It will probably be: yourIDConnectionString.

10

Page 11: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

22. There will be several compile errors highlighted with the red squiggly line. As shown on the right, right-click each one, choose: Resolve and then add the using statement (choose the first item in all cases).

When complete you will have added the using statements shown below at the top of your file. Verify that you see them there.

using System.Configuration;using System.Data;using System.Data.SqlClient;

23. Build and run your application (Ctrl+Shift B, Ctrl+F5). The resulting page should look as shown on the right. Of course the connection is Closed as we have not opened it yet. This is just to show you that that we can query the state of the connection as shown in the code above: con.State.

24. Set the SQL Statement – We will write code to build a SQL statement that will be used later to read data from the database. Study the code below and then add it at the end of the button click event:

// Build sql string String sql = "SELECT " + "Players.PlayerID, " + "Players.TeamID, " + "Players.LName, " + "Players.FName, " + "Players.PNumber, " + "Players.BDate " + "FROM" + "Players " + "ORDER BY " + "Players.LName Asc, " + "Players.FName Asc";

// Add sql to command object cmd.CommandText = sql;

// Display SQL statement. Very useful debugging technique. txtMsg.Text += "***CommandText: " + cmd.CommandText + "\n\n";

11

Page 12: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

25. Build and Run (Ctrl+Shift B, Ctrl+F5). Do the following:

a. The SQL statement will be displayed in the TextBox towards the bottom where it says, “***CommandText” as shown on the right. Find it now and study the SQL statement.

b. The SQL statement is incorrect. It has a small error. Try to find it now. Inspect the statement carefully. Ask for a hint if you don’t see the problem.

c. When you find the error, fix it.

26. Open Connection to Database – Study the code below and then add it to the end of the code in the button click event.

try { // Open the connection. cmd.Connection.Open(); txtMsg.Text += "***Connection state: " + cmd.Connection.State + "\n\n"; } catch (Exception ex) { txtMsg.Text += ex.ToString(); }

27. Build and Run (Ctrl+Shift B, Ctrl+F5). Verify that the Connection state is “Open” as shown on the right.

28. Create the DataReader – Add the lines below to the end of the code inside the try block (as shown on the right):

// Read the data and put the results in data reader.IDataReader dr = cmd.ExecuteReader();txtMsg.Text += "***DataReader.IsClosed: " + dr.IsClosed + "\n\n";

29. Build and Run (Ctrl+Shift B, Ctrl+F5). Verify that the DataReader. IsClosed is “False” as shown on the right. This means it is ready to have data extracted from it.

12

Page 13: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

30. Extract the Data from the DataReader – Study the code below and then add it to the end of the code inside the try block (just below the lines from the previous step) as shown on the right.

// Read the data from the data reader. // Note that this is one-pass, forward only. while (dr.Read()) { // Read the data. Must specify the data type you

// are reading (e.g. GetInt32) and the position // in the reader: 0, 1, etc. Note that this order

// is the same as the order in the SQL statement. int pID = dr.GetInt32(0); int tID = dr.GetInt32(1); string lName = dr.GetString(2); string fName = dr.GetString(3); int jerNum = dr.GetInt32(4); DateTime bDate = dr.GetDateTime(5);

// Do something with the data, i.e. put it in a textbox. txtMsg.Text += pID + " " + tID + " " + lName + " " + fName + " " + jerNum + " " + bDate.ToShortDateString() + "\n"; }

// Close data reader and connection dr.Close(); cmd.Connection.Close(); txtMsg.Text += "***DataReader.IsClosed: " + dr.IsClosed + "\n\n"; txtMsg.Text += "***Connection state: " + cmd.Connection.State + "\n\n";

31. Build and Run (Ctrl+Shift B, Ctrl+F5). Verify (as shown on the right):

a. The data is displayed. (If you don’t see the data displayed as shown below and you see lots of error messages, that means your SQL is still wrong. If so, scroll up in the TextBox, find where the SQL statement is being displayed and find and fix the error.)

b. At the end, the DataReader.IsClosed is “True”

c. The Connection state is “Closed”.

32. Review – Review your button click code and verify the algorithm below for obtaining data from a database.

1. Create a Connection and a Command Object.2. Retrieve the connection string from Web.config.3. Put the connection string in the Connection object.4. Put the connection object in the Command object.5. Build SQL string and put in Command object.6. Open the connection.7. Create a DataReader object from the Command object (e.g. read the data into a data reader)

13

Page 14: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

8. Loop through the DataReader object and extract the data. (e.g. extract data from data reader)9. Close the DataReader and Connection.

Stage 5 – Copying a Page

Sometimes you will want to copy a page so that you can experiment on the copy while preserving the original. Or, you may just want to use a copy of the original to jump start the process of building a new page. We detail this simple task of copying a page because it can be a bit confusing if you look under hood.

33. Copy a Page

a. Close Page2.aspx.

b. Select Page2.aspx in the SE and copy (Ctrl+c).

c. Select the Lab6 node in the SE and paste (Ctrl+v).

d. Select the file name Page2-copy.aspx in the SE and rename it Page3.aspx.

e. Open the code-behind file for Page3 as shown on the right. Note the name of the (partial) class: Page2. This is the same name for the code-behind file for Page2. However, this is actually OK. No action needs to take place (in previous versions of VS you needed to manually rename several things).

How does ASP.NET differentiate the two? First, they are in different files, Page2.aspx.cs and Page3.aspx.cs. Second, the Page directive in the Source (Page3.aspx) specifies the file (Page3.aspx.cs) and the class (Page2) as shown below:

34. Add a link from your Lab 6 homepage (Default.aspx) to this new page (Page3.aspx) as shown on the right.

14

Page 15: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

Stage 6 – Working with an Access DB

This stage will show how to work with a MS Access database. We will implement exactly the same functionality we provided in Page2, in Page3 using an Access database instead of the SQL Server database on Narcissa. Note that each version of the database has the same tables; however, the data will probably be different, maybe just a little.

35. Put Access Database in Solution – Do the following (noting the figure on the right below):

a. Right-click the Lab6 node in the Solution Explorer and choose: Add, Add ASP.NET Folder, App_Data

b. Download players.zip and unzip anywhere. It contains a single file, players.mdb, the Players database.

c. Drag the Players database into the App_Data folder.

36. Change Code to Use Access – Do the following:

a. Open Web.config

b. Find the connection string we added earlier for SQL Server. Add the new one below for Access, either above or below the existing one.

<add name="ConnectionStringAccessPlayersDB" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;

Data Source=|DataDirectory|\players.mdb" providerName="System.Data.OleDb" />

c. Open the code-behind file for Page3 and scroll to the beginning of the Button’s click event. Replace:

IDbConnection con = new SqlConnection();IDbCommand cmd = new SqlCommand();

with

IDbConnection con = new OleDbConnection();IDbCommand cmd = new OleDbCommand();

d. The two new classes show a compile error. Right-click one of them and choose: Resolve, using System.Data.OleDb. Tis will add the using statement: using System.Data.OleDb;

e. Find this line of code immediately below the previous two:

string conn = ConfigurationManager.ConnectionStrings["yourIDConnectionString"] .ConnectionString;

Replace the connection string key (highlighted in yellow above) with the name from step b above:

ConnectionStringAccessPlayersDB

37. Build and Run (Ctrl+Shift B, Ctrl+F5). Verify that the Read button displays the data from the Access database.

15

Page 16: mypages.valdosta.edu · Web viewLab 6 – CS 3340, Spring 2016. Lab Objectives: Be able to describe what these are: database, table, row, record, column, field, AutoNumber. Configure

Stage 7 – Wrapping Up and Posting to Lucius

We will have to add a statement to Web.config so that your code on Lucius can access the database on Narcissa.

38. Open Web.config and add the node below to a position inside the <system.web> node:

<identity impersonate="true" userName="vsu\YOUR_ID" password="YOUR_PASWORD” />

When complete, you <system.web> node will look like this:

<system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <identity userName="vsu\YOUR_ID" password="YOUR_PASSWORD"/> </system.web>

Obviously you want to protect your password. You may choose to do this step once you get your pages uploaded to Lucius. Web.config is not available from the internet so it is safe. Also, you may want to put this statement in the Web.config for your whole site (the one that sits in your root folder). That way you will not need to do this step in future assignments.

Why is this statement needed? When you are running your page off localhost, when the page attempts to access the database, the system passes through your login credentials (your AD id and password) to SQL Server. When your page is live and accessed anonymously over the internet there are no credentials to pass through. Thus, you must add this statement to your web.config to impersonate your credentials:

39. Upload to Lucius

a. RDP to Lucius.b. Copy your local Lab6 folder to your root folder on Lucius (c:\students\yourID).c. Copy your App_Data folder in the Lab6 folder to your root folder on Lucius.

40. Test – Open a browser NOT on Lucius and pull up your page (https://lucius.valdosta.edu/yourID/lab6). Test thoroughly. If there is an error, open a browser ON Lucius and pull up your page (https://lucius.valdosta.edu/yourID/lab6).

41. Check links before stopping!

a. Do you have a link (that works) from your course home page to the home page for Lab 6?b. Do you have a link (that works) from your home page for Lab 6 to your course home page?c. Do you have links (that work) from your Lab 6 homepage to Page2 and Page3?

Log off LuciusYou’re done!

16


Recommended