1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25.

Slides:



Advertisements
Similar presentations
1 Northwind Traders Order Entry. 2 Northwind Traders Call Center Add an Order Entry capability to the Northwind Traders Call Center application. Start.
Advertisements

11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
Adding a database to web service Add a database – Service->Add new item->SQL server database Add table to database – Server explorer->tables->Add new table.
Let’s try Oracle. Accessing Oracle The Oracle system, like the SQL Server system, is client / server. For SQL Server, –the client is the Query Analyser.
J4www/jea Week 3 Version Slide edits: nas1 Format of lecture: Assignment context: CRUD - “update details” JSP models.
ASP.NET Programming with C# and SQL Server First Edition
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
1 Web Services Visual C# 2008 Step by Step Chapter 30.
From C++ to C#. Web programming The course is on web programming using ASP.Net and C# The course is on web programming using ASP.Net and C# ASP.Net is.
Stored Procedures Dr. Ralph D. Westfall May, 2009.
1 Working with MS SQL Server II. 2 The sqlcmd Utility Command line utility for MS SQL Server databases. Previous version called osql Available on classroom.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
1 Project 6: Cats in Tree. 2 Project 3: Cats in Tree In this project you will Create a class definition for a Cat class. Populate a BST with Cat information.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 Working with MS SQL Server. 2 Objectives You will be able to Use Visual Studio for GUI based interactive access to a Microsoft SQL Server database.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
JavaScript & jQuery the missing manual Chapter 11
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
11 Updating a Database Table Textbook Chapter 14.
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.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
1 Working with Menus and Dialog Boxes. 2 Objectives You will be able to Create and edit menus for Windows Forms applications. Write code to handle menu.
1 Databound Controls. 2 Objectives You will be able to use design time data binding to display and update SQL Server database data without writing any.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
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.
1 Working with MS SQL Server Textbook Chapter 14.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with MSSQL Server Code:G0-C# Version: 1.0 Author: Pham Trung Hai CTD.
1 Joining Tables in Queries. 2 Objectives You will be able to Write SQL queries that use Join operations to retrieve information from multiple tables.
.Net and Web Services Security CS795. Web Services A web application Does not have a user interface (as a traditional web application); instead, it exposes.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
MySQL Connection using ADO.Net Connecting to MySQL from.NET Languages.
CIS 338: Using Queries in Access as a RecordSource Dr. Ralph D. Westfall May, 2011.
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.
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
ASP.NET The Clock Project. The ASP.NET Clock Project The ASP.NET Clock Project is the topic of Chapter 23. By completing the clock project, you will learn.
ASP.NET Rina Zviel-Girshin Lecture 5
1 Project 7: Northwind Traders Order Entry. 2 Northwind Order Entry Extend the Select Customer program from Project 6 to permit the user to enter orders.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
Database Handling, Sessions, and AJAX. Post Back ASP.NET Functionality The IsPostBack method in ASP.NET is similar to the BlackBerry.refresh method –IsPostBack.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Module 3: Performing Connected Database Operations.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
Command Object’s ExecuteNonQuery Method ISYS 512.
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.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
HNDIT Rapid Application Development
Database Connectivity with ASP.NET. 2 Introduction Web pages commonly used to: –Gather information stored on a Web server database Most server-side scripting.
ADO.NET FUNDAMENTALS BEGINNING ASP.NET 3.5 IN C#.
Coding ADO.NET Objects: Connection, Command, DataReader.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
1 Database Programming with ADO.NET Kashef Mughal.
Using ADO.Net to Build a Login System Dr. Ron Eaglin.
1 Project 4 Address Lookup. Project 4 Write an ASP.NET app that permits users to retrieve addresses from a potentially large list of addresses. There.
11 User Controls Beginning ASP.NET in C# and VB Chapter 8.
1 Working with MS SQL Server Beginning ASP.NET in C# and VB Chapter 12.
Introduction to Database C# MySQL onnect-C-to-MySQL 1.
1 Project 5 Eyeglass Rx User Control. Eyeglass Rx Earlier in the semester we looked at an eyeglass prescription as an example of an HTML table. 2.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
C# MySQL onnect-C-to-MySQL 1.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 11 Creating Web Applications and Writing Data to a Database.
ASP.NET Programming with C# and SQL Server First Edition
Stored Procedures Dr. Ralph D. Westfall May, 2011.
SQL commands from C# and ASP.net
MySQL Connection using ADO.Net
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Presentation transcript:

1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25

2 Getting Started Download and expand the Northwind Product Browser as we left it last class. Downloads/2011_03_31_Low_Level_ADO_Operations/ Downloads/2011_03_31_Low_Level_ADO_Operations/ File Northwind_Product_Browser.zip Build and run

3 SqlDataReader Class SqlDataReader provides two ways for us to access various columns of the current query result: Column name Position

4 Access by Column Name We have seen one example of the name based method Form1.cs, btnGetData_Click while (rdr.Read()) { String Product_Name = (String)rdr["ProductName"]; Product_List.Add(Product_Name); }

5 Access by Position We could have written: while (rdr.Read()) { String Product_Name = rdr.GetString(0); Product_List.Add(Product_Name); } Get column 0 of the current query result, as a String. No typecast necessary.

6 Reading Other Datatypes The SqlDataReader class has a postion based method for each datatype. GetString() GetInt32() GetInt16() GetDecimal() GetBoolean() … You have to use the right one for the data type of column you want to retrieve. But then you don’t have to typecast the result.

7 Product Browser Let’s extend the Product Browser to display more information about each product.

