Date post: | 18-Jan-2016 |
Category: |
Documents |
Upload: | florence-small |
View: | 219 times |
Download: | 0 times |
Visual Basic.NET ProgrammingADO ProgrammingFebruary 11, 2004
AgendaQuestions / Homework
Namespaces
Files, Streams and Directories
OpenFileDialog and SaveFileDialog
Class Exercise FileIO Class
Databases
ADO.NET
Grid Control
Class Exercise
Homework
Coming Attractions
•February 18, 2004 – ASP.NET Programming– Web Forms– ASP.NET Controls
•February 18, 2004– Web Services
•March 3, 2004– More Web Services
Open Questions
• Open Homework Assignments
• Visual Studio Class Library Root Namespace Namespaces and a Demo
• Collections and Serialization / Deserialization Class Demo
Namespaces
Namespaces
• The Namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types.
• Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace.
• Namespaces implicitly have public access and this is not modifiable.
Namespaces• Used to organize classes and types into a
hierarchical structure.• Makes it easier to find types.• Helps prevent name collisions.• Declared with the Namespace keyword.
Namespace HelloVS
End Namespace
Namespaces can be nestedNamespace HelloVS Namespace HelloVS.Foo
NamespacesNamespace name[.name1] ...]
name, name1 - A Namespace name can be any legal identifier. ANamespace name can contain periods.
type-declarations - Within a Namespace, you can declare one or more of the following types:
• another Nnamespace
• Class
• Interface
• Struct
• Enum
• Delegate
Namespaces and Imports• Namespaces can get pretty long
– e.g. System.Runtime.Remoting.Channels.HttpChannel– To use the HttpChannel class, you would need to type:
System.Runtime.Remoting.Channels.Http.HttpChannel• Fortunately, with a Namespace rather than... Dim hc As System.Runtime.Remoting.Channels.HttpChannel
you can use...Imports System.Runtime.Remoting.Channels.HttpDim hc As HttpChannel
• Imports is just syntactic sugar, does not link any code automatically.
• So System.Console.WriteLine can become Console.WriteLine
Class Library Namespace
• Click on Project Properties
• Root namespace is under common properties
Files, Streams and Directories
Files, Streams and Directories
• Directories and Files• Reading and Writing a Sequential Files • Using OpenFileDialog and SaveFileDialog
System.IO Namespace
• Directory Class • File Class • StreamReader Class • SteamWriter Class
System.IO Namespace• Directory Class - Exposes static methods for creating,
moving, and enumerating through directories and subdirectories.
• File Class - Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
• StreamReader Class - Implements a TextReader that reads characters from a byte stream in a particular encoding.
• SteamWriter Class - Implements a TextWriter for writing characters to a stream in a particular encoding.
Directory Class
Exposes static methods for creating, moving, and enumerating through directories and subdirectories.
Directory ClassImports System.IOPublic Class Test
Public Shared Sub Main()Dim path As String = "c:\MyDir"Dim target As String = "c:\TestDir"Try If Directory.Exists(path) = False Then
Directory.CreateDirectory(path) Create Dir. End If If Directory.Exists(target) Then
Directory.Delete(target, True) Delete Directory End If Directory.Move(path, target) Move Directory File.CreateText(target + "\myfile.txt") New File
Catch Ex As Exception Console.WriteLine(Ex.message)
End TryEnd Sub
End Class
File Class
Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of
FileStream objects.
File Class
Imports System.IOPublic Class Test
Public Shared Sub Main()Dim target As String = "c:\TestDir\Test.Txt"
If File.Exists(target ) Then File.Delete(target ) End If
If File.Exists(target ) = False Then Dim sw As StreamWriter = File.CreateText(target)
sw.WriteLine("Hello World") sw.Close() End If
End SubEnd Class
StreamReader Class
Implements a TextReader that reads characters from a byte stream in a particular encoding.
StreamReader ClassImports SystemImports System.IOClass Test Public Shared Sub Main() Try Dim sr As StreamReader = New StreamReader("TestFile.txt") Dim line As String Do line = sr.ReadLine() Console.WriteLine(Line) Loop Until line Is Nothing sr.Close() Catch E As Exception Console.WriteLine("The file could not be read:") Console.WriteLine(E.Message) End Try End SubEnd Class
SteamWriter Class
Implements a TextWriter for writing characters to a stream in a particular encoding.
StreamWriter Class
Imports SystemImports System.IOClass Test Public Shared Sub Main() Dim sw As StreamWriter = New StreamWriter("TestFile.txt") sw.Write("This is the ") sw.WriteLine("header for the file.") sw.WriteLine("-------------------") sw.Write("The date is: ") sw.WriteLine(DateTime.Now) sw.Close() End SubEnd Class
OpenFileDialogand
SaveFileDialog
OpenFileDialog Class
• Represents a common dialog box that displays the control that allows the user to open a file.
• This class allows you to check whether a file exists and to open it. The ShowReadOnly property determines whether a read-only check box appears in the dialog box.
• The ReadOnlyChecked property indicates whether the read-only check box is checked.
• Imports requires (default with Forms application)
System.Windows.Forms
OpenFileDialogProtected Sub button1_Click(sender As Object, e As System.EventArgs) Dim myStream As Stream Dim openFileDialog1 As New OpenFileDialog() openFileDialog1.InitialDirectory = "c:\" openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" openFileDialog1.FilterIndex = 2 openFileDialog1.RestoreDirectory = True If openFileDialog1.ShowDialog() = DialogResult.OK Then myStream = openFileDialog1.OpenFile() If Not (myStream Is Nothing) Then ' Insert code to read the stream here. myStream.Close() End If End IfEnd Sub
SaveFileDialog Class
• Represents a common dialog box that allows the user to specify options for saving a file.
• Imports requires (default with Forms application)
System.Windows.Forms
• This class allows you to open and overwrite an existing file or create a new file.
SaveFileDialogProtected Sub button1_Click(sender As Object, e As System.EventArgs) Dim myStream As Stream Dim saveFileDialog1 As New SaveFileDialog() saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" saveFileDialog1.FilterIndex = 2 saveFileDialog1.RestoreDirectory = True If saveFileDialog1.ShowDialog() = DialogResult.OK Then myStream = saveFileDialog1.OpenFile() If Not (myStream Is Nothing) Then ' Code to write the stream goes here. myStream.Close() End If End IfEnd Sub
Class Exercise FileIO Class
File and Directory Class Exercise
• Modify the NameAddress application as follows, before you write a serialized file:– Test for a specific directory, if it exists delete it– Create the same directory– Use the SaveFileDialog to select the target file name
and directory for saving the serialize file.• Before you read the serialized file use the
OpenFileDialog to select the deseriale file.
Databases
Databases and SQL
Introduction
Relational Database Model
Structured Query Language (SQL)Basic: SELECT Query
WHERE ClauseORDER BY ClauseINSERT Statement
UPDATE StatementDELETE Statement
Introduction
Database:– Integrated collection of data– Database management system (DBMS)
• Provides mechanisms for storing and organizing data in a way that is consistent with database’s format
• Allows storage and access to database without knowledge of internal representation
– Relational Databases most popular• Use Structured Query Language to perform queries
(search) and manipulate data• Programming languages need an interface to interact with
relational databases
Relational Database Model
• Logical representation of data:– Relationships can be considered without
concern for physical structure of data
• Composed of tables– Rows called records– Columns called fields– Primary key: field that contains unique data
• Each record can be identified by at least one distinct value
– New sets made from queries called result sets
Relational Database Modelnumber name department salary location
23603 Jones 413 1100 New Jersey
24568 Kerwin 413 2000 New Jersey
34589 Larson 642 1800 Los Angeles
35761 Myers 611 1400 Orlando
47132 Neumann 413 9000 New Jersey
78321 Stephens 611 8500 Orlando
record/row
field/columnprimary key
Structured Query Language (SQL)
• Used to request data (perform queries) and manipulate data
Structured Query Language (SQL)
SQL Key Word Description
SELECT Select (retrieve) fields from one or more tables.
FROM Tables from which to get fields. Required in every Select statement.
WHERE Criteria for selection that determines the rows to be retrieved.
ORDER BY Criteria for ordering records.
Basic Select Query• Extracts information from one or more tables in a
database• Format:
– Basic: SELECT * FROM tableName– * extracts all columns– To get specific fields use a comma separated
list instead of *• Example:
SELECT * FROM Books
Where Clause• Used to specify certain criteria in a query• Basic form:
– SELECT * FROM tableName WHERE criteria• Example:
– SELECT * FROM Books WHERE Author = ‘Robert Parker’
• Can use LIKE clause– Used for pattern matching
• Uses wildcards– *: zero or more characters take its place– ?: exactly one character takes its place
ORDER BY Clause• Used to arrange results of a query
– Can be ascending or descending order• Uses ASC and DESC respectively
• Example:
SELECT * FROM Books ORDER BY Copyright DSC
• Can be used to sort by multiple fields
Insert Statement
• Inserts a new record into a table• Form:
INSERT INTO tableName(fieldName1, …) VALUES (value1, …)
• Values must match field names in order and type
UPDATE Statement
• Modifies data in a table• Form:
UPDATE tableName SET fieldName1 = value1 WHERE criteria
DELETE Statement
• Removes data from a table• Form:
DELETE FROM tableName WHERE criteria
ADO.NET
ADO Components
• DataAdapter
• DBConnection and DBCommand
• Datasets
• Grid Control
• XML Output
ADO.NET
DataAdapters
• Bridge between a data source and a DataSet
• The DataAdapter Fill() method is used to retrieve data from the database and to populate the DataSet
• Using the DataAdapter to mediate between the DataSet and the database allows a DataSet to represent more than one database or data source
DBCommand and DBConnection• DBConnection object represents a connection to a
data source.
• DBCommand object allows you to send a command (typically a SQL statement or stored procedure) to the database.
• Both are implicitly created when you create a database, but they may also be explicitly created and accessed.
DataSets
• Replaces the Old Recordset
• Standalone Relational Data Structure
• Completely Separate From the Server
• Resides with Client
• Contains one or more tables, plus table relationships, full subset of database
• Can be used to update data back in the source database
Navigating a DataSet Dim ds As DataSet = New DataSet()
Dim dt As DataTable
Dim rw As DataRow
Dim cl As DataColumn
dt = ds.Tables.Item("Books")
For Each rw In dt.Rows
For Each cl In dt.Columns
tmpStr = rw(cl)
Next cl
Nexr rw
XML Output From DataSetDim strXML As String
strXML = ds.GetXml()
Dim wlf As WriteListingFile = New WriteListingFile()
wlf.GetFileToOpen()
wlf.WriteLine(strXML)
wlf.Close()
Sample XML Output-- <NewDataSet>-- <Books>
-<Title>Family Honor</Title>-<Author>Robert Parker</Author>-<Publisher>G.P. Putnam / the Penquin Group</Publisher>-<Copyright>1999</Copyright>-<Comments>A Sunny Randall novel.</Comments>
- </Books>-- <Books>
- <Title>Hugger Mugger</Title>- <Author>Robert Parker</Author>- <Publisher>G.P. Putnam / the Penquin Group</Publisher>- <Copyright>2000</Copyright>- <Comments>A Spenser Novel.</Comments> </Books> </NewDataSet>
Database Types
• SQL– SQL Server Version 7– SQL Server Version 2000
• OleDB– Microsoft Access
• ODBC– MySQL
.NET Framework Data Providers
.NET Framework Data Provider for SQL Server
For Microsoft® SQL Server™ 7.0 or later.
.NET Framework Data Provider for OLE DB
For data sources exposed using OLE DB.
ODBC .NET Framework Data Provider
For data sources exposed using ODBC.
ADO.NETADO.NET is the strategic application-level interface for providing data access services in the Microsoft .NET Platform. You can use ADO.NET to access data sources using the new .NET Framework data providers. These data providers include:
– .NET Framework Data Provider for SQL Server. – .NET Framework Data Provider for OLE DB. – .NET Framework Data Provider for ODBC. – .NET Framework Data Provider for Oracle.
These data providers support a variety of development needs, including middle-tier business objects using live connections to data in relational databases and other stores.
Comparison Chart
Data Base Type Connection Object Adapter Object
SQL
(SQL Server)
SQLConnection SQLDataAdapter
OleDB
(Microsoft Access)
OleDBConnection OleDBDataAdapter
ODBC
(MySQL)
ODBCConnection OdbcDataAdapter
SQL (SQL Server)
Imports System.Data.SqlClient
Private cn As SqlConnection = New System.Data.SqlClient.SqlConnection() Private adpt As SqlDataAdapter Private ds As DataSet = New DataSet() Dim sqlString As String = “SELECT * FROM Books” If cn.State <> ConnectionState.Open Then cn.ConnectionString = "Initial Catalog=Books;
Data Source=localhost;Integrated Security=SSPI;" cn.Open() End If
adpt = New SqlDataAdapter(sqlString , cn)adpt.Fill(ds, "Books")
OleDB (Microsoft Access)
Imports System.Data.OleDb
Private cn As OleDbConnection = New OleDbConnection() Private adpt As OleDBDataAdapter Private ds As DataSet = New DataSet() Dim sqlString As String = “SELECT * FROM Books” If cn.State <> ConnectionState.Open Then cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\…\Books.mdb“ Full Path cn.Open() End If
adpt = New OleDBDataAdapter(sqlString , cn)adpt.Fill(ds, "Books")
ODBC (MySQL Database)
Imports Microsoft.Data.Odbc
Private cn As ODBCConnection = New ODBCConnection() Private adpt As OdbcDataAdapter Private ds As DataSet = New DataSet() Dim sqlString As String = “SELECT * FROM Books” If cn.State <> ConnectionState.Open Then cn.ConnectionString = "FIL=MySQL;DSN=MySQL_Books" cn.Open() End If
adpt = New OdbcDataAdapter(sqlString , cn)adpt.Fill(ds, "Books")
Grid Control
Grid Control
• Easy way to display a DataSet Table
Data Grid Control
Private DataGrid1 As DataGrid() = New DataGrid()
Note: Above created using Form Design.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
OleDbDataAdapter1.Fill(DataSet1)
DataGrid1.SetDataBinding(DataSet1, "Books")
End Sub
Building a Simple Database Query using a Grid Control
Let’s jointly build a very simple ADO.NET Database Application.
Simple Database Query1. Open a new Windows Form Project
2. Add a Button ("Update Grid")
3. Add an OleDBDataAdapter
4. Add a DataSet
5. Add a DataGrid
6. Double click on the Button and add these two lines of code
OleDbDataAdapter1.Fill(DataSet1) DataGrid1.SetDataBinding(DataSet1, "Books")
7. Run it...
Hand Crafted Grid Populator Class Exercise
Books Populator Class Exercise
Guestbook Database Homework Exercise
for February 18th