7. The FCL: files, databases, & data structures. 2 Microsoft Objectives “The Framework Class Library (FCL) contains thousands of classes, from graphics.

Slides:



Advertisements
Similar presentations
Data Structures and Collections
Advertisements

Database Access Using ADO.NET
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
Object-Oriented Application Development Using VB.NET 1 Chapter 13 Introduction to Data Access Classes and Persistence.
C# Programming: From Problem Analysis to Program Design1 Working with Databases C# Programming: From Problem Analysis to Program Design 3 rd Edition 14.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
5. OOP. 2 Microsoft Objectives “Classes, objects and object-oriented programming (OOP) play a fundamental role in.NET. C# features full support for the.
2. Developing in.NET and C#. 2 Microsoft Objectives “Microsoft.NET development is based on an underlying framework of tools and classes. These tools and.
Objective In this session we will discuss about : What is ADO. NET ?
Lecture 11: Programmatic Database Access with ADO.NET.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
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 UCN Technology: Computer Science: Autumn 2012 ADO.NET 2.0 Architecture DataReader DataSet Connection factory Config file.
Joe Hummel, PhD Dept of Mathematics and Computer Science Lake Forest College
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
Chapter 13 Database Access Using ADO.NET
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
Architectures Classic Client/Server Architecture Classic Web Architecture N-tier (multi-tier) Architecture FEN Databaser og Modellering.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
ASP.NET Rina Zviel-Girshin Lecture 5
Session 8: ADO.NET. Overview Overview of ADO.NET What is ADO.NET? Using Namespaces The ADO.NET Object Model What is a DataSet? Accessing Data with ADO.NET.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
1 COMP3100e Developing Microsoft.Net Applications for Windows (Visual Basic.Net) Class 6 COMP3100E.
1 UCN Technology: Computer Science: Autumn 2012 ADO.NET 2.0 Architecture DataReader DataSet Connection factory Config file.
1.Net programmingADO.NETNOEA / PQC ADO.NET Architecture Connection factory Config file DataReader DataSet DataGrid Autogeneration of SQL.
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
ADO.NET connections1 Connecting to SQL Server and Oracle.
C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.
CS360 Windows Programming
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
Interface: (e.g. IDictionary) Specification class Appl{ ---- IDictionary dic; dic= new XXX(); application class: Dictionary SortedDictionary ----
COP2360 – C# Programming Chapter 14 – Nov 25, 2015.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
1 9/22/05CS360 Windows Programming Arrays, Collections, Hash Tables, Strings.
Databases – Unit 3 & 4.  SQL is not restricted to a specific database, however in class we will be looking at the two major database programmes in use.
Dictionaries, Hash Tables, Collisions Resolution, Sets Svetlin Nakov Telerik Corporation
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Input and Output 23: Input and Output
CSC 298 Streams and files.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
Object-Oriented Application Development Using VB.NET 1 Chapter 13 Introduction to Data Access Classes and Persistence.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
VB.Net. Topics Introduction to VB.Net Creating VB.Net Project in VS 2005 Data types and Operators in VB.Net String Functions Conditions (If Else, Select.
Data Access. ADO.NET ADO.NET is the primary library for building database solutions within the.NET Framework. ADO.NET does not replace ADO. ADO and OLEDB.
.NET Data Access and Manipulation
Chapter 6: Creating Windows–based Applications 1 Microsoft® Visual C# 2008.
Lecture 1: The .NET Architecture
ASP.NET Programming with C# and SQL Server First Edition
Data Access with ADO.NET
Accessing Databases using Ado.net
Introduction to Database Processing with ADO.NET
ADO.NET Framework.
Input and Output 23: Input and Output
Lecture 6 VB.Net SQL Server.
Collections 24: Collections Programming C# © 2003 DevelopMentor, Inc.
Chapter 3 The .NET Framework Class Library (FCL)
CS313D: Advanced Programming Language
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Chapter 10 ADO.
Fundaments of Game Design
Presentation transcript:

7. The FCL: files, databases, & data structures

2 Microsoft 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

3 Microsoft Part 1 File I/O…

4 Microsoft 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

5 Microsoft Character I/O Classes provided to do character IO –most methods defined in base classes Two possible data locations –disk –string TextReader StreamReaderStringReader TextWriter StreamWriterStringWriter read from disk read from string write to disk write to StringBuilder

6 Microsoft StreamWriter StreamWriter usage: –open file with one of many constructors –write with overloaded Write / WriteLine methods –close automatically converted to string using ToString StreamWriter sw = new StreamWriter("Chores.txt"); int n = 3; sw.WriteLine("Go to pet store"); sw.Write("Feed all "); sw.Write(n); sw.WriteLine(" cats"); sw.Close(); open write close char, bool, string, short, int, long, float, double, etc. text file

7 Microsoft StreamReader StreamReader usage: –open file with one of many constructors –read characters or strings with Read / ReadLine methods –close StreamReader sr = new StreamReader("Chores.txt"); 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 Microsoft 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; string[] drives = Directory.GetLogicalDrives(); foreach (string s in drives) { if (Directory.Exists(s))... } all drives disk in drive?

9 Microsoft Part 2 Database access…

10 Microsoft 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

11 Microsoft Relational technology ADO.NET is designed to access relational databases Example: –Sales database with customers, orders, and products

12 Microsoft Overview of database access Three steps: 1.open connection to database 2.execute SQL to update DB / retrieve records 3.close connection

13 Microsoft 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"; IDbConnection dbConn; dbConn = new OleDbConnection(sConnection); dbConn.Open(); MessageBox.Show( dbConn.State.ToString() ); connection

14 Microsoft Building connection strings Connection strings are vendor-specific, not well-documented Where to turn for help? – –

15 Microsoft 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; IDataReader dbReader; dbReader = dbCmd.ExecuteReader(); while (dbReader.Read()) { // retrieve records 1-by-1... name = dbReader["LastName"] + ", " + dbReader["FirstName"]; this.listBox1.Items.Add(name); } data reader record

16 Microsoft Step 3: close connection Be sure to close connection… –to flush pending updates –so others can access DB (connections are limited resources) dbConn.Close();

17 Microsoft 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(); }

18 Microsoft 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?!");

19 Microsoft Example of action queries Insert, update and delete: Insert Into Customers(CID, FirstName, LastName, CreditLimit, Balance) Values(118, 'Jia', 'Zhang', , 0.0); Update Customers Set CreditLimit = , Balance = 0.0 Where LastName = 'Gates' and FirstName = 'Bill'; Delete From Customers Where CID = 666;

20 Microsoft DataSets DataSets are an in-memory, read-write data structure –easily filled with data from a database –easily displayed in a GUI app DataSet ProductPriceQuantity Ants $ Birds $ Cats $ Dogs $ DB Command Connection DataAdapter

21 Microsoft Example Retrieve product info and display in a DataGrid: sql = "Select * From Products;". DataSet ds; IDataAdapter adapter; ds = new DataSet(); adapter = new OleDbDataAdapter((OleDbCommand) dbCmd); dbConn.Open(); adapter.Fill(ds); dbConn.Close(); this.dataGrid1.SetDataBinding(ds, "Table");

22 Microsoft Flushing changes back to database Reconnect, and apply adapter's Update() method: sql = "Select * From Products;". 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 Microsoft Part 3 Data structures…

24 Microsoft 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

25 Microsoft 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

26 Microsoft 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() int BinarySearch(object value) int IndexOf (object value, int startIndex) int LastIndexOf (object value, int startIndex)... } control of memory in underlying array searching

27 Microsoft IList interface IList defines sequence of elements –can be accessed by index 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 Microsoft Example Creating and using an ArrayList: using System.Collections; ArrayList a = new ArrayList(); a.Add("mom"); // added to end... a.Add("dad"); a.Add("sister"); Console.WriteLine(a[2]); // direct access if (a.Contains("dad")) // search... foreach (string s in a) // iterate Console.WriteLine(s); handles iteration interfaces, casting element 0 element 1 element 2 true "sister"

29 Microsoft 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 Hashtable ages = new Hashtable(); ages["Ann"] = 27; ages["Bob"] = 32; ages.Add("Tom", 15); ages["Ann"] = 28; int a = (int) ages["Ann"]; create add update retrieve

30 Microsoft 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; foreach (DictionaryEntry entry in ages) { string name = (string) entry.Key; int age = (int) entry.Value;... } enumerate entries get key and value

31 Microsoft 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

32 Microsoft 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: – –Oracle for.NET: –Rotor (SSCLI): –Mono:

33 Microsoft Lab? Work on lab #4, "Interfaces and FCL"…