7. The Framework Class Library (FCL)

Download Report

Transcript 7. The Framework Class Library (FCL)

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