Presentation is loading. Please wait.

Presentation is loading. Please wait.

Disconnected Data Applications: using Datasets, XML and Transactions.

Similar presentations


Presentation on theme: "Disconnected Data Applications: using Datasets, XML and Transactions."— Presentation transcript:

1 Disconnected Data Applications: using Datasets, XML and Transactions

2 Overview Adding ADO.NET Objects to and Configuring ADO.NET Objects in a Windows Forms Application Accessing and Modifying Data by Using DataSets Binding Data to Controls Filtering and Sorting Data Resolving Data Conflicts Using Transactions

3 Adding ADO.NET Objects to and Configuring ADO.NET Objects in a Windows Forms Application ADO.NET Objects What Is a DataSet? What Is a Typed DataSet? How to Add ADO.NET Objects to and Configure ADO.NET Objects in a Windows Forms Application Demo: Adding ADO.NET Objects to and Configuring ADO.NET Objects in a Windows Forms Application

4 ADO.NET Objects Data Source DataAdapter DataTable DataSet DataAdapter Fill Update Fill Connection UpdateCommand SelectCommand UpdateCommand

5 What Is a DataSet? Datasets can include multiple DataTables Relationships between tables are represented using DataRelations Constraints enforce primary and foreign keys Use the DataRow and DataColumn to access values in Tables DataTable DataColumn DataRow DataRelation

6 What Is a Typed DataSet? Typed datasets Derive from the base DataSet class Provide type checking at compile time Provide faster access to tables and columns in the dataset Generated from XML Schema (.xsd) files by using the XSD.exe tool To access tables and columns Typed dataset Untyped dataset PubsDataSet.Tables( " Titles " ); PubsDataSet.Titles;

7 How to Add ADO.NET Objects to and Configure ADO.NET Objects in a Windows Forms Application Drag an OleDbDataAdapter or SqlDataAdapter object from the Toolbox to a form Specify connection and SQL command information Select the adapter or adapters that will be used to transfer data between the data source and the dataset On the Data menu, choose Generate Dataset Select New and then specify a name for the new dataset

8 Demo: Adding ADO.NET Objects to and Configuring ADO.NET Objects in a Windows Forms Application Add and configure a SQLConnection object on a Windows Form Add and configure a SQLDataAdapter control on a Windows Form Generate the dataset

9 Accessing and Modifying Data by Using DataSets How to Populate a Dataset How to Update Data in a Dataset How to Update Data to a Data Source Demo: Populating and Updating DataSets How to Create Database Schema on the Client Demo: Creating Database Schema by Using the XML Schema Designer How to Read and Write XML Data into a DataSet

10 How to Populate a Dataset Use the DataAdapter object to fill the dataset SqlDataAdapter storesSQLDataAdapter; SqlCommand storesSelectSQLCommand; storesSelectSQLCommand.CommandText = "SELECT * FROM stores"; storesSelectSQLCommand.Connection = SqlConnection1; storesSQLDataAdapter.SelectCommand = storesSelectSQLCommand; storesSQLDataAdapter.Fill(storesDataSet.Tables["Stores"]); SqlDataAdapter storesSQLDataAdapter; SqlCommand storesSelectSQLCommand; storesSelectSQLCommand.CommandText = "SELECT * FROM stores"; storesSelectSQLCommand.Connection = SqlConnection1; storesSQLDataAdapter.SelectCommand = storesSelectSQLCommand; storesSQLDataAdapter.Fill(storesDataSet.Tables["Stores"]);

11 How to Add a Record to the DataSet Untyped datasets Typed datasets DataRow newDataRow = pubsDataSet.Tables["Titles"].NewRow(); newDataRow["title"] = "New Book"; newDataRow["type"] = "business"; pubsDataSet.Tables["Titles"].Rows.Add(newDataRow); DataRow newDataRow = pubsDataSet.Tables["Titles"].NewRow(); newDataRow["title"] = "New Book"; newDataRow["type"] = "business"; pubsDataSet.Tables["Titles"].Rows.Add(newDataRow); allData.darbiniekiRow dR = allDataSet.darbinieki.AdddarbiniekiRow(“John”,”B”,”JB@JB.LV”,null,”Admin”); allData.darbiniekiRow dR = allDataSet.darbinieki.AdddarbiniekiRow(“John”,”B”,”JB@JB.LV”,null,”Admin”);

