11 Using ADO.NET II Textbook Chapter 14. 2 Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.

Slides:



Advertisements
Similar presentations
11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
Advertisements

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.
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.
J4www/jea Week 3 Version Slide edits: nas1 Format of lecture: Assignment context: CRUD - “update details” JSP models.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Sara SartoliAkbar Siami Namin NSF-SFS workshop July 14-18, 2014.
11 ASP.NET Controls Beginning ASP.NET 4.0 in C# 2010 Chapter 6.
Stored Procedures Dr. Ralph D. Westfall May, 2009.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
JavaScript & jQuery the missing manual Chapter 11
SQL Azure Database Windows Azure SQL Database is a feature-rich, fully managed relational database service that offers a highly productive experience,
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.
11 Updating a Database Table Textbook Chapter 14.
Chapter 15: Using LINQ to Access Data in C# Programs.
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.
PHP meets MySQL.
1 Working with Menus and Dialog Boxes. 2 Objectives You will be able to Create and edit menus for Windows Forms applications. Write code to handle menu.
CIS 375—Web App Dev II ASP.NET 10 Database 2. 2 Introduction to Server-Side Data Server-side data access is unique in that Web pages are basically ___________.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
Attacking Applications: SQL Injection & Buffer Overflows.
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.
Internet Technologies and Web Application Web Services With ASP.NET Tutorial: Introduction to.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
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.
ASP.NET The Clock Project. The ASP.NET Clock Project The ASP.NET Clock Project is the topic of Chapter 23. By completing the clock project, you will learn.
Analysis of SQL injection prevention using a filtering proxy server By: David Rowe Supervisor: Barry Irwin.
Module 7: Accessing Data by Using ADO.NET
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.
Neal Stublen Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom.
Security Attacks CS 795. Buffer Overflow Problem Buffer overflows can be triggered by inputs that are designed to execute code, or alter the way the program.
Object Oriented Software Development 10. Persistent Storage.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
DAT356 Hackers Paradise SQL Injection Attacks Doug Seven, Microsoft MVP Cofounder of SqlJunkies.com
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Adding Parameters to Commands ADO.NET - Lesson 06  Training time: 15 minutes.
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.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
Security Attacks CS 795. Buffer Overflow Problem Buffer overflow Analysis of Buffer Overflow Attacks.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
HNDIT Rapid Application Development
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
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.
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.
Beginning ASP.NET in C# and VB Chapter 9
1 Project 5 Eyeglass Rx User Control. Eyeglass Rx Earlier in the semester we looked at an eyeglass prescription as an example of an HTML table. 2.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
 ADO.NET is an object-oriented set of libraries that allows you to interact with data sources  Commonly, the data source is a database, but it could.
ASP.NET Programming with C# and SQL Server First Edition
ADO.NET Fundamentals.
PROG Advanced Web Apps 5/23/2018 Notes on ADO.NET (1) Wendi Jollymore, ACES.
How to Create Login Form using vb.net and SqlServer Database
SQL commands from C# and ASP.net
ISC440: Web Programming 2 Server-side Scripting PHP 3
An Introduction to Entity Framework
Web DB Programming: PHP
Lecture 2 - SQL Injection
PROG Advanced Web Apps 4/13/2019 Programming Data Pages Wendi Jollymore, ACES.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
ADO.NET Fundamentals.
Presentation transcript:

11 Using ADO.NET II Textbook Chapter 14

2 Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses database table: Permit user to look up addresses by last name. TextBox for user input. Do query for address having that last name. Display results or "Not Found" message.

3 Getting Started Download a slightly improved version of the example as of the end of last class: _06_12_In_Class/ _06_12_In_Class/ I have added the rest of the output controls and put all output controls into a table so that they are aligned. Open website in Visual Studio Drill down to the real website folder! Or extract it from the enclosing folder(s) Build and run.

4 Connection String Function Setup_Connection will require a connection string. Rather than hard coding the connection string in your C# code, it is good practice to put it into web.config. web.config can be edited without needing to modify the app code..NET provides a convenient way to retrieve connection strings from the config file. The WebConfigurationManager class

5 <add name="AddressTable" connectionString="server=scorpius.eng.usf.edu; Initial Catalog=wpusr40; User=wpusr40; Password=xxxxx"/> Connection String in web.config

6 private static SqlConnection Setup_Connection() { String connection_string = WebConfigurationManager.ConnectionStrings["AddressTable"].ConnectionString; SqlConnection cn = new SqlConnection(connection_string); cn.Open(); return cn; } Setup_Connection() Name in web.config WebConfigurationManger requires "using System.Web.Configuration;"

7 Get_Reader() private static SqlDataReader Get_Reader(string last_name, SqlConnection cn) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM Addresses " + "WHERE Last_Name='" + last_name + "'"; cmd.Connection = cn; return cmd.ExecuteReader(); } CAUTION Splicing a command string together like this is NOT good practice. A little later we will see why and what to do instead.

