7. The Framework Class Library (FCL)


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

7. The Framework Class Library (FCL)

  1. 1. 7. The FCL: files, databases, & data structures
  2. 2. Objectives <ul><li>“ The Framework Class Library (FCL) contains thousands of classes, from graphics to I/O to networking to XML processing. The goal of the FCL? To present an abstract, portable view of the underlying operating system…” </li></ul><ul><li>File I/O </li></ul><ul><li>Database access </li></ul><ul><li>Data structures </li></ul>
  3. 3. Part 1 <ul><li>File I/O… </li></ul>
  4. 4. I/O library <ul><li>Input/output library in System.IO namespace </li></ul><ul><li>Compiled into mscorlib.dll assembly </li></ul><ul><li>Support provided for: </li></ul><ul><ul><li>file and directory management </li></ul></ul><ul><ul><li>text files </li></ul></ul><ul><ul><li>binary files </li></ul></ul>
  5. 5. Character I/O <ul><li>Classes provided to do character IO </li></ul><ul><ul><li>most methods defined in base classes </li></ul></ul><ul><li>Two possible data locations </li></ul><ul><ul><li>disk </li></ul></ul><ul><ul><li>string </li></ul></ul>TextReader StreamReader StringReader TextWriter StreamWriter StringWriter read from disk read from string write to disk write to StringBuilder
  6. 6. StreamWriter <ul><li>StreamWriter usage: </li></ul><ul><ul><li>open file with one of many constructors </li></ul></ul><ul><ul><li>write with overloaded Write / WriteLine methods </li></ul></ul><ul><ul><li>close </li></ul></ul>automatically converted to string using ToString StreamWriter sw = new StreamWriter (&quot;Chores.txt&quot;); int n = 3; sw. WriteLine (&quot;Go to pet store&quot;); sw. Write (&quot;Feed all &quot;); sw. Write (n); sw. WriteLine (&quot; cats&quot;); sw. Close (); open write close char , bool , string , short , int , long , float , double , etc. text file
  7. 7. StreamReader <ul><li>StreamReader usage: </li></ul><ul><ul><li>open file with one of many constructors </li></ul></ul><ul><ul><li>read characters or strings with Read / ReadLine methods </li></ul></ul><ul><ul><li>close </li></ul></ul>StreamReader sr = new StreamReader (&quot;Chores.txt&quot;); string s; while ((s = sr. ReadLine ()) != null) Console.WriteLine(s); sr. Close (); open read close can read only char or string char , string text file
  8. 8. Files and directories <ul><li>Lots of utility classes for working with files & directories </li></ul><ul><ul><li>Directory : for manipulating directories and drives </li></ul></ul><ul><ul><li>File : for manipulating files </li></ul></ul><ul><ul><li>Path : for manipulating path strings </li></ul></ul>using System.IO; string[] drives = Directory. GetLogicalDrives (); foreach (string s in drives) { if ( Directory. Exists (s)) ... } all drives disk in drive?
  9. 9. Part 2 <ul><li>Database access… </li></ul>
  10. 10. Database library <ul><li>Database access provided by System.Data.* namespaces </li></ul><ul><li>Compiled into System.Data.dll assembly </li></ul><ul><li>Known collectively as ADO.NET </li></ul><ul><ul><li>native support for SQL Server and Oracle </li></ul></ul><ul><ul><li>support for other databases via older OleDB technology </li></ul></ul><ul><ul><li>requires a knowledge of SQL </li></ul></ul><ul><li>Core namespaces: </li></ul><ul><ul><li>general: System.Data , System.Data.Common </li></ul></ul><ul><ul><li>SQL Server: System.Data.SqlClient </li></ul></ul><ul><ul><li>Oracle: System.Data.OracleClient </li></ul></ul><ul><ul><li>OleDB: System.Data.OleDb </li></ul></ul>
  11. 11. Relational technology <ul><li>ADO.NET is designed to access relational databases </li></ul><ul><li>Example: </li></ul><ul><ul><li>Sales database with customers, orders, and products </li></ul></ul>
  12. 12. Overview of database access <ul><li>Three steps: </li></ul><ul><ul><li>open connection to database </li></ul></ul><ul><ul><li>execute SQL to update DB / retrieve records </li></ul></ul><ul><ul><li>close connection </li></ul></ul>
  13. 13. Step 1: open connection <ul><li>Connections are opened based on connection string info </li></ul><ul><ul><li>here we open a connection to a MS Access 2000 database </li></ul></ul><ul><ul><li>&quot;Sales.mdb&quot; must exist in same dir as .EXE (e.g. binDebug) </li></ul></ul>using System.Data; using System.Data.OleDb; string sConnection; sConnection = &quot;Provider=Microsoft.Jet.OLEDB.4.0;&quot; + &quot;Data Source=Sales.mdb&quot;; IDbConnection dbConn; dbConn = new OleDbConnection (sConnection); dbConn. Open (); MessageBox.Show( dbConn.State.ToString() ); connection
  14. 14. Building connection strings <ul><li>Connection strings are vendor-specific, not well-documented </li></ul><ul><li>Where to turn for help? </li></ul><ul><ul><li>www.connectionstrings.com </li></ul></ul><ul><ul><li>www.able-consulting.com/ADO_conn.htm </li></ul></ul>
  15. 15. Step 2: retrieve records <ul><li>Retrieve records via SQL Select query </li></ul><ul><ul><li>read-only access by database field names </li></ul></ul>string sql, name; sql = &quot;Select * From Customers Order By LastName Asc, FirstName Asc;&quot;; IDbCommand dbCmd; dbCmd = new OleDbCommand (); dbCmd.CommandText = sql; dbCmd.Connection = dbConn; IDataReader dbReader; dbReader = dbCmd. ExecuteReader (); while (dbReader. Read ()) { // retrieve records 1-by-1... name = dbReader [ &quot;LastName&quot; ] + &quot;, &quot; + dbReader [ &quot;FirstName&quot; ] ; this.listBox1.Items.Add(name); } data reader record record record
  16. 16. Step 3: close connection <ul><li>Be sure to close connection… </li></ul><ul><ul><li>to flush pending updates </li></ul></ul><ul><ul><li>so others can access DB (connections are limited resources) </li></ul></ul>dbConn. Close ();
  17. 17. Guaranteed close? <ul><li>Ensure DB is closed via try-catch-finally: </li></ul>IDbConnection dbConn = null; try { dbConn.Open(); . . . } catch(Exception ex) { System.Diagnostics.EventLog.WriteEntry(&quot;MyApp&quot;, ex.Message); System.Diagnostics.EventLog.WriteEntry(&quot;MyApp&quot;, ex.StackTrace); throw ex; } finally { if ((dbConn != null) && (dbConn.State != ConnectionState.Closed)) dbConn.Close(); }
  18. 18. Updating a database <ul><li>To update database, execute an SQL Action query </li></ul><ul><li>Example: </li></ul><ul><ul><li>delete customer by their id number </li></ul></ul>int result, cid = ? ; string sql; sql = String.Format(&quot;Delete From Customers Where CID={0};&quot;, cid); IDbCommand dbCmd; dbCmd = new OleDbCommand(); dbCmd.CommandText = sql; dbCmd.Connection = dbConn; dbConn.Open(); result = dbCmd. ExecuteNonQuery (); dbConn.Close(); if (result != 1) throw new Exception(&quot;Action failed to delete 1 customer?!&quot;);
  19. 19. Example of action queries <ul><li>Insert, update and delete: </li></ul><ul><li>Insert Into Customers(CID, FirstName, LastName, CreditLimit, Balance) Values(118, 'Jia', 'Zhang', 10000.0, 0.0); </li></ul><ul><li>Update Customers Set CreditLimit = 40000000000.0, Balance = 0.0 Where LastName = 'Gates' and FirstName = 'Bill'; </li></ul><ul><li>Delete From Customers Where CID = 666; </li></ul>
  20. 20. DataSets <ul><li>DataSets are an in-memory, read-write data structure </li></ul><ul><ul><li>easily filled with data from a database </li></ul></ul><ul><ul><li>easily displayed in a GUI app </li></ul></ul>DataSet DB Command Connection DataAdapter 20 $79.95 Dogs 100 $29.95 Cats 500 $ 4.49 Birds 5000 $ 0.49 Ants Quantity Price Product
  21. 21. Example <ul><li>Retrieve product info and display in a DataGrid: </li></ul>sql = &quot;Select * From Products;&quot; . . . DataSet ds; IDataAdapter adapter; ds = new DataSet (); adapter = new OleDbDataAdapter ((OleDbCommand) dbCmd); dbConn.Open(); adapter. Fill(ds) ; dbConn.Close(); this.dataGrid1.SetDataBinding(ds, &quot;Table&quot;);
  22. 22. Flushing changes back to database <ul><li>Reconnect, and apply adapter's Update() method: </li></ul>sql = &quot;Select * From Products;&quot; . . . DataSet ds; IDataAdapter adapter; ds = (DataSet) this.dataGrid1.DataSource; adapter = new OleDbDataAdapter ((OleDbCommand) dbCmd); OleDbCommandBuilder cmdBuilder; cmdBuilder = new OleDbCommandBuilder((OleDbDataAdapter) adapter); dbConn.Open(); adapter. Update ( ds ); // this fails if updates conflict dbConn.Close();
  23. 23. Part 3 <ul><li>Data structures… </li></ul>
  24. 24. Collections library <ul><li>Data structures in .NET are generally known as Collections </li></ul><ul><li>Located in the namespace System.Collections </li></ul><ul><li>Compiled into mscorlib.dll assembly </li></ul><ul><li>Defined in terms of object for generic use </li></ul><ul><li>Core classes: </li></ul><ul><ul><li>Array </li></ul></ul><ul><ul><li>ArrayList </li></ul></ul><ul><ul><li>Hashtable </li></ul></ul><ul><ul><li>Stack </li></ul></ul><ul><ul><li>Queue </li></ul></ul>
  25. 25. Collection interfaces <ul><li>Collections implement various interfaces to ensure uniformity </li></ul><ul><ul><li>classes that implement the same interface offer same services </li></ul></ul><ul><ul><li>makes library easier to learn and use </li></ul></ul><ul><ul><li>allows generic code to be written against interface </li></ul></ul><ul><li>Core interfaces: </li></ul><ul><ul><li>ICollection </li></ul></ul><ul><ul><li>IEnumerable </li></ul></ul><ul><ul><li>IEnumerator </li></ul></ul><ul><ul><li>IList </li></ul></ul><ul><ul><li>IComparer </li></ul></ul><ul><ul><li>IComparable </li></ul></ul>
  26. 26. ArrayList <ul><li>ArrayList provides storage for sequence of elements </li></ul><ul><ul><li>duplicate values ok </li></ul></ul><ul><ul><li>data stored internally as an array, automatically resized </li></ul></ul><ul><ul><li>primarily manipulated via Ilist </li></ul></ul>public class ArrayList : IList , IEnumerable , ... { // IList services ... // additional services int Capacity { get... set... } void TrimToSize() int BinarySearch(object value) int IndexOf (object value, int startIndex) int LastIndexOf (object value, int startIndex) ... } control of memory in underlying array searching
  27. 27. IList interface <ul><li>IList defines sequence of elements </li></ul><ul><ul><li>can be accessed by index </li></ul></ul>public interface IList : ICollection { int Add (object value); void Insert(int index, object value); void Remove (object value); void RemoveAt(int index); void Clear (); bool Contains(object value); int IndexOf (object value); object this[int index] { get; set; } bool IsReadOnly { get; } bool IsFixedSize { get; } } add new elements remove containment testing read/write existing element structural properties
  28. 28. Example <ul><li>Creating and using an ArrayList: </li></ul>using System.Collections; ArrayList a = new ArrayList (); a. Add (&quot;mom&quot;); // added to end... a. Add (&quot;dad&quot;); a. Add (&quot;sister&quot;); Console.WriteLine(a [2] ); // direct access if (a. Contains (&quot;dad&quot;)) // search ... foreach (string s in a) // iterate Console.WriteLine(s); handles iteration interfaces, casting element 0 element 1 element 2 true &quot;sister&quot;
  29. 29. Hashtable <ul><li>Hashtable provides collection of key/value pairs </li></ul><ul><ul><li>keys must be unique, values hold the data </li></ul></ul><ul><ul><li>stores object reference for both key and value </li></ul></ul><ul><ul><li>GetHashCode method of key used to determine placement </li></ul></ul>Hashtable ages = new Hashtable (); ages [ &quot;Ann&quot; ] = 27; ages [ &quot;Bob&quot; ] = 32; ages. Add (&quot;Tom&quot;, 15); ages [ &quot;Ann&quot; ] = 28; int a = (int) ages [ &quot;Ann&quot; ] ; create add update retrieve
  30. 30. Hashtable traversal <ul><li>Can traverse Hashtable contents </li></ul><ul><ul><li>each element is DictionaryEntry struct </li></ul></ul><ul><ul><li>data exposed in Key and Value properties </li></ul></ul>Hashtable ages = new Hashtable (); ages[&quot;Ann&quot;] = 27; ages[&quot;Bob&quot;] = 32; ages[&quot;Tom&quot;] = 15; foreach ( DictionaryEntry entry in ages) { string name = (string) entry. Key ; int age = (int) entry. Value ; ... } enumerate entries get key and value
  31. 31. Summary <ul><li>The FCL is huge </li></ul><ul><li>The FCL is quite powerful </li></ul><ul><li>The FCL is essentially a portable OS </li></ul><ul><ul><li>fully-implemented on Windows 98 and above </li></ul></ul><ul><ul><li>partially-implemented on FreeBSD, Mac OS X, and Linux </li></ul></ul>
  32. 32. References <ul><li>Books: </li></ul><ul><ul><li>J. Richter, &quot;Applied Microsoft .NET Framework Programming&quot; </li></ul></ul><ul><ul><li>T. Thai and H. Lam, &quot;.NET Framework Essentials&quot; </li></ul></ul><ul><ul><li>W. Vaughn and P. Blackburn, &quot;ADO.NET Examples and Best Practices for C# Programmers&quot; </li></ul></ul><ul><ul><li>B. Beauchemin, &quot;Essential ADO.NET&quot; </li></ul></ul><ul><li>Web sites: </li></ul><ul><ul><li>http://msdn.microsoft.com/net </li></ul></ul><ul><ul><li>Oracle for .NET: http :// otn.oracle.com/tech/windows/odpnet/ </li></ul></ul><ul><ul><li>Rotor (SSCLI): http://msdn.microsoft.com/net/sscli </li></ul></ul><ul><ul><li>Mono: http://www.go-mono.com/ </li></ul></ul>
  33. 33. Lab? <ul><li>Work on lab #4, &quot;Interfaces and FCL&quot;… </li></ul>