12 Modifying Data in a Table The BeginEdit method of DataRow class Disables the raising of events and exceptions EndEdit and CancelEdit methods of DataRow class Enable the raising of events and exceptions How to modify data in a table Dim drEmployee As DataRow = dtEmployees.Rows(3) drEmployee.BeginEdit() drEmployee("FirstName") = "John" drEmployee("LastName") = "Smith" drEmployee.EndEdit()

13 How to Delete a Record The Remove method of the DataRowCollection class Completely removes the row from the collection Example: dtEmployees.Rows.Remove(drEmployee) The Delete method of the DataRow class Marks the row as deleted Hidden, but still accessible if necessary Example: drEmployee.Delete

14 What Are the RowState and RowVersion Properties? RowState property of a DataRow Added, Deleted, Detached, Modified, Unchanged DataViewRowState enumeration Used with a DataView to filter rows of a certain state CurrentRows, OriginalRows, and so on DataRowVersion enumeration is used when retrieving values using the Item property Current, Default, Original, Proposed HasVersion method of a DataRow AcceptChanges and RejectChanges methods

15 How to Update Data to a Data Source SqlCommand insertTitlesCommand = new SqlCommand ("Insert titles (title_id, title, type) values (@title_id,@title,@type)"); insertTitlesCommand.Parameters.Add ("@title_id", SqlDbType.VarChar, 6, "title_id"); insertTitlesCommand.Parameters.Add ("@title", SqlDbType.VarChar, 80, "title"); insertTitlesCommand.Parameters.Add ("@type", SqlDbType.Char, 12, "type"); titlesSQLDataAdapter.InsertCommand = insertTitlesCommand; titlesSQLDataAdapter.Update(pubsDataSet, "titles"); SqlCommand insertTitlesCommand = new SqlCommand ("Insert titles (title_id, title, type) values (@title_id,@title,@type)"); insertTitlesCommand.Parameters.Add ("@title_id", SqlDbType.VarChar, 6, "title_id"); insertTitlesCommand.Parameters.Add ("@title", SqlDbType.VarChar, 80, "title"); insertTitlesCommand.Parameters.Add ("@type", SqlDbType.Char, 12, "type"); titlesSQLDataAdapter.InsertCommand = insertTitlesCommand; titlesSQLDataAdapter.Update(pubsDataSet, "titles"); Explicitly specifying the updates

16 Demo: Populating and Updating DataSets Populate the dataset Update the database

17 Defining Data Relationships Using Foreign Key Constraints to Restrict Actions How to Create a Foreign Key Constraint What Is a DataRelation Object? How to Create a DataRelation Object How to Navigate Related DataTables

18 Using Foreign Key Constraints to Restrict Actions A ForeignKeyConstraint enforces referential integrity If the EnforceConstraints property of a DataSet is True Restricting actions performed in related tables DeleteRule and UpdateRule properties ActionActionDescriptionDescription Cascade Deletes or updates related rows. This is the default. SetNull Sets values in related rows to DBNull. SetDefault Sets values in related rows to the DefaultValue. None No action is taken, but an exception is raised.

19 How to Create a Foreign Key Constraint Use Properties window DataSet must have at least two tables Parent table must have a primary key Add a ForeignKeyConstraint to the child table Choose the matching columns Choose Update and Delete rules Write code

20 What Is a DataRelation Object? Definition A DataRelation object defines a navigational relationship, NOT a constraint relationship Used by presentation objects (for example, a DataGrid) to allow easier navigation (for example, “drill down” capability from parent rows to child rows) Used by expression columns to calculate aggregates A DataSet has a Relations collection

21 How to Create a DataRelation Object Use the Properties window Or, write code dsNorthwind.Relations.Add( _ "FK_CustomersOrders", _ dtCustomers.Columns("CustomerID"), _ dtOrders.Columns("CustomerID"), _ True) ' create a ForeignKeyConstraint too

22 How to Navigate Related DataTables The GetChildRows method of the DataRow Pass a DataRelation name as the parameter Example: Dim drCustomer As DataRow Dim drOrder As DataRow For Each drCustomer In _ dsNorthwind.Tables("Customer").Rows For Each drOrder In drCustomer.GetChildRows( _ "FK_CustomersOrders") ' process row Next

23 How to Create Database Schema on the Client XML Schema (.xsd) files enforce data integrity on the client Use the XML Designer to create and modify XML Schema files 1. Determine the schema design 2. On the Project menu, click Add New Item 3. Add the schema 4. Create the schema