8 Using the Query Result The SqlDataReader object is similar to a C# StreamReader (or C++ ifstream): An object that we can use to get the query results Read() method makes next line available. Returns true if successful. We can then access items in the current line using the column name as an indexer. Example: rdr["Last_Name"]

9 Class Address Class Address is responsible for knowledge of the structure of the database table. Column names only. No knowledge of how to do a query. Let it extract the individual items from the query result. Pass the SqlDataReader object to the constructor. Constructor initializes Address object with query results.

10 Class Address Constructor using System.Data.SqlClient;... public Address(SqlDataReader rdr) { id = (int) rdr["ID"]; last_name = (string) rdr["Last_Name"]; first_name = (string) rdr["First_Name"]; address1 = (string) rdr["Address1"]; address2 = (string) rdr["Address2"]; city = (string) rdr["City"]; state = (string) rdr["State"]; zip_code = (string) rdr["Zip_Code"]; } Use column name as indexer value for the SqlDataReader. Typecast the result as the appropriate C# type.

Process the Query Results public static Address Get_Address( string last_name, out string error_msg) { SqlDataReader rdr = null; SqlConnection cn = null; Address adr = null; error_msg = ""; try { cn = Setup_Connection(); rdr = Get_Reader(last_name, cn); if (rdr.Read()) { adr = new Address(rdr); } else { error_msg = "Lookup failed"; }... return adr; }

12 Real Event Handler protected void btnLookup_Click(object sender, EventArgs e) { string error_msg; Address adr = Query.Get_Address(tbInput.Text, out error_msg); if (adr != null) { Display_Results(adr); } lblMessage.Text = error_msg; } Replace the stub in Default.aspx.cs.

13 Display_Results() protected void Display_Results(Address adr) { tbLastName.Text = adr.Last_name; tbFirstName.Text = adr.First_name; tbAddress1.Text = adr.Address1; tbAddress2.Text = adr.Address2; tbCity.Text = adr.City; tbState.Text = adr.State; tbZipCode.Text = adr.Zip_code; } Build and run.

14 Initial Page Enter a name and click Lookup Address.

15 Successful Lookup Try an unsuccessful lookup.

16 Unsuccessful Lookup Previous results not cleared.

17 Clear Previous Results Default.aspx.cs protected void Page_Load(object sender, EventArgs e) { lblMessage.Text = ""; tbLastName.Text = ""; tbFirstName.Text = ""; tbAddress1.Text = ""; tbAddress2.Text = ""; tbCity.Text = ""; tbState.Text = ""; tbZipCode.Text = ""; } Try unsuccessful lookup following a successful lookup again.

18 A Serious Problem Look up last name O'Brian.

19 A Serious Problem This is the reason you should not build a command string by splicing in user input. An apostrophe (single quote) in the user input terminates the last name string, leaving the rest of the input to be interpreted as more command. Syntax error in this case. Also makes the app vulnerable to a SQL Injection Attack.

20 SQL Injection Attack A hacker can concatenate his own SQL command after an apostrophe in user input. Potentially execute any SQL command. Can take over your database. Destroy your data. Worse, steal it without your knowing.

21 Defensive Measures One defensive measure is to validate the user input. Only accept expected inputs. Scan for single quotes in user input and replace them with two single quotes. The SQL Server treats two consecutive single quotes as an escape sequence. Puts one single quote into the command. Does not terminate the string. These defensive measures apply to any SQL server.

22 Parmeterized Commands ADO.NET provides a better solution: Parameterized Commands Rather than splicing together strings, include parameters in the command string. Placeholders to be filled in at run time. Set parameter values from user input. Strings as parameter values are not enclosed in single quotes. Will not terminate a string even if they contain single quotes.

23 Parmeterized Commands symbol in front of a word in a command string in a SqlCommand object's CommandText property identifies the word as a parameter. This only applies to ADO.NET. It is not part of the SQL language. Parameter value must be supplied to the SqlCommand object before the command is executed.

24 A Parameterized Command private static SqlDataReader Get_Reader(string last_name, SqlConnection cn) { SqlCommand cmd = new SqlCommand(); //cmd.CommandText = "SELECT * FROM Addresses " + // "WHERE Last_Name='" + last_name + "'"; cmd.CommandText = "SELECT * FROM Addresses " + "WHERE last_name); cmd.Connection = cn; return cmd.ExecuteReader(); }

25 Successful Lookup

26 Input Containing an Apostrophe

27 An Ironclad Rule Never splice user input into a command string. Use a command parameter instead.

28 Loose Ends What if there are multiple rows with the same last name?

29 Summary Apply the principles of OOD to web apps. Let the Page class be just user interface. Entity class for contents of a database table. Collect query code in a static class. Classes from ADO.NET provide easy access to a database table. SqlConnection SqlCommand SqlDataReader Use parameterized commands rather than splicing user input into command strings. End of Presentation