11 Updating a Database Table Textbook Chapter 14.

Slides:



Advertisements
Similar presentations
Microsoft® Access® 2010 Training
Advertisements

CC SQL Utilities.
Stored procedures and views You can see definitions for stored procedures and views in the demo databases but you can’t change them. For views, expand.
11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
11 User Controls II Chapter Objectives You will be able to Create a realistic reusable user control. Use data binding in a user control. Change.
11 ASP.NET Controls II Beginning ASP.NET 4.0 in C# 2010 Chapter 6.
Chapter 18 - Data sources and datasets 1 Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Some Introductory Programming 1. Structured Query Language (SQL) - used for queries. - a standard database product. 2. Visual Basic for Applications -
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
Database Updates Made Easy In WebFocus Using SQL And HTML Painter Sept 2011 Lender Processing Services 1.
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
11 ASP.NET Controls Beginning ASP.NET 4.0 in C# 2010 Chapter 6.
Stored Procedures Dr. Ralph D. Westfall May, 2009.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
JavaScript & jQuery the missing manual Chapter 11
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
BIM211 – Visual Programming Database Operations II 1.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
Introduction to Graphical User Interfaces. Objectives * Students should understand what a procedural program is. * Students should understand what an.
Databases in Visual Studio. Database in VisualStudio An MS SQL database are built in Visual studio The Name can be something like ”(localdb)\Projects”
BİL528 – Bilgisayar Programlama II Database Operations II 1.
Navigating database with windows forms.. Tiered applications  Provide a means to develop many presentations of the same app  Makes changes to the back.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
1 Project 4: XML Product Browser (Not Graded). Objectives This project is an exercise of the following knowledge and skills: Accessing and displaying.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
UNIT 9.2: Learning Objectives Agile Development – Bruce Feiler on Agile Programming Database access from code – Database Cycle Review – SQL Command Types.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
1 Working with MS SQL Server Textbook Chapter 14.
Internet Technologies and Web Application Web Services With ASP.NET Tutorial: Introduction to.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with MSSQL Server Code:G0-C# Version: 1.0 Author: Pham Trung Hai CTD.
Programming using C# Joins SQL Injection Stored Procedures
C# Tutorial -1 ASP.NET Web Application with Visual Studio 2005.
CIS 338: Using Queries in Access as a RecordSource Dr. Ralph D. Westfall May, 2011.
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
1 Chapter 12 – Web Applications 12.1 Programming for the Web, Part I 12.2 Programming for the Web, Part II 12.3 Using Databases in Web Programs.
1 Project 3: Chomp (Not graded). 2 Project 3 The game of Chomp was described in a Math Trek column in Science News:
Dynamic Dropdown Lists 1. Objectives You will be able to Use Dropdown Lists to solicit multiple choice user input in an ASPX web page. Populate a Dropdown.
Damian Tamayo Tutorial DTM Data Generator Fall 2008 CIS 764.
Stored Procedure. Objective At the end of the session you will be able to know :  What are Stored Procedures?  Create a Stored Procedure  Execute a.
1 Project 7: Northwind Traders Order Entry. 2 Northwind Order Entry Extend the Select Customer program from Project 6 to permit the user to enter orders.
Neal Stublen Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom.
ASP.NET OPTIMIZATION. Why Optimize? $$$ Whether you build applications for customers or not, enhanced applications save money.
Windows Forms Navigating database with windows forms.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
1 Chapter 20 – Data sources and datasets Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
1 Database Programming with ADO.NET Kashef Mughal.
Using ADO.Net to Build a Login System Dr. Ron Eaglin.
11 ASP.NET Server Controls Beginning ASP.NET in C# and VB Chapter 4.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
1 Project 4 Address Lookup. Project 4 Write an ASP.NET app that permits users to retrieve addresses from a potentially large list of addresses. There.
1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25.
11 User Controls Beginning ASP.NET in C# and VB Chapter 8.
1 Working with MS SQL Server Beginning ASP.NET in C# and VB Chapter 12.
Beginning ASP.NET in C# and VB Chapter 9
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
C# MySQL onnect-C-to-MySQL 1.
ASP.NET Programming with C# and SQL Server First Edition
How to organize and document your classes
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Presentation transcript:

11 Updating a Database Table Textbook Chapter 14

22 Objectives You will be able to Write C# code to update a database table from user input.