24 Demo: Creating and Using Data Relationships In this demonstration, you will see how to create a DataRelation between tables in a DataSet and how to use it in a form.

25 How to Read and Write XML Data into a DataSet Use ReadXML to load data from a file or stream Write data and schema information from a DataSet to a file or stream by using the WriteXML method purchaseDataSet.ReadXml ("C:\\sampledata\\PurchaseData.xml", XmlReadMode.IgnoreSchema); purchaseDataSet.ReadXml ("C:\\sampledata\\PurchaseData.xml", XmlReadMode.IgnoreSchema); purchaseDataSet.WriteXml ("C:\\sampledata\\CurrentOrders.xml", XmlWriteMode.IgnoreSchema); purchaseDataSet.WriteXml ("C:\\sampledata\\CurrentOrders.xml", XmlWriteMode.IgnoreSchema);

26 Binding Data to Controls How to Perform Simple Binding by Using the DataBindings Property How to Perform Complex Data Binding by Using the DataBound Windows Forms Controls How to Maintain the Currency of a Control by Using CurrencyManager Demo: Binding Controls to Data and Maintaining the Currency of a Control by Using CurrencyManager

27 How to Perform Simple Binding by Using the DataBindings Property txtCustomerAddress.DataBindings.Add("Text", dsNorthwindData1.Customers, "Address"); txtCustomerCity.DataBindings.Add("Text", dsNorthwindData1.Customers, "City"); txtCustomerAddress.DataBindings.Add("Text", dsNorthwindData1.Customers, "Address"); txtCustomerCity.DataBindings.Add("Text", dsNorthwindData1.Customers, "City"); Property of the control to which data is bound Column in the table Table from the data source To use the DataBindings Collection to bind a control to a data source, set the DataBinding property of the control to the data source

28 How to Perform Complex Data Binding by Using the DataBound Windows Forms Controls Complex data binding Bind a control property to a data table Use with combo boxes, list boxes, data grids Can bind controls to DataSets, Arrays, and ArrayLists Complex databinding at design time Set the DataSource and DataMember properties Complex databinding at run time DataGrid1.DataSource = productsDataSet; DataGrid1.DataMember = "Products"; DataGrid1.DataSource = productsDataSet; DataGrid1.DataMember = "Products";

29 How to Maintain the Currency of a Control by Using CurrencyManager Datagrid Data Source 1 Data Source 2 Currency Manager1 TextBox1 TextBox2 Currency Manager2 CurrencyManager cm; cm = (CurrencyManager)this.BindingContext[pubsDataSet, "Authors"]; cm.Position += 1; CurrencyManager cm; cm = (CurrencyManager)this.BindingContext[pubsDataSet, "Authors"]; cm.Position += 1;

30 Demo: Binding Controls and Maintaining the Currency of a Control by Using CurrencyManager Bind controls to columns in the dataset at design time Bind controls to columns in the dataset at run time maintain the currency of a control by using CurrencyManager

31 Sorting and Filtering How to use the Select method What Is a DataView Object? How to Define a DataView How to Use a DataView at Design Time

32 How to Use the Select Method DataTables have a Select method Gets an array of DataRow objects that match the filter in the order of the sort, and that match the specified state Three optional parameters Filter expression, for example, "City='London'" Sort, for example, "CompanyName ASC" DataViewRowState, for example, Deleted

33 What Is a DataView Object? ServerData Store Database Connection Stored procedure DataSet DataTable Windows and Web controls DataView

34 How to Define a DataView Creating a DataView by using form controls Creating a DataView programmatically Dim dvProducts As New _ DataView(dsNorthwind.Tables("Products")) dvProducts.Sort = "UnitPrice" dvProducts.RowFilter = "CategoryID > 4" grdProducts.DataSource = dvProducts Applying a DataView to a DataTable dvProducts.Table = _ dsNorthwind.Tables("Products")

35 How to Use a DataView at Design Time DataViews allow sorting and filtering at design time A DataView cannot span multiple DataTables, unlike the View object in SQL Server Use presentation-level objects instead (for example, the DataGrid control, report designers, and so on) Every DataTable has a DefaultView property

36 Demo: Sorting and Filtering data Filter data with a Select method Filter and sort data by using dataview object

37 Configuring a DataAdapter to Update the Underlying Data Source How Does a DataSet Track Changes? What Are the Data Modification Commands? How to Set the Data Modification Commands Using the Data Adapter Configuration Wizard

