neal stublen [email protected]. populating a database sqlexpress should be installed with visual...

39
C#: INTRODUCTION FOR DEVELOPERS Neal Stublen [email protected]

Upload: clement-weaver

Post on 12-Jan-2016

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

C#: INTRODUCTION

FOR DEVELOPERS

Neal Stublen

[email protected]

Page 2: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

DATABASE CHECK

Page 3: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Populating a Database

SQLExpress should be installed with Visual Studio

The book provides a .sql file for populating the MMABooks database in SQLExpress

Double-click the .bat file on the S: drive We’ll need to repeat this process at the

start of each class session

Page 4: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Confirm Database Access Using Visual Studio to locate the new

database as a Data SourceView > Server ExplorerAdd Connection...Server name: .\SQLEXPRESSDatabase name: MMABooksTest Connection

Page 5: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

HANDLING DATA ERRORS

Page 6: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Data Provider Errors

SqlException OracleException OdbcException OleDbException

Number Message Source Errors

Page 7: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Catch Provider Exceptionprivate void Form1_Load(object sender, EventArgs e){ try { this.customersTableAdapter.Fill(...); } catch (SqlException ex) { // report ex.Number, ex.Message }}

Page 8: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

ADO.NET Errors

DBConcurrencyException DataException ConstraintException NoNullAllowedException

Message

Page 9: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Catch ADO.NET Exceptiontry{ this.customerBindingSource.EndEdit(); this.customersTableAdapterManager.UpdateAll(...);}catch (DBConcurrencyException ex){ // from UpdateAll() exception // report concurrency error this.customerTableAdapter.Fill(...);}catch (DataException ex){ // from EndEdit() exception // report ex.Message customerBindingsSource.CancelEdit();}catch (SqlException ex){ // report ex.Number, ex.Message}

Page 10: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

DataGridView Control Errors

Not an exception, but an event on the control

DataError

Exception RowIndex ColumnIndex

Page 11: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Catch DataGridView Errorsprivate void gridView_DataError(...){ // report error in e.RowIndex and/or // e.ColumnIndex}

Page 12: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

MORE WITH DATA SOURCES AND DATA SETS

Page 13: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Dataset Designer

Command property on Fill, GetData Opens Query Builder Visually build SQL command Preview Data to see query results

Page 14: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Designer.cs Queries

SQL queries are updated in the schema’s Designer.cs file

DeleteCommand, InsertCommand, UpdateCommand

SCOPE_IDENTITY() = ID generated from INSERT command

@ = query parameter UPDATE only updates a record

matching original column values

Page 15: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Bound TextBox Controls

Formatting and Advanced Binding Select TextBox Open Properties Window Expand DataBindings property Select Advanced option, click “…”

Select new format type Specify representation of null value

Page 16: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Bound ComboBox Controls Populate a ComboBox with values from

a column of a database table SelectedItem is used to specify the

value in a column of another database table

Page 17: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Code Practice Select customer state using dropdown list

ComboBox instead of TextBox

Create StatesDataSet in Data Source window Add DataSet control for StatesDataSet and set

DataSetName property Add BindingSource control for DataSet and set

DataSource/DataMember properties Set State field to use ComboBox Set ComboBox to use data bound controls Clear ComboBox data bindings for Text property

Page 18: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Parameterized Queries

We can customize a DataSet by providing parameters to modify the query

Parameters can be introduced using the Query Builder

Page 19: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Code Practice Create a customer search form Populate a DataGridView based on the entry within a

TextBox

Create CustomersDataSet as a Data Source Open CustomersDataSet.xsd and modify Fill

CommandText using Query Builder Change Name Filter to “LIKE @Name” Drag Customers table onto a form Update Fill to append ‘%’ ToolStrip is added to provide the @Name parameter Examine Fill button’s Click event

Page 20: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

What was that ToolStrip?

A tool strip can be docked around the main window

It contains other controls Controls can be added through the Items

collection Items have events just like other controls We can add a “Cancel” button to the

navigation tool stripCancelEdit() on the customersBindingSource

Page 21: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Navigation Tool Strip customersBindingSource.AddNew(); customersBindingSource.EndEdit(); customersBindingSource.CancelEdit(); customersBindingSource.RemoveCurrent();

A binding source keeps all bound controls in sync

Page 22: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

DataViewGrid Control

Smart tag allows you to modify commonly used properties

Columns can be added, moved, or removedRemove ID columnsColumns still exist in the DataSet

Column content can be formatted using DefaultCellStyle

Page 23: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Master-Detail Relationships One-to-many relationship between

tables One customer has many invoices

Page 24: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Code Practice View customer invoices based on the

selection of a customer record Populate DataGridView with invoice entries

Create Customers-Invoices DataSet Customers uses Detail View Drag Customers onto Form Drag Customers.Invoices onto Form Examine DataSource/DataMember on grid

view and invoicesBindingSource

Page 25: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

CREATING DATA ACCESS OBJECTS

Page 26: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Why create our own?

Place data objects into a shared library We’re not using a form Separates database code from UI code

Page 27: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Using Our Own Connections

SqlConnection cxn = new SqlConnection();cxn.ConnectionString = "...";cxn.Open();...cxn.Close();

Sample Connection String:

Data Source=localhost\SqlExpress;Initial Catalog=MMABooks;Integrated Security=False;User ID=Be Careful;Password=Be Very, Very Careful;

Page 28: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Using Our Own CommandsSqlCommand cmd = new SqlCommand();cmd.CommandText =

"SELECT * FROM Customers";cmd.CommandType = CommandType.Text;cmd.Connection = cxn;SqlReader r = cmd.ExecuteReader();

Page 29: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Parameters in Commands Add parameters to SQL statements

SELECT * FROM Customers WHERE STATE = 'VA'

SELECT * FROM Customers WHERE STATE = @State

@State is a SQL variable representing the state

Page 30: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Create the ParametersSqlParameter stateParam = new SqlParameter();stateParam.ParameterName = "@State";stateParam.Value = some_local_variable;

cmd.Parameters.Add(stateParam);

cmd.Parameters.AddWithValue("@State", value);

Page 31: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

SQL Injection

Don’t let this happen…

string cmd = "SELECT * FROM Customers WHERE State=" + value;

Page 32: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Executing CommandsSqlDataReader r = cmd.ExecuteReader();

List<Customer> customers =new List<Customer>();

while (r.Read()){ Customer c = new Customer(); ... customers.Add(c);}

r.Close();cxn.Close();

Page 33: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Other Commandsobject result = cmd.ExecuteScalar();// Cast result to expected type

cmd.ExecuteNonQuery();

Page 34: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Examine Chapter 20 Code MMABooksDB CustomerDB

GetCustomer – ExecuteReader, exceptionsAddCustomer – current IDUpdateCustomer – concurrency,

ExecuteNonQuery StateDB frmAddModifyCustomer

Page 35: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

BONUS CONTENT

Page 36: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Disposable Objects

IDisposable interface Single method: Dispose()

Releases unmanaged resources that may be held by an object

Such as a database connection!!

Page 37: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Using…

using keyword can be used to confine objects to a particular scope

using also ensures that Dispose() is called if the object implements IDisposable

using also calls Dispose if an exception is thrown

Page 38: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Disposable Connectionsusing (SqlConnection cxn = ...){ cxn.Open(); using (SqlCommand cmd = ...) { cmd.Execute... }}

Page 39: Neal Stublen nstublen@jccc.edu. Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating

Using Equivalenceusing (object obj = …){}

object obj = …;try{}finally{ obj.Dispose();}