.NET Frameworks week 4 November 24, 2003
Dec 27, 2015
Agenda – November 24, 2003
Open Questions
Namespaces
System.IO Namespace (Files and Directories)
File I/O and Directory Class Exercise
Databases and SQL (GRID Control)
Simple Books Database Class Exercise
Books Database Grid Populator Class Exercise
XML
Guestbook Database Homework Exercise due December 4th
Week Topics5 - Thursday
12/4/2003
Bootstrapping the Common Language Resource (CLR)
Modules and Assemblies
.Net Packaging
Public and Private Keys
Shared Assemblies
The Global Assemble Cache (GAC)
Strong Names
.NET Frameworks Language Overview
Frameworks Class Library
Advanced Concepts (Serialization and Reflection)
Course Schedule
Week Topics
6 - Monday
12/8/2003
ASP.NET
Programming .NET Web Form Application
Introduction to Web Services
Web Security
7 - Thursday
12/11/2003
Web Services Class Project (continued)
8 - Monday
12/15/2003
Web Services Class Project (continued)
Course Schedule
Tonight’s Class Goals
• Namespaces
• Files and Streams and Directories
• ADO.NET Database Programming– Connectors– Adapters– DataSets
• Using the Grid Control
• Datasets and XML
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 { … }
• Namespaces can be nested– namespace HelloVS { namespace Foo { … } }– namespace HelloVS.Foo { … }
Namespacesnamespace name[.name1] ...] { type-
declarations }
name, name1 - A namespace name can be any legal identifier. A namespace name can contain periods.
type-declarations - Within a namespace, you can declare one or more of the following types:
• another namespace
• class
• interface
• struct
• enum
• delegate
Namespaces and Using• Namespaces can get pretty long
– e.g. System.Runtime.Remoting.Channels.Http– To use the HttpChannel class, you would need to type:
System.Runtime.Remoting.Channels.Http.HttpChannel
• Fortunately, C# gives us a shorthand mechanismusing System.Runtime.Remoting.Channels.Http;
HttpChannel hc = new ….;
• Using can only be used with a namespace, not a class name• Using is just syntactic sugar, does not link any code
automatically.• So System.Console.WriteLine can become
Console.WriteLine
Files and Streams and Directories
• Directories and Files• Reading and Writing a Sequential Files • Using OpenFileDialog and SaveFileDialog
Directory Class
Exposes static methods for creating, moving, and enumerating through directories and subdirectories.
Directory Classusing System;using System.IO;class Class1 {
[STAThread]static void Main(string[] args) {
string path = "c:\\MyDir";string target = "c:\\TestDir";if (Directory.Exists(path) == false) {
Directory.CreateDirectory(path); // Create Dir.}if (Directory.Exists(target)) {
Directory.Delete(target, True); // Delete Directory}Directory.Move(path, target); // Move DirectoryFile.CreateText(target + "\\myfile.txt"); // New File
}}
File Class
Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of
FileStream objects.
File Classusing System;using System.IO;class Class1{
[STAThread]static void Main(string[] args) {
string target = "c:\\TestDir\\Test.Txt"; if (File.Exists(target)) {
File.Delete(target ); }
else {StreamWriter sw = File.CreateText(target);sw.WriteLine("Hello World"); sw.Close();
}}
}
StreamReader Class
Implements a TextReader that reads characters from a byte stream in a particular encoding.
StreamReader Classusing System;using System.IO;class Class1{
[STAThread]static void Main(string[] args) {
using (StreamReader sr = new StreamReader("TestFile.txt")) {
string line;while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);}
}}
}
SteamWriter Class
Implements a TextWriter for writing characters to a stream in a particular encoding.
StreamWriter Class
using System;using System.IO;class Class1{
[STAThread]static void Main(string[] args) {
using (StreamWriter sw = 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);
}}
}
Represents a common dialog box that displays the control that allows the user to open a file. This
class cannot be inherited.
OpenFileDialog
SaveFileDialog - Represents a common dialog box that allows the user to specify options for saving a file. This class cannot be inherited.
SaveFileDialog
OpenFileDialogprotected void button1_Click(object sender, System.EventArgs e) {
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = openFileDialog1.OpenFile())!= null)
{
// Insert code to read the stream here.
myStream.Close();
}
}
}
SaveFileDialogprotected void button1_Click(object sender, System.EventArgs e) {
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
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
Books Database
• Microsoft Access• One Table Books
– Title– Author– Copyright– Publisher – Comments
• On Website
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
.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")
DataSets
• Replaces the Old Recordset
• Standalone Relational Data Structure
• Completely Separate From the Server
• Resides with Client
• Contains one or more tables
DataSet DataSet ds = new DataSet(); DataTable dt; DataRow rw; DataColumn cl;
dt = ds.Tables.Item("Books");for each rw In dt.Rows {
for each cl In dt.Columns {tmpStr = rw(cl);
}}
Data Grid Control
private DataGrid dg = new DataGrid();
Note: Above created using Form Design.
dg.SetDataBinding(ds, "Books");
dg.Show();
XML Output From DataSet
string strXML;
strXML = ds.GetXml();
WriteListingFile wlf = 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>
Class ExerciseSimple Books Database Form
Let’s jointly build a very simple ADO.NET Database Application.