Neal Stublen Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom.

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

Chapter 10 Database Applications Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Chapter 14.3 LINQ to SQL Programming in Visual Basic 2010: The Very Beginner’s Guide by Jim McKeown Databases – Part 3.
Chapter 18 - Data sources and datasets 1 Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Chapter 12: Using ADO.NET 2.0 Programming with Microsoft Visual Basic 2005, Third Edition.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Introduction to Data Adapter. A Simplified View of ADO.Net Objects Ado.Net Data Provider Connection Adapter Command Reader Dataset Data Consumer WinForm.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
VB.NET Database Access ISYS 812. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
C# Programming: From Problem Analysis to Program Design1 Working with Databases C# Programming: From Problem Analysis to Program Design 3 rd Edition 14.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
Introduction to ADO.Net and Visual Studio Database Tools
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
Databases and LINQ Visual Basic 2010 How to Program 1.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Chapter 11 Introduction to Database Processing. Class 11: Database Processing Use a Visual Studio Wizard to establish a database connection used to load.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
Neal Stublen Open/Close Connections  ADO.NET uses “connection pooling” to optimize opening and closing connections to the database.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
11 Updating a Database Table Textbook Chapter 14.
ADO.NET Tools and Wizards. Slide 2 Data Sources Window (Introduction) Use the Data Sources window to Establish a connection Create bound control instances.
Advanced Visual Basic th Edition Chapter 3: Using SQL Server Databases (c) 2007 Pearson Education Inc. All rights reserved. You may modify and copy.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Twelve Access Databases and LINQ.
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.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Thirteen Working with Access Databases and LINQ.
CHAPTER EIGHT Accessing Data Processing Databases.
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
ADO.NET Part 2. Slide 2 Overview Slide 3 Introduction to the DataGridView Control It’s a two-dimensional grid containing rows and columns Its use in.
Using Adapter Wizard ISYS 512. Data Adapter Wizard – 2 nd Level of Using ADO.Net Configure Data Adapter and generating a dataset: –From the Data tab of.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
1 Data Classes- DataView DataGridView Control. Objectives 2  Data Class  DataAdapter  DataReader  DataSet  DataTable  DataView  DataGridView Control.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
1 Chapter 20 – Data sources and datasets Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Mauricio Featherman, Ph.D. Washington St. University
Introduction to ADO.Net and VS Database Tools and Data Binding ISYS 350.
Making the Most of WinForms 2.0 Data Binding Rajiv Sodhi Microsoft India.
Chapter Fourteen Access Databases and SQL Programming with Microsoft Visual Basic th Edition.
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 25 I’m Suffering from Information Overload.
Chapter 24 I’m Suffering from Information Overload (Access Databases) Clearly Visual Basic: Programming with Visual Basic nd Edition.
1 Database Programming with ADO.NET Kashef Mughal.
ADO.NET Objects Data Adapters Dr. Ron Eaglin. Agenda Builds on Information in Part I Should have working knowledge of creating a database connection Continuation.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
Understand Databound Controls Windows Development Fundamentals LESSON 4.2A.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 350.
Chapter Fourteen Access Databases and SQL Programming with Microsoft Visual Basic th Edition.
Programming with Microsoft Visual Basic 2012 Chapter 14: Access Databases and SQL.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Common SQL keywords. Building and using CASE Tools Data Base with Microsoft SQL-Server and C#
ASP.NET Programming with C# and SQL Server First Edition
Microsoft Visual Basic 2010: Reloaded Fourth Edition
ADO.NET Framework.
© 2013, Mike Murach & Associates, Inc.
CIS16 Application Programming with Visual Basic
How to work with bound controls and parameterized queries
Chapter 10 Accessing Database Files
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Presentation transcript:

Neal Stublen

Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom data objects  IDisposable  ADO.NET connections  Q&A

Review  How would you display a single customer record on a form?

Database Errors  Errors can be reported by the data provider, ADO.NET, or a bound control  Possible causes Invalid data Network failure Server shutdown

Data Provider Errors  Data providers will throw an exception when an error occurs SqlException OracleException OdbcException OleDbException

Error Properties  Number  Message  Source  Errors Contains multiple errors that may have occurred when executing a single command Number and Message refer to the first error in the collection

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

ADO.NET Errors  Errors may occur when updating a Dataset DBConcurrencyException DataException (general exception) ConstraintException NoNullAllowedException  Message property describes the exception

Catch ADO.NET Exception try { 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 }

Concurrency Errors  Exception handling of concurrency errors may be tested by running multiple instances of an application and editing the same record from both applications

DataGridView Control Errors  Not an exception, but an event on the control  DataError event Exception RowIndex ColumnIndex

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

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

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

Formatting Bound Text  Advanced formatting options Numeric values Dates  Display for null values  Format and Parse events of the Binding object

