Introduction to ADO.Net Malek Kemmou CEO Arrabeta

Slides:



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

ADO.NET: Working in Disconnected Environment Sergey Baidachni MCT, MCSD, MCDBA.
ADO vs ADO.NET ADOADO.NET Client/server coupledDisconnected collection of data from data server Uses RECORDSET object (contains one table) Uses DATASET.
Chapter 10 ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a programming interface to access data in a database.
Introduction to Database Processing with ADO.NET.
ADO. NET. What is “ADO.Net”? ADO.Net is a new object model for dealing with databases in.Net. Although some of the concepts are similar to the classical.
.NET Mobile Application Development Data in Distributed Systems Accessing Data with.NET.
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.
Objective In this session we will discuss about : What is ADO. NET ?
ADO.NET – part II August 2004 [ Marmagna Desai]. CONTENTS ADO vs ADO.NET ADO.NET – Managed providers Connecting to Database SqlConnection Selecting Database.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
Visual Studio ®.NET Data with XML Carlotta Eaton ( Associate Professor of IST New River Community College Slides by Microsoft Modified.
ADO.NET Tools and Wizards. Slide 2 Data Sources Window (Introduction) Use the Data Sources window to Establish a connection Create bound control instances.
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.
Intro to C#.net and EF Ilan Shimshoni. The Three Faces of ADO.NET The connected layer – Directly connecting to the DB The disconnected layer – Using datasets.
Overview of ADO.NET with the.NET Framework Scalable Development, Inc. Building systems today that perform tomorrow.
1 ASP.NET ASP.NET Rina Zviel-Girshin Lecture 4. 2 Overview Data Binding Data Providers Data Connection Data Manipulations.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
IT533 Lectures DataBinding Controls. Installations Microsoft® SQL Server® 2008 Express Download the sample MDF files from the course’s web site CodeWeek3.zip.
CIS 375—Web App Dev II ASP.NET 10 Database 2. 2 Introduction to Server-Side Data Server-side data access is unique in that Web pages are basically ___________.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
.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.
Introduction to Database Development Using Borland Data Providers 2128 Martin Rudy.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
Moving from Microsoft ® ADO 2.X To ADO.NET Jackie Goldstein Renaissance Computer Systems Ltd. MSDN Regional Director, Israel Prerequisites.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
ASP.NET Rina Zviel-Girshin Lecture 5
Session 8: ADO.NET. Overview Overview of ADO.NET What is ADO.NET? Using Namespaces The ADO.NET Object Model What is a DataSet? Accessing Data with ADO.NET.
Module 7: Accessing Data by Using ADO.NET
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Introduction to ADO.NET ADO.NET - Lesson 01  Training time: 10 minutes  Author:
Module 4: Building DataSets. Overview Working in a Disconnected Environment Building DataSets and DataTables Binding and Saving a DataSet Defining Data.
Presented by Joseph J. Sarna Jr. JJS Systems, LLC
An Introduction to ADO.Net Marmagna Desai.NET Seminar, Fall-2003.
1 Data Classes- DataView DataGridView Control. Objectives 2  Data Class  DataAdapter  DataReader  DataSet  DataTable  DataView  DataGridView Control.
C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 – May 2007 Chair of Software Engineering Lecture 10: Database Lisa (Ling) Liu.
Why ADO.NET Not your father’s Data Access.
Mauricio Featherman, Ph.D. Washington St. University
DEV383 The ADO.NET DataSet and You Jackie Goldstein General Manager Renaissance Computer Systems
Accessing Data with Microsoft Visual C# Applications.
Why ADO.NET Not your father’s Data Access.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
Module 3: Working with Local Data. Overview Using DataSets Using XML Using SQL Server CE.
1 11/15/05CS360 Windows Programming ADO.NET Continued.
DataSets Demystified. Who I am Shawn Wildermuth Senior Consultant with Magenic Technologies ( C# MVP INETA.
Module 4 Introduction ADO.NET.
SQLXML XML Technology For SQL Server Brian Moore Developer and Platform Strategy Group Microsoft Corporation.
C# .NET Software Development
Active Data Objects Using.Net ADO.Net Farooq Ahmed Amna Umber Summayya Shehzad.
Module 5 Data Classes DataView – DataGridView Control 1.
DAT200 Microsoft® ADO.NET for ADO Classic Developers: Introducing ADO.NET Jackie Goldstein Renaissance Computer Systems
Module 2: Using ADO.NET to Access Data. Overview ADO.NET Architecture Creating an Application That Uses ADO.NET to Access Data Changing Database Records.
Data Access. ADO.NET ADO.NET is the primary library for building database solutions within the.NET Framework. ADO.NET does not replace ADO. ADO and OLEDB.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
.NET Data Access and Manipulation
DAT 390 Advanced ADO.NET Programming Techniques Jackie Goldstein Renaissance Computer Systems
ASP.NET Programming with C# and SQL Server First Edition
Introduction to ADO.NET
Introduction to Database Processing with ADO.NET
Introduction to Database Processing with ADO.NET
ADO.NET and Stored Procedures
ADO.NET Framework.
ADO.Net and Stored Procedures
Tonga Institute of Higher Education
Chapter 10 ADO.
PROG Advanced Web Apps 4/13/2019 Programming Data Pages Wendi Jollymore, ACES.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
Presentation transcript:

Introduction to ADO.Net Malek Kemmou CEO Arrabeta

bioAdapter.Fill(bio_DataSet); repeater1.DataBind(); CEO Arrabeta (consulting firm based in Casablanca Morocco) Newtelligence Alliance Partner Senior Consultant and Senior Trainer Solutions Architecture, integration, interoperability Microsoft Regional Director for Middle East and Africa Ineta MEA Speaker Bureau Speaker at many conferences and events (TechEd, NDC, MDC, DevDays, DevEssentials …)

Agenda Overview of Data Access in.Net Fetching Data Processing Data Data as XML Tips & Tricks

What is ADO.NET? Managed Code (.NET) Data Access Methodology Complete Integration with the.NET Framework Improved support for the disconnected business model Improved integration with XML Explicit control of Data Access behaviors for.NET applications

Introducing ADO.NET Part of the.NET framework, ADO.NET was built with the new world of XML, disconnected data, web and HTTP in mind Is a rewrite of ADO for the.NET framework –Not a replacement of ADO for COM developers –ADO.NET is a natural evolution of ADO, built around n-tier development and architected with XML at its core

Overview of Data in.Net.NET Data Provider DataReader Command Connection Sync Controls, Design Tools, Code Generation … DataSet XmlReader XSL/T, X-Path, … XMLDataDocument DataAdapter

Fetching Data Connected Model –Create a connection –Open Connection –Execute Commands –Obtain Results –Process Rows –Close Connection –Data Bind

Create & open a Connection C# SqlConnection cnn = new SqlConnection(“Data Source = MyServer; User Id=myUser; password=myPassword”); cnn.Open(); VB.Net Dim cnn as New SqlConnection( (“Data Source = MyServer; User Id=myUser; password=myPassword”) cnn.open

Open a Transaction if needed C# SqlTransaction tnx = cnn.BeginTransaction(); // do some Data Access and processing If (somecondition) tnx.Commit(); Else tnx.Rollback(); VB.Net Dim tnx as SqlTransaction = cnn.BeginTransaction ‘ Do some Data Access and processing If (somecondition) Then tnx.Commit() Else tnx.Rollback() End If

Execute Commands Various types of commands –Insert, Update, Delete, stored procedure, … Optionally transmit parameters SqlCommand cmd = new SqlCommand("DeleteAccount", cnn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = new param.Value = accountID; cmd.Parameters.Add(param); Int32 RowsAffected = cmd.ExecuteNonQuery();

Obtain a Single Value Use ExecuteScalar SqlCommand cmd = new SqlCommand( "Select Balance from Accounts where ” + “AccountID &cnn); Decimal AccountBalance = (Decimal) cmd.ExecuteScalar();

Process Rows Dynamic Processing SqlCommand cmd = new SqlCommand("Select Desc, " +"Amt from Activity where AccountID cnn); SqlDataReader results = cmd.ExecuteReader(); While (results.Read()) { Console.Write("Description: " + results.GetString(0)); Console.WriteLine("Amount: " + results.GetDecimal(1)); }

Data Binding (Web Forms) public void Page_Load(Object sender, EventArgs e) { // Créer une SqlCommand et obtenir un DataReader SqlConnection cnn = new SqlConnection("server=localhost;uid=sa;"); cnn.Open(); SqlCommand cmd = new SqlCommand("Select * from customers", cnn); SqlDataReader results = cmd.ExecuteReader(); // Lier les résulats ActivityList.DataSource = results; ActivityList.DataBind(); }

Demo Connected DataAccess from a Web Page

Processing Data Disconnected Model –Fill DataSet –Navigate the DataSet –Update Changes from DataSet –Data Bind –DataSet can be used as cache

DataSet A DataSet is a local buffer of tables, or a collection of disconnected “recordsets” –Keeps track of the relationships between the tables it contains DataSets are an in-memory relational store Exposes a rich programming model –All data is stored in a local cache –Same performance and semantics regardless of whether the data is loaded from a database, loaded from XML, or is generated by the application. No connection! –(Not directly anyway)

DataSets: Tables A DataSet contains a collection of DataTables (the DataTableCollection) –A DataTable represents one table of in-memory data. It contains a collection of columns (the DataColumnCollection) that represents the table's schema A DataTable also contains a collection of rows (the DataRowCollection), representing the data held by the table. It remembers the original state along with current state, tracking the kinds of changes that have occurred.

Fill DataSet from Database Use a DataAdapter SqlCommand selectCommand = new SqlCommand("Select CategoryName from Categories",cnn); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = selectCommand; DataSet categories = new DataSet("Categories"); adapter.Fill(categories);

Navigate the DataSet Navigate the Row Collection of a Table Obtain Rows as an Array Use language expressions as “foreach” foreach(DataRow customer in myDataSet.Tables["Customer"].Rows) { Console.WriteLine("Orders for customer: " + customer["Name"]); foreach(DataRow order in customer.GetChildRows("cust_orders") ) { Console.Write("\t Order ID = " + order["OrderID"]); Console.WriteLine("Amount = " + order["Amount"]); }

Update Changes SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand delete = new SqlCommand("DeleteOrder",cnn); delete.CommandType=CommandType.StoredProcedure; adapter.DeleteCommand = delete; SqlCommand insert = new SqlCommand("AddOrder",cnn); insert.CommandType=CommandType.StoredProcedure; = DateTime.Now; adapter.InsertCommand = insert; SqlCommand update = new SqlCommand("UpdateOrder",cnn); update.CommandType=CommandType.StoredProcedure; adapter.UpdateCommand = update; adapter.Update(ordersTable);

Winforms DataBinding SqlCommand cmd = new SqlCommand("GetAccountInfo", cnn); cmd.CommandType=CommandType.StoredProcedure; DataSet account = new DataSet; DataAdapter adapter = new DataAdapter(cmd); adapter.Fill(account); DataGrid accountGrid = new DataGrid(); accountGrid.SetDataBinding(myDataSet, "AccountList");

Demo A Simple WinForm Working with Data

ADO.NET & XML DataSets and XML –Load/Save XML Data to/From DataSet –Schema can be loaded/saved as XSD –Schema can be inferred from XML Data

Loading XML DataSet ds = new DataSet(); ds.ReadXml("inventory.xml"); DataTable inventory = ds.Tables["Inventory"]; DataRow row = inventory.NewRow(); row["TitleID"]=1; row["Quantity"]=25; inventory.Rows.Add(row); ds.WriteXml("updatedinventory.xml");

Load Schema from XSD myDataSet.ReadXmlSchema(schemaFile); –Complex Types converted to tables –Nested Complex Types converted to child tables –Keys/Constraints converted into unique constraints –Foreign Key Constraints inferred

Inferred Schema If no schema is defined before calling DataSet.ReadXml(), schema is inferred from data General Rules –An element becomes a table if : It is repetitive within its parent or it contains more than one simple content …Otherwise, it becomes a column –Attributes become columns –Relations are created for nested tables Hidden columns are created for the keys Useful for dynamic data binding

Demo DataSets and XML

X/Path And XSL/T Over DataSet XmlDataDocument xmlData = new XmlDataDocument(po); // Requête X/Path XmlNodeList nodes = foreach(XmlNode node in nodes) { DataRow row = xmlData.GetRowFromElement((XmlElement)node); row.Delete(); } // Transformation XSLT XslTransform xsltransform = new XslTransform(); xsltransform.Load("po.xsl"); XmlReader xReader = xsltransform.Transform(xmlData, null);

Tips & Tricks Auto generate Commands for updating DataSet Refreshing DataSet data Managing and processing errors when updating a DataSet Working with row versions and changes Passing null values Guarantee connection closes when DataReader is finished Inserting primary keys

Auto Generate Commands for Updating DataSet Use CommandBuilder SqlDataAdapter sda = new SqlDataAdapter(“select x, y, z from table1”, cnn); SqlCommandBuilder scb = new SqlCommandBuilder(sda); sda.UpdateCommand = scb.GetUpdateCommand(); sda.InsertCommand = scb.GetInsertCommand(); sda.DeleteCommand = scb.GetDeleteCommand(); sda.Update(ds);

Refreshing DataSet Data Fill data with the Fill method of the Adapter myAdapter1.fill(dataSet12); Process data. Before Updating, use : DataSet dataSetTemp = new DataSet(); myAdapter1.fill(dataSetTemp); dataSet12.Merge(dataSetTemp, true);

Managing and Processing Errors When updating DataSet DataAdapter.ContinueUpdateOnError –Default is False; setting to True allows all updates to complete even if updates on certain rows generate errors DataTable.GetErrors() –Returns array of DataRow objects that represent rows whose updates failed DataRow.RowError –Returns a string with a general error message that applies to the entire row DataRow.GetColumnsInError() –Returns array of DataColumn objects that contributed to error DataRow.GetColumnError(x) –Returns string description of the error itself –x is column ordinal, name, or DataColumn object

Working with Row versions and changes Item(x) –Allows you to examine the value of column x, where x is column’s ordinal or name Item(x, version) –Allows you to examine the value of a specific version of column x (DataRowVersion.Current,.Default,.Original, or.Proposed) BeginEdit(), EndEdit() –In conjunction with.Items(x), allows you to modify column values in the row CancelEdit() –Abandons pending changes to an edited row RowState –DataRowState.Added,.Deleted,.Detached,.Modified, or.Unchanged

Passing null values Use DBNull.Value SqlParameter param = new SqlParameter(); param.Value = DBNull.value;

Guarantee connection closes when DataReader finishes Use CommandBehavior.CloseConnection private DataReader getCategories() { SqlCommand cmd = new SqlCommand( "Select * from Categories, cnn); DataReader results = cmd.ExecuteReader(CommandBehavior.CloseConnection); return results; }

Inserting Primary Keys Use Guids as Primary Keys Can be generated on the client Guarantees to be unique Doesn’t change when updated on the server –No problem on child tables

Summary ADO.Net has tailored objects –.NET Data Providers for connected access Executing commands DataReader –DataSet for disconnected access, user interaction and caching ADO.Net and XML are made for each other

Questions I will post session content on my blog :