38 How Does a DataSet Track Changes? Each DataRow has a RowState property Indicates the status of each row Added, Deleted, Detached, Modified, Unchanged The DataSet maintains two copies of data for each row Original version Current version

39 What Are the Data Modification Commands? A SqlDataAdapter or OleDbDataAdapter object has command properties that are themselves command objects that you can use to modify data at the data source InsertCommand UpdateCommand DeleteCommand

40 How to Set the Data Modification Commands Using the Data Adapter Configuration Wizard You can create data modification commands by using the Data Adapter Configuration Wizard The wizard can generate the commands in three different ways: By using SQL statements By creating new stored procedures By using existing stored procedures

41 Persisting Changes to a Data Source How the DataAdapter’s Update Method Modifies the Underlying Data Source When to Use the GetChanges Method of a DataSet Object How to Merge Changes into the DataSet How to Update a Data Source by Using a DataSet How to Accept Changes into the DataSet

42 How the DataAdapter’s Update Method Modifies the Underlying Data Source Determines, which data modification operations have been carried out Executes appropriate commands (insert, update or delete) for each added, modified or deleted row Returns status information for each operation

43 When to Use the GetChanges Method of a DataSet Object Use the GetChanges method when you need to give the changes to another class for use by another object Code example If dsCustomers.HasChanges(DataRowState.Modified) Then Dim dsTemp As DataSet dsTemp = dsCustomers.GetChanges(DataRowState.Modified) DataGrid1.DataSource = dsTemp.Tables(0).DefaultView End If Use the GetChanges method to get a copy of a DataSet that contains all changes made to the DataSet Since it was loaded, or Since the last time the AcceptChanges method was called.

44 How to Merge Changes into the DataSet Use the Merge method to merge two DataSets – an original, and one containing only the changes to the original Code example aDataSet.Merge(anotherDataSet) The two merged DataSets should have similar schemas

45 Lesson: How to Handle Conflicts What Conflicts Can Occur? How to Detect Conflicts How to Resolve Conflicts

46 What Conflicts Can Occur? Disconnected applications use optimistic concurrency Releases database locks between data operations Data conflicts can occur when you update the database Another application or service might have already changed the data Examples Deleting a previously deleted row Changing a previously changed column

47 How to Detect Conflicts The Data Adapter Configuration Wizard can generate SQL statements to detect conflicts When you update the database: Data modification commands compare the current data in the database against your original values Any discrepancies cause a conflict error

48 How to Resolve Conflicts Use the HasErrors property to test for errors Test a DataSet, DataTable, or DataRow Choose one of these strategies to resolve conflicts : “Last in wins” Retain conflicting rows in your DataSet so you can update the database again later Reject conflicting rows and revert to the original values in your DataSet Reject conflicting rows and reload the latest data from the database

49 Demo: How to Update a Data Source by Using a DataSet Configuring the dataadapter using dataadapter wizard Configuring parameters for dataadapter commands – using optimistic concurrency Using GetChanges method Resolving conflicts

50 Using Transactions What Is a Transaction? How to Manage Transactions Using SQL Statements How to Manage Transactions Using ADO.NET What Are Isolation Levels?

51 What Is a Transaction? A transaction is a set of related tasks that either succeed or fail as a unit Two types of transactions Local transactions Distributed transactions

52 How to Manage Transactions Using SQL Statements SQL transaction statements BEGIN TRANS, COMMIT TRANS, ROLLBACK TRANS Code example BEGIN TRANS DECLARE @orderDetailsError int, @productError int DELETE FROM "Order Details" WHERE ProductID=42 SELECT @orderDetailsError = @@ERROR DELETE FROM Products WHERE ProductID=42 SELECT @productError = @@ERROR IF @orderDetailsError = 0 AND @productError = 0 COMMIT TRANS ELSE ROLLBACK TRANS

53 How to Manage Transactions Using ADO.NET XxxConnection – for example, SqlConnection BeginTransaction XxxTransaction – for example, SqlTransaction Commit Rollback

54 What Are Isolation Levels? Examples of concurrency problems Guidelines for setting the isolation level Code example trans = cnNorthwind.BeginTransaction( _ IsolationLevel.Serializable) Support for isolation levels is dependent on which database you use


Download ppt "Disconnected Data Applications: using Datasets, XML and Transactions."

Similar presentations


Ads by Google