3 SQL Injection Attacks Last class we looked briefly at SQL Injection Attacks. General defensive measure: scan for single quotes in user input and replace them by pairs of single quotes. Student Ryan Wheeler informed me of a class of attacks where this measure fails: SQL Smuggling Attacks Described in November 2007

4 SQL Injection Attacks The "ironclad rule" still applies (all the more so): Never splice user input into a command string (in ADO.NET). Use a command parameter instead. Stored procedures are another effective mechanism applicable to most database systems. Permit the use of parameters. But have some vulnerabilites described in the SQL Smuggling paper.

5 Overview for Today We will extend the Address Lookup app from last class to permit the user to update database table entries, delete entries, and add new entries.

6 Getting Started Download the Address Lookup app from last class: Downloads/2012_06_14_In_Class/ Downloads/2012_06_14_In_Class/ Drill down to website folder Rename website folder Address_Update Open VPN connection if necessary. Open website folder, Address_Update, in Visual Studio Open web.config and put your own username, database name, and password into the connection string. Build and run.

7 Default.aspx

8 App in Action

9 Update The user can modify the TextBoxes but there is no way to write the updated entries back to the database. Add an Update button below the table. Initially disabled. Enabled only when something has been changed.

10 Update Button

11 Update Button Event Handler Double click on the Update Button to add an event handler. Fill in a stub.

12 Detect Changes Double click on one of the result TextBoxes. Visual Studio creates an empty event handler for TextChanged.

13 Use Same Event Handler for All TextBoxes Change the name to tbXXX_Text_Changed In Source View add this event handler to all result TextBoxes. Also set AutoPostBack to True Set btnUpdate.Enabled to false in btnLookup_Click event handler.

14 Text Changed Event Handlers Try it!

15 Successful Lookup Update button is disabled. Change any textbox.

16 TextBox Changed What's going on here? Why did the address disappear?

17 TextBox Changed There was a postback as soon as we changed an input. We needed this in order to enable the Update button. The Page_Load event handler cleared all of the Textboxes. We wanted this to that results from a previous lookup would not stay on the page after an unsuccessful lookup.

18 Solution Clear the results in the Lookup button click event handler when the lookup is unsuccessful. Not in Page_Load.

19 New Page_Load

20 New Lookup Button Click Handler Try again.

21 Zip Code Changed Click "Update Database" Modify Zip code.

22 Update Database Clicked

23 Lookup Failure Try entering address data.

24 Zip Code Modified Update Database is enabled!

25 A Flaw

26 A Flaw User should not be able to update the database unless lookup was successful. Results TextBoxes should be disabled if lookup was unsuccessful. Update Database button should also be disabled.

27 Updated Lookup Click Handler

28 Disable_Results_TextBoxes protected void Disable_Results_TextBoxes() { tbLastName.Enabled = false; tbFirstName.Enabled = false; tbAddress1.Enabled = false; tbAddress2.Enabled = false; tbCity.Enabled = false; tbState.Enabled = false; tbZipCode.Enabled = false; }

29 Enable_Results_TextBoxes protected void Enable_Results_TextBoxes() { tbLastName.Enabled = true; tbFirstName.Enabled = true; tbAddress1.Enabled = true; tbAddress2.Enabled = true; tbCity.Enabled = true; tbState.Enabled = true; tbZipCode.Enabled = true; }

30 Another Flaw Previous results should be cleared, and the TextBoxes disabled on TextChanged for the Input TextBox. Need AutoPostBack = True Double click on tbInput to add a TextChanged event handler.

31 tbInput_TextChanged Event Handler protected void tbInput_TextChanged(object sender, EventArgs e) { Clear_Results(); btnUpdate.Enabled = false; Disable_Results_TextBoxes(); } Try it! End of Section

32 Now the Real Work Add code to class Query to update the database. Will need a SQL Update command. Recall the Introduction to ADO.NET. Slide 46

33 Updating Multiple Fields Slide 46

34 A Design Dilemma Class Address knows nothing about SQL or ADO.NET. Class Query knows about SQL and ADO.NET Knows no details about class Address Where should we put the SQL Update function? Has to know details of both class Address and ADO.NET.

35 SQL Update Command Let's put the Update function in class Query. Keep class Address pure. Class Query already depends on class Address. Has function Get_Address. Knows the table name. Knows column Last_Name Add function Update_Address to class Query. Small increase in dependency on class Address.