8 Table Products Contents

9 Table Products Definition

10 Product_Information Form Extended

11 Add Class Product using System; namespace Product_Browser { class Product { private String product_name; private int product_id; private decimal unit_price; private int units_in_stock; private bool discontinued ; }

12 Define Properties for Product Fields Select field. Refactor > Encapsulate Field

13 Product_List In Form1.cs modify Product_List to be a list of Products. List Product_List = new List ();

14 Changes to Form1.cs New SQL command in Form1.cs, Get_SqlDataReader : SqlCommand1.CommandText = "SELECT * FROM Products ORDER BY ProductName";

15 Recall Definition of Table Products

16 Update btnGetData_Click while (rdr.Read()) { Product p = new Product(); p.Product_name = rdr.GetString(1); p.Product_id = rdr.GetInt32(0); if (rdr.IsDBNull(5)) { p.Unit_price = 0.00M; } else { p.Unit_price = rdr.GetDecimal(5); } Must check any column that could be Null. A Decimal literal (M for “money”)

17 More Compactly while (rdr.Read()) { Product p = new Product(); p.Product_name = rdr.GetString(1); p.Product_id = rdr.GetInt32(0); p.Unit_price = rdr.IsDBNull(5) ? 0.0M : rdr.GetDecimal(5); p.Units_in_stock = rdr.IsDBNull(6) ? 0 : rdr.GetInt16(6); p.Discontinued = rdr.GetBoolean(9); Product_List.Add(p); }

18 Changes to Product_Information.cs Update references to List to be List. Update Display_Current_Record as shown on next slide.

19 Chanages to Display_Current_Record() private void Display_Current_Record() { Product p = (Product) Product_List[Current_Record_Number]; tbProductName.Text = p.Product_name; tbProductID.Text = p.Product_id.ToString(); tbUnitPrice.Text = p.Unit_price.ToString("C"); tbUnitsInStock.Text = p.Units_in_stock.ToString(); cbDiscontinued.Checked = p.Discontinued; tbRecordNumber.Text = "Record " + (Current_Record_Number + 1) + " of " + Product_List.Count; Update_Buttons(); } Format as currency Build and run.

20 Compile Error!

21 Class Product We have to declare class Product as “public”.

22 Class Product Try again to build and run.

23 Enhanced Product Browser in Action End of Section

24 A Better Solution Forms should be limited to just UI functions. Knowledge of how products are represented in the database is better confined to a separate class. Separation of responsibilities. Let class Product be responsible for knowledge of how to initialize a product object using results of a database query. Anyone else who needs product info should use the Product class.

25 Class Product We will add a constructor that takes the query result as a parameter. Initializes object with data from a SqlDataReader. Add using System.Data.SqlClient;

26 Class Product Constructor // This constructor initializes a product using a query result. public Product(SqlDataReader rdr) { Product_name = rdr.GetString(1); Product_id = rdr.GetInt32(0); Unit_price = rdr.IsDBNull(5) ? 0.0M : rdr.GetDecimal(5); Units_in_stock = rdr.IsDBNull(6) ? 0 : rdr.GetInt16(6); Discontinued = rdr.GetBoolean(9); } Copy from btnGetData_Click()

27 Class Products Let another class be responsible for knowledge of how to do the query. Static class Products will hold a static method Get_Products. Code previously included in Form1 Make username and password parameters. Return List No constructor. The class cannot be instantiated. Just a home for the static Get_Products method.

28 Get_Products() public static List Get_Products(String Username, String Password) { List Product_List = new List (); SqlDataReader rdr; SqlConnection SqlConnection1; SqlConnection1 = Setup_Connection(Username, Password); rdr = Get_SqlDataReader(SqlConnection1); while (rdr.Read()) { Product p = new Product(rdr); Product_List.Add(p); } rdr.Close(); SqlConnection1.Close(); return Product_List; }

29 Setup_Connection() private static SqlConnection Setup_Connection(String Username, String Password) { String connection_string = "server=scorpius.eng.usf.edu; " + "database=Northwind;" + "User=" + Username + "; " + "Password=" + Password; SqlConnection SqlConnection1 = new SqlConnection(connection_string); SqlConnection1.Open(); return SqlConnection1; }

30 Get_SqlDataReader() private static SqlDataReader Get_SqlDataReader( SqlConnection SqlConnection1) { SqlCommand SqlCommand1 = new SqlCommand(); SqlCommand1.CommandText = "SELECT * FROM Products ORDER BY ProductName"; SqlCommand1.Connection = SqlConnection1; return SqlCommand1.ExecuteReader(); }

31 Form1.cs private void btnGetData_Click(object sender, EventArgs e) { try { Product_List = Products.Get_Products(tbUserName.Text, tbPassword.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } // Instantiate the form that displays product information. Product_Information pif = new Product_Information(Product_List); this.Hide(); pif.ShowDialog(); this.Close(); }

32 A Better Solution The functionality is unchanged from previous version. Class Form1 is now simpler. Limited to UI functions. Class Products is responsible for interfacing with the database. Class Product is responsible for internal representation of products. This is an example of refactoring.

33 Assignment Before next class: Explore the Northwind Traders database. Familiarize yourself with its tables. Browse with Visual Studio or Management Studio Express. Try some queries. If you haven't already done so, download and read the Northwind Traders Call Center concept document from the Downloads area of the class web site: Downloads/Northwind_Call_Center/ File Concept_v1_3.doc Downloads/Northwind_Call_Center/ End of Presentation