Chapter 10 ASP.NET Security


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Chapter 10 ASP.NET Security

  1. 1. Chapter 12 ADO.NET Yingcai Xiao
  2. 2. Introduction to Database
  3. 3. <ul><li>Computer Science: the science of data processing using a computational device. </li></ul><ul><li>Database (DB) : a persistent store of data in a compact, secure, easy-and-fast-to-retrieve form. </li></ul><ul><li>Database Engine: a software program that creates and manages databases. (e.g. MS Jet Engine) </li></ul><ul><li>Database Management System (DBMS): a database engine plus user interfaces and other supporting software. </li></ul><ul><li>DBMS Examples: Oracle, DB2 (IBM), Sybase, Informix, Microsoft SQL Server, Microsoft Access, MySQL (public domain), … </li></ul><ul><li>Database Server : a DBMS that provides data to its remote clients. </li></ul>. Definitions
  4. 4. Definitions Cont. <ul><li>Database API: application programming interface to DBMSs. </li></ul><ul><li>Database Table: data are stored in a database as “tables”. Each row of a table is called a record, each column of a table is called an attribute. </li></ul>PhoneBook (Database Table Name) <ul><li>Database schema: meta data for databases, defining tables and their attributes. </li></ul>… … … … 330-168-7777 330-777-7777 330-972-7777 John 330-168-8888 330-888-8888 330-972-5809 Tom Cell Home Office Name
  5. 5. SQL <ul><li>SQL: Structured Query Language, a standardized language for accessing and manipulating databases. </li></ul><ul><li>The Select-From-Where Clause: </li></ul><ul><li>Select Office From PhoneBook Where Name=’Tom’; </li></ul><ul><li>Select * From PhoneBook; </li></ul><ul><li>Three Parts of SQL: </li></ul><ul><ul><li>Query: data retrieval </li></ul></ul><ul><ul><li>DML - Data Manipulation Language: inserting, deleting, updating, … </li></ul></ul><ul><ul><li>DDL - Data Definition Language: table creation, alteration and drop. </li></ul></ul>
  6. 6. SQL Example <ul><li>CREATE DATABASE pubs; </li></ul><ul><li>USE pubs; </li></ul><ul><li>CREATE TABLE authors </li></ul><ul><li>( </li></ul><ul><li>au_id varchar(11) NOT NULL, </li></ul><ul><li>au_lname varchar(40) NOT NULL, </li></ul><ul><li>au_fname varchar(20) NOT NULL, </li></ul><ul><li>phone char(12) NOT NULL DEFAULT 'UNKNOWN', </li></ul><ul><li>address varchar(40) NULL, </li></ul><ul><li>city varchar(20) NULL, </li></ul><ul><li>state char(2) NULL, </li></ul><ul><li>zip char(5) NULL, </li></ul><ul><li>contract bit NOT NULL, </li></ul><ul><li>PRIMARY KEY(au_id) </li></ul><ul><li>); </li></ul>
  7. 7. SQL Example <ul><li>insert authors </li></ul><ul><li>values('409-56-7008', 'Bennet', 'Abraham', '415 658-9932', </li></ul><ul><li>'6223 Bateman St.', 'Berkeley', 'CA', '94705', 1); </li></ul><ul><li>insert authors </li></ul><ul><li>values('213-46-8915', 'Green', 'Marjorie', '415 986-7020', </li></ul><ul><li>'309 63rd St. #411', 'Oakland', 'CA', '94618', 1); </li></ul>
  8. 8. DBMS Example: SQL Server <ul><li>By Microsoft </li></ul><ul><li>Needs runtime license </li></ul><ul><li>Best fit for .NET </li></ul><ul><li>Features </li></ul><ul><li> </li></ul><ul><li>Free version: SQL Server Express </li></ul><ul><li> </li></ul><ul><li>Available in MSDNAA. </li></ul>
  9. 9. DBMS Example: MySQL <ul><li>By MySQL AB (part of Sun after 1/16/08) </li></ul><ul><li>Free: </li></ul><ul><li>No need of runtime license </li></ul><ul><li>Not the best fit for .NET </li></ul><ul><li>Installed on all lab PCs. </li></ul><ul><li>How to install it at home: </li></ul><ul><ul><li> </li></ul></ul>
  10. 10. Database Programming
  11. 11. Architecture of a Three-Tier Application DBMS / Database Server Database User Interface Database Engine Supporting Software Application Server Database API Application Logic App User Interface C L I E N T Architecture of a Three-Tier Application
  12. 12. Architecture of a Four-Tier Application DBMS / Database Server Database User Interface Database Engine Supporting Software Application Server Database API Application Logic App User Interface WEB S E R V E R Architecture of a Four-Tier Application WEB C L I E N T
  13. 13. ADO .NET <ul><li>ADO.NET is the database API for managed applications (application servers) to talk to database servers (DBMS: Database Management Systems). </li></ul><ul><li>a database API for managed applications; </li></ul><ul><li>a set of classes in .NET FCL System.Data namespace; </li></ul><ul><li>designed to work over the Web; </li></ul><ul><li>integrates effortlessly with XML; </li></ul><ul><li>maps very well to stateless, text-based protocol HTTP; </li></ul><ul><li>accesses databases through modules known as data providers ( a set of APIs that make the accesses easy to program). </li></ul>
  14. 14. <ul><li>The SQL Server .NET provider </li></ul><ul><ul><li>interfaces to Microsoft SQL Server (7.0 or later) </li></ul></ul><ul><ul><li>all managed code </li></ul></ul><ul><ul><li>code runs faster </li></ul></ul><ul><ul><li>code not portable to other databases </li></ul></ul><ul><li>The OLE DB .NET provider </li></ul><ul><ul><li>OLE: Object Linking and Imbedding </li></ul></ul><ul><ul><li>interfaces to databases through unmanaged OLE DB providers: SQLOLEDB for SQL Server (6.5 or earlier), MSDAORA for Oracle and Microsoft, Jet.OLEDB.4.0 for Microsoft Jet database engine. </li></ul></ul><ul><ul><li>code runs slower </li></ul></ul><ul><ul><li>code portable to other databases </li></ul></ul>Two Data Providers
  15. 15. The System.Data.SqlClient and System.Data.OleDb Namespaces <ul><li>Classes in System.Data.SqlClient are for SQL Server .NET </li></ul><ul><li>using System.Data.SqlClient; </li></ul><ul><li>SqlConnection conn = new SqlConnection </li></ul><ul><li>(&quot;server=localhost;database=pubs;uid=sa;pwd=&quot;); </li></ul><ul><li>try { conn.Open (); </li></ul><ul><li>SqlCommand cmd = new SqlCommand (&quot;select * from titles&quot;, conn); </li></ul><ul><li>SqlDataReader reader = cmd.ExecuteReader (); </li></ul><ul><li>while (reader.Read ()) Console.WriteLine (reader[&quot;title&quot;]); </li></ul><ul><li>} catch (SqlException ex) { </li></ul><ul><li>Console.WriteLine (ex.Message); </li></ul><ul><li>} finally { conn.Close (); } </li></ul>
  16. 16. The System.Data.SqlClient and System.Data.OleDb Namespaces <ul><li>Classes in System.Data.OleDb are for OLE DB .NET </li></ul><ul><li>using System.Data.OleDb; </li></ul><ul><li>OleDbConnection conn = new OleDbConnection(&quot;provider=sqloledb;server=localhost;database=pubs;uid=sa;pwd=&quot;); </li></ul><ul><li>try { conn.Open (); </li></ul><ul><li>OleDbCommand cmd = </li></ul><ul><li>new OleDbCommand (&quot;select * from titles&quot;, conn); </li></ul><ul><li>OleDbDataReader reader = cmd.ExecuteReader (); </li></ul><ul><li>while (reader.Read ()) Console.WriteLine (reader[&quot;title&quot;]); </li></ul><ul><li>} catch (OleDbException ex) { </li></ul><ul><li>Console.WriteLine (ex.Message); </li></ul><ul><li>} finally { conn.Close (); } </li></ul>
  17. 17. Pattern of database programming <ul><li>Create a connection object. </li></ul><ul><li>Open the connection. </li></ul><ul><li>Create a command object. </li></ul><ul><li>Execute the command. </li></ul><ul><li>Access the data. </li></ul><ul><li>Close the connection. </li></ul>
  18. 18. Connections, Commands, and DataReaders <ul><li>Connection objects represent physical connections to a database. </li></ul><ul><li>SqlConnection or OleDbConnection </li></ul><ul><li>Command objects represent the commands performed on a database. </li></ul><ul><li>SqlCommand or OleDbCommand </li></ul><ul><li>DataReader objects represent the data obtained by the commands. </li></ul><ul><li>SqlDataReader or OleDbDataReader </li></ul>
  19. 19. Connection Objects <ul><li>The SqlConnection Class </li></ul><ul><li>The ConnectionString </li></ul><ul><li>SqlConnection conn = new SqlConnection (); </li></ul><ul><li>conn.ConnectionString = </li></ul><ul><li>&quot;server=localhost;database=pubs;uid=sa;pwd=&quot;; </li></ul><ul><li>or </li></ul><ul><li>SqlConnection conn = new SqlConnection </li></ul><ul><li>(&quot;server=localhost;database=pubs;uid=sa;pwd=&quot;); </li></ul><ul><li>Errors in the connection string only throws exceptions at runtime. </li></ul>
  20. 20. Server <ul><li>Server </li></ul><ul><li>Server=localhost or Server=(local) or Data Source=(local) </li></ul><ul><li>SQL Server permits different instances of servers to be installed on a given machine. </li></ul><ul><li>server=DBSERVER (an database server computer named “DBSERVER” at the CS department of UA) </li></ul><ul><li>server=hawkeyewintellect (an instance of SQL Server named Wintellect on a remote machine named Hawkeye) </li></ul><ul><li>Database or Initial Catalog: database name (e.g. Pubs) </li></ul><ul><li>UID or User ID, Pwd: tempdb, tempdb </li></ul>
  21. 21. <ul><li>Min Pool Size and Max Pool Size , the size of the connection pool (the defaults are 0 and 100) </li></ul><ul><li>Integrated Security : default to false, otherwise uses Windows access tokens for authentication. </li></ul><ul><li>Connect Timeout : how many seconds to wait for a connection to open (default=15). </li></ul><ul><li>SqlConnection conn = new SqlConnection     </li></ul><ul><li>(&quot;server=hawkeyewintellect;database=pubs;uid=sa;pwd=;&quot; +    </li></ul><ul><li>&quot;min pool size=10;max pool size=50;connect timeout=10&quot;); </li></ul>Server
  22. 22. Exceptions and Closing Open Connections <ul><li>Exceptions should never go uncaught, and open connections should always be closed before terminating. (Calling Close on a connection that’s not open isn’t harmful.) </li></ul><ul><li>SqlConnection conn = new SqlConnection </li></ul><ul><li>(&quot;server=localhost;database=pubs;uid=sa;pwd=&quot;); //before try block </li></ul><ul><li>try {conn.Open (); </li></ul><ul><li>// TODO: Use the connection </li></ul><ul><li>} </li></ul><ul><li>catch (SqlException e) { </li></ul><ul><li>Console.WriteLine (e.Message); </li></ul><ul><li>// TODO: Handle the exception </li></ul><ul><li>} </li></ul><ul><li>finally { conn.Close ();} </li></ul>
  23. 23. Command Classes: SqlCommand and OleDbCommand. <ul><ul><li>Encapsulate SQL commands performed on a database. </li></ul></ul><ul><ul><li>Rely on connections established. </li></ul></ul><ul><ul><li>Include methods to execute the commands encapsulated inside. </li></ul></ul><ul><li>Example, delete a record from the Pubs database’s “Titles” table using an SQL DELETE command: </li></ul><ul><li>SqlCommand  cmd = new SqlCommand        </li></ul><ul><li>  (&quot;delete from titles where title_id = 'BU1032'&quot;, conn);     </li></ul><ul><li>cmd.CommandTimeout = 10; // Allow 10 seconds, default 30. </li></ul><ul><li>cmd.ExecuteNonQuery (); // Execute the command </li></ul>
  24. 24. The ExecuteNonQuery Method <ul><li>For executing DML and DDL commands: CREATE, INSERT, UPDATE, DELETE, … </li></ul><ul><li>Not getting any data back. </li></ul><ul><li>Examples: </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;create database MyDatabase&quot;, conn); </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;create table titles …&quot;, conn); </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;insert into titles (title_id, title, type, pubdate) &quot; + </li></ul><ul><li>&quot;values ('JP1001', 'Programming Microsoft .NET', &quot; + </li></ul><ul><li>&quot;'business', 'May 2002')&quot;, conn); </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul>
  25. 25. The ExecuteNonQuery Method <ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;update titles set title_id = 'JP2002' &quot; + </li></ul><ul><li>&quot;where title_id = 'JP1001'&quot;, conn); </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;delete from titles where title_id = 'JP2002'&quot;, conn); </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul>
  26. 26. The ExecuteScalar Method <ul><li>Executes a query command and returns a single value in the result set, such as COUNT, AVG, MIN, MAX, and SUM. </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;select min (price) from titles&quot;, conn); </li></ul><ul><li>decimal amount = (decimal) cmd.ExecuteScalar (); </li></ul><ul><li>Console.WriteLine (&quot;ExecuteScalar returned {0:c}&quot;, amount); </li></ul>
  27. 27. The ExecuteScalar Method <ul><li>Another common use for ExecuteScalar is to retrieve BLOBs (binary large objects) from databases. </li></ul><ul><li>For example, retrieving an image from the “Logo” field of the Pubs database’s “Pub_info” table and encapsulates it in a bitmap: </li></ul><ul><li>use System.IO; </li></ul><ul><li>use System.Drawing; </li></ul><ul><li>use System.Data.SqlClient; </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;select logo from pub_info where pub_id='0736'&quot;, conn); </li></ul><ul><li>byte[] blob = (byte[]) cmd.ExecuteScalar (); </li></ul><ul><li>stream.Write (blob, 0, blob.Length); </li></ul><ul><li>Bitmap bitmap = new Bitmap (stream); </li></ul><ul><li>stream.Close (); </li></ul>
  28. 28. Write a BLOB to a database. <ul><li>FileStream stream = new FileStream(&quot;Logo.jpg&quot;, FileMode.Open); </li></ul><ul><li>byte[] blob = new byte[stream.Length]; </li></ul><ul><li>stream.Read (blob, 0, (int) stream.Length); </li></ul><ul><li>stream.Close (); </li></ul><ul><li>SqlCommand cmd = new SqlCommand </li></ul><ul><li>(&quot;insert into pub_info (pub_id, logo) values ('9937', @logo)&quot;, conn); </li></ul><ul><li>cmd.Parameters.Add (&quot;@logo&quot;, blob); </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul>
  29. 29. The ExecuteReader Method <ul><li>For performing database queries and obtain the results as quickly and efficiently as possible. </li></ul><ul><li>Returns a DataReader object. </li></ul><ul><li>Pulls back only the data to be “Read” by the DataReader not all records satisfying the query condition. </li></ul><ul><li>SqlCommand cmd = new SqlCommand (&quot;select * from titles&quot;, conn); </li></ul><ul><li>SqlDataReader reader = cmd.ExecuteReader (); </li></ul><ul><li>while (reader.Read ()) Console.WriteLine (reader[&quot;title&quot;]); </li></ul><ul><li>Each call to “Read” returns one row from the result set. </li></ul><ul><li>It uses a property indexer to extract the value of the record’s “title” field. </li></ul><ul><li>Fields can be referenced by name or by numeric index (0-based). </li></ul>
  30. 30. DataReader <ul><li>Reads data. </li></ul><ul><li>Reads schema (meta data) . </li></ul><ul><li>Stream-based access to the results of database queries. </li></ul><ul><li>Fast and efficient. </li></ul><ul><li>Read-only and forward-only. </li></ul><ul><li>Closing a DataReader: reader.Close( ) does NOT close the connection, only frees it for others to use. </li></ul><ul><li>D-E-F-E-N-S-I-V-E P-R-O-G-R-A-M-M-I-N-G. </li></ul>
  31. 31. DataSets <ul><li>Set-based Database Accesses </li></ul><ul><li>capture an entire query in memory </li></ul><ul><li>support backward and forward traversal </li></ul><ul><li>edit data and propagate the changes back to the database. </li></ul>
  32. 32. DataSet, DataTable and DataAdapter <ul><li>.NET supports set-based database accesses through three classes: </li></ul><ul><li>DataSet: equivalent of an in-memory database. </li></ul><ul><li>It consists of a collection of DataTables. </li></ul><ul><li>DataTables are created by a DataAdapter (SqlDataAdapter and OleDbDataAdapter). </li></ul><ul><li>DataSet doesn’t interact with databases directly. DataAdapter reads the physical data sources and fills DataTables and DataSets </li></ul>
  33. 33. DataSets vs. DataReaders <ul><li>To simply query a database and read through the records one at a time until you find the one you’re looking for, then DataReader is the right tool. DataReaders (1) retrieve only the data that you actually use, and (2) they don’t consume memory by storing every record that you read, but (3) but they can’t iterate backward. </li></ul><ul><li>To use all the query results and to iterate backward and forward through a result set, or to cache the result set in memory, use a DataSet. </li></ul><ul><li>Many controls that support DataSets are perfectly capable of binding to DataReaders. </li></ul>
  34. 34. DataGrid (GUI) <ul><li>DataGrid is an ASP control for displaying datasets. </li></ul><ul><li>Database displaying procedure: </li></ul><ul><ul><li>Use DataAdapter to get data from the database. </li></ul></ul><ul><ul><li>Fill the data into a DataSet </li></ul></ul><ul><ul><li>Bind the DataSet to a DataGrid </li></ul></ul><ul><ul><li>Select the fields (columns) to be displayed and their header texts. </li></ul></ul>
  35. 35. Example: DataAdapter, DataSet and DataGrid (GUI) <ul><li><asp:DataGrid ID=&quot;MyDataGrid&quot; </li></ul><ul><li>OnItemCommand=&quot;OnItemCommand&quot; RunAt=&quot;server&quot;> </li></ul><ul><li><Columns> </li></ul><ul><li><asp:BoundColumn HeaderText=&quot;Title&quot; </li></ul><ul><li>DataField=&quot;title&quot; /> </li></ul><ul><li><asp:BoundColumn HeaderText=&quot;Price&quot; </li></ul><ul><li>DataField=&quot;price&quot; DataFormatString=&quot;{0:c}&quot;/> </li></ul><ul><li><asp:ButtonColumn HeaderText=&quot;Action&quot; </li></ul><ul><li> Text=&quot;Add to Cart&quot; CommandName=&quot;AddToCart&quot; /> </li></ul><ul><li></Columns> </li></ul><ul><li></asp:DataGrid> </li></ul><ul><li>Examples/C9/Congo-Lab-MySQL/ViewCart.aspx </li></ul>
  36. 36. Example: DataAdapter, DataSet and DataGrid (GUI) <ul><ul><li>void Page_Load (Object sender, EventArgs e) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>if (!IsPostBack) { </li></ul></ul><ul><ul><li>string ConnectString = </li></ul></ul><ul><ul><li>ConfigurationSettings.AppSettings[&quot;connectString&quot;]; </li></ul></ul><ul><ul><li>MySqlDataAdapter adapter = new MySqlDataAdapter </li></ul></ul><ul><ul><li>(&quot;select * from titles where price != 0&quot;, ConnectString); </li></ul></ul><ul><ul><li>DataSet ds = new DataSet (); </li></ul></ul><ul><ul><li>adapter.Fill (ds); </li></ul></ul><ul><ul><li>MyDataGrid.DataSource = ds; </li></ul></ul><ul><ul><li>MyDataGrid.DataBind ();//Bind data to GUI </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
  37. 37. Transaction Commands <ul><li>A transaction is a logical unit of operations grouped together. </li></ul><ul><li>If one of the operations fails, the others will fail (or be rolled back). </li></ul><ul><li>Distributed transactions — transactions that span two or more databases. </li></ul><ul><li>The .NET Framework supports distributed transactions. </li></ul><ul><li>The .NET supports local transactions (one database): </li></ul>
  38. 38. Transacted Commands <ul><li>// Start a local transaction </li></ul><ul><li>trans = conn.BeginTransaction (IsolationLevel.Serializable); </li></ul><ul><li>// Create and initialize a SqlCommand object </li></ul><ul><li>SqlCommand cmd = new SqlCommand (); </li></ul><ul><li>cmd.Connection = conn; </li></ul><ul><li>cmd.Transaction = trans; </li></ul><ul><li>// Debit $1,000 from account 1111 </li></ul><ul><li>cmd.CommandText = &quot;update accounts set balance = &quot; + </li></ul><ul><li>&quot;balance - 1000 where account_id = '1111'&quot;; </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul><ul><li>// Credit $1,000 to account 2222 </li></ul><ul><li>cmd.CommandText = &quot;update accounts set balance = &quot; + </li></ul><ul><li>&quot;balance + 1000 where account_id = '2222'&quot;; </li></ul><ul><li>cmd.ExecuteNonQuery (); </li></ul><ul><li>// Commit the transaction (commit changes) </li></ul><ul><li>trans.Commit (); </li></ul>
  39. 39. Transacted Commands <ul><li>IsolationLevel.Serializable locks down the records while they’re updated so that they can’t be read or written. </li></ul><ul><li>Committing the transaction writes the changes to the database. </li></ul>
  40. 40. Uses DataGrid to represent a DataSet in XML <ul><ul><li>DataSet ds = new DataSet (); </li></ul></ul><ul><ul><li>ds.ReadXml (Server.MapPath (&quot;Bonuses.xml&quot;)); </li></ul></ul><ul><ul><li>MyDataGrid.DataSource = ds; </li></ul></ul>
  41. 41. Summary <ul><li>Database Programming: part of the architecture of a multi-tier application. </li></ul><ul><li>DB Programming API </li></ul><ul><li>ADO.NET </li></ul><ul><li>Data Providers (SQLServer Provider, OLEDB Provider) </li></ul><ul><li>Connection </li></ul><ul><li>Commands (NonQuery, Scaler) </li></ul><ul><li>DataReader </li></ul><ul><li>DataSet </li></ul><ul><li>DataAdapter </li></ul><ul><li>DataGrid </li></ul><ul><li>Transaction </li></ul>