Why a BindingSource?  Using a BindingSource will keep all bound controls synchronized  Changing the position within a data source will update all the bound controls  Changes made to any controls will update the data source when changing position

Using a BindingSource  AddNew Add a new blank row to the data source  EndEdit Save changes to a new or existing row  CancelEdit Abort and changes to a new or existing row  RemoveCurrent Delete the current row

Using a BindingSource  Position/Count Determine current position with the data source  MoveFirst  MoveLast  MoveNext  MovePrevious Change the current position within the data source

Parameterized Queries  We can customize a DataSet by providing parameters to modify the query  Add Query from smart tag menu of a bound control  Parameters can be introduced by modifying the WHERE clause  Parameter values are prefixed

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  Drag Customers table onto a form  Update Fill to append ‘%’ (wildcard)  ToolStrip is added to provide parameter  Examine Fill button’s Click event

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 strip CancelEdit() on the customersBindingSource

Navigation Tool Strip  A ToolStrip can be used to add and update rows in the data source customersBindingSource.AddNew(); customersBindingSource.EndEdit(); customersBindingSource.CancelEdit(); customersBindingSource.RemoveCurrent();

DataViewGrid Control  Smart tag allows you to modify commonly used properties  Columns can be added, moved, or removed Remove ID columns Columns still exist in the DataSet  Column content can be formatted using DefaultCellStyle

Master-Detail Relationships  One-to-many relationship between tables  One customer has many invoices

Code Practice  View customer invoices based on the selection of a customer record  Populate DataGridView with customer entries  Populate DataGridView with invoice entries  Create CustomerInvoice DataSet  Customers uses Detail View  Drag Customers onto Form  Drag Customers.Invoices onto Form  Examine DataSource/DataMember on grid view and invoicesBindingSource

Why create our own?  Place data objects into a shared library  We’re not using a form  Separates database code from UI code  Start with an empty console application

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;

Using Our Own Commands SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM Customers"; cmd.CommandType = CommandType.Text; cmd.Connection = cxn; SqlDataReader r = cmd.ExecuteReader();

Parameters in Commands  Add parameters to SQL statements SELECT * FROM Customers WHERE STATE = 'VA' SELECT * FROM Customers WHERE STATE is a SQL variable representing the state

Create the Parameters SqlParameter stateParam = new SqlParameter(); stateParam.ParameterName = stateParam.Value = some_local_variable; cmd.Parameters.Add(stateParam); value);

SQL Injection  Don’t do this… string cmd = "SELECT * FROM Customers WHERE Name=" + value;  Especially if value is user-entered data, such as: “John; DROP TABLE Customers;”

Executing Commands SqlDataReader r = cmd.ExecuteReader(); List customers = new List (); while (r.Read()) { Customer c = new Customer();... customers.Add(c); } r.Close(); cxn.Close();

Other Commands object result = cmd.ExecuteScalar(); // Cast result to expected type cmd.ExecuteNonQuery();

Chapter 20-1 Exercise  MMABooksDB  CustomerDB GetCustomer – ExecuteReader, exceptions AddCustomer – current ID UpdateCustomer – concurrency, ExecuteNonQuery  StateDB Notice exception handling  frmAddModifyCustomer Notice DataSource for states

Disposable Objects  IDisposable interface  Single method: Dispose()  Releases unmanaged resources that may be held by an object  Such as a database connection!!

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

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

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

Open/Close Connections  ADO.NET uses “connection pooling” to optimize opening and closing connections to the database  cxn.Open() and cxn.Close() are using connections from the connection pool that share the same connection string  ADO.NET manages the actual connection to the database  us/library/8xx3tyca(v=vs.110).aspx us/library/8xx3tyca(v=vs.110).aspx

Think of it like this… class SqlConnectionPool { public SqlConnection Open(string cxnStr) { if (mPool.Contains(cxnString)) { return mPool[cxnString]; } // Create a new connection... }

And… class SqlConnectionPool { public void CheckIdle() { foreach (cxn in mPool) { if (cxn.IsIdle()) { cxn.ReallyClose(); mPool.Remove(cxn); }

DataSets in Class Libraries  Create a DataSet in a class library  Specify DataSet Modifier property public or internal?  Add the library as a reference from another project  Select “Referenced DataSets” when adding a DataSet control to a form  Add a BindingSource  Add form controls and bind them to the BindingSource

Slow Start Times?  012/10/18/an-easy-solution-for- improving-app-launch-performance.aspx 012/10/18/an-easy-solution-for- improving-app-launch-performance.aspx  us/magazine/cc aspx us/magazine/cc aspx  us/library/cc656914(v=vs.110).aspx us/library/cc656914(v=vs.110).aspx

Designer Walkthrough

Summary  MenuStrip w/ defaults  ToolStrip w/ defaults  StatusStrip  View Menu Toggles  PerformClick()  ToolStripContainer w/ docking  ContextMenuStrip  SplitContainer  ErrorProvider