36 Function Update_Address Pass in an updated Address object. Note that the ID cannot change. Everything else can change. Set up a connection to the database server just as we did for Get_Address. Set up a command object to do the update. Use ID field to specify table row to be updated. Set all other row items to the Address object property values, using command parameters.

37 The Update Function Create a SqlConnection object. Create a SqlCommand object. Set its Connection Property Set its CommandText property to the string for an UPDATE command. Use parameters for all table values. Use Address ID in the "where" clause. Invoke the command object's ExecuteNonquery method. Should affect exactly one row.

38 Function Update_Address public static void Update_Address( Address adr, out string error_msg) { SqlConnection cn = null; error_msg = ""; try { cn = Setup_Connection(); int nr_rows_affected = Perform_Update(cn, adr); if (nr_rows_affected != 1) { error_msg = "ERROR: Nr rows affected was " + nr_rows_affected; }...

39 Function Update_Address (continued)... catch (Exception ex) { error_msg = "ERROR updating table Addresses: " + ex.Message; } finally { if (cn != null) { cn.Close(); }

40 Function Perform_Update private static int Perform_Update(SqlConnection cn, Address adr) { string cmd_str = "UPDATE Addresses " + "SET " + " + " + " + " + " + " + "WHERE ID=" + adr.Id; SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandText = cmd_str;...

41 Function Perform_Update (continued) adr.Last_name); adr.First_name); adr.Address1); adr.Address2); adr.City); adr.State); adr.Zip_code); int nr_rows_affected = cmd.ExecuteNonQuery(); return nr_rows_affected; } Build, but don't run. (We still don't have a call to Update_Address.)

42 The hardest part is done! But we have to pass an updated Address object to function Update_Address from the click event handler for btnUpdate. Where do we get the Address object? Where do we update its values?

43 The Address Object We might save the original Address object in ViewState. Must mark the class as "Serializable" Textbook page 259. We DO NOT have to provide the function to serialize the object. Update it from the TextBoxes when the user clicks the Update Database button.

44 The Address Object We have updated values for all of the properties of the Address object in the results TextBoxes. Everything except the ID. These values are automatically preserved in the ViewState. We could reconstruct the Address object, with the updated values, from the contents of the TextBoxes.

45 The Address Object We need a new constructor for class Address. ID as parameter. Initialize all fields as blank. Use the public properties to set the fields. Preserve just the ID as explicit member of ViewState

46 Class Address New constructor: public Address(int ID) { id = ID; last_name = ""; first_name = ""; address1 = ""; address2 = ""; city = ""; state = ""; zip_code = ""; }

47 Persist ID in ViewState In Default.aspx.cs protected void btnLookup_Click(object sender, EventArgs e) { string error_msg; Address adr = Query.Get_Address(tbInput.Text, out error_msg); if (adr == null) { Clear_Results(); Disable_Results_TextBoxes(); ViewState["ID"] = null; } else { Display_Results(adr); Enable_Results_TextBoxes(); ViewState["ID"] = adr.Id; } lblMessage.Text = error_msg; btnUpdate.Enabled = false; }

48 Button Update Click Handler protected void btnUpdate_Click(object sender, EventArgs e) { string error_msg = ""; int id = (int)ViewState["ID"]; Address adr = new Address(id); // Update the Address object from the TextBoxes. adr.Last_name = tbLastName.Text; adr.First_name = tbFirstName.Text; adr.Address1 = tbAddress1.Text; adr.Address2 = tbAddress2.Text; adr.City = tbCity.Text; adr.State = tbState.Text; adr.Zip_code = tbZipCode.Text; Query.Update_Address(adr, out error_msg); lblMessage.Text = error_msg; btnUpdate.Enabled = false; } Try it!

49 Successful Lookup Change Zip Code to

50 Zip Code Modified Click Update Database.

51 Check the Database Table

52 Summary We used ViewState to hold the Addess ID across postbacks. All other information for the current Address is automatically preserved in ViewState The user can update any part of the address in a TextBox. When the user asks to update the database we first reconstruct the Address object from the TextBoxes then pass the updated object to a function that updates the database table.

53 Summary Minimal Coupling Class Default is responsible for the user interface. Knows nothing about SQL. Knows the public methods of class Query. Knows the public methods and properties of class Address. Class Query is responsible for SQL operations. Knows the public methods and properties of class Address. Knows nothing about the user interface. Could be used in other apps or PC programs that use table Addresses. Class Address provides an object oriented interface to database table Addresses. Knows nothing about the user interface. Knows how to use a SqlDataReader.