La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

ADO .NET Diego Casali SE Región Córdoba y NOA Microsoft de Argentina

Presentaciones similares


Presentación del tema: "ADO .NET Diego Casali SE Región Córdoba y NOA Microsoft de Argentina"— Transcripción de la presentación:

1 ADO .NET Diego Casali SE Región Córdoba y NOA Microsoft de Argentina
KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

2 Lo que vamos a cubrir Entender la diferencia entre ADO y ADO.NET
Cómo integrar ADO.NET con .NET utilizando Visual Studio.NET Cómo utilizar las capacidades avanzadas de ADO.NET Cómo aprovechar el soporte XML con ADO.NET KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

3 Prerrequisitos de la sesión
Diseño y programación de la base de datos relacional Programación de Visual Basic 6.0 ADO de Microsoft Entendimiento de XML KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

4 Agenda Introducción a ADO.NET Programación con ADO.NET Soporte XML
Funciones avanzadas ¿Cuándo utilizar qué? KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

5 Introducción a ADO.NET ¿Qué es ADO.NET?
Evolución natural de ADO Interoperabilidad Basado en estándares como XML, XSD Escalabilidad Objetivos distribuidos, escenarios web desconectados Modelo Arquitectura distribuida que reemplaza al cliente / servidor Integración de datos de diferentes recursos heterogéneos KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: So what is ADO.NET? The .NET Framework includes a new data access technology named ADO.NET, an evolutionary improvement to Microsoft ActiveX Data Objects (ADO). Though the new data access framework it is evolutionary, the classes that make up ADO.NET bear little resemblance to the ADO objects you may be familiar with. Some fairly significant changes must be made to existing ADO applications to convert them to ADO.NET. The changes don't have to be made immediately to existing ADO applications to run under ASP.NET, however. ADO will function under ASP.NET. The work necessary to convert ADO applications to ADO.NET is worthwhile, though. For disconnected applications, ADO.NET should offer performance advantages over ADO disconnected record sets. ADO required that transmitting and receiving components be COM objects. ADO.NET transmits data in a standard XML format file so that COM marshaling or data type conversions aren't required. ADO.NET supports the industry standards. ADO.NET, like ADO, provides a data access interface to communicate with OLE DB-compliant data sources, such as Microsoft® SQL Server™ Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data. Applications can also use OLE DB to manipulate data kept in non-relational formats, such as Microsoft Excel. In solutions requiring disconnected or remote access to data, ADO.NET uses XML to exchange data between programs or with Web pages. Any component that can read XML can process ADO.NET components. A receiving component does not even have to be an ADO.NET component if a transmitting ADO.NET component packages and delivers a data set in an XML file. Transmitting information in XML-formatted data sets enables programmers to easily separate the data processing and user interface components of a data-sharing application onto separate servers. This can greatly improve both performance and maintainability for systems supporting many users. For distributed application, use of XML data sets in ADO.NET provides performance advantages relative to the COM marshalling used to transmit disconnected data sets in ADO. Because transmission of data sets occurs through XML files in a simple text-based standard accepted throughout the industry, receiving components have none of the architectural restrictions required by COM. XML data sets used in ADO.NET also avoid the processing cost of converting values in a record set to data types recognized by COM. Virtually any two components can share XML data sets provided that they both use the same XML schema for formatting the data set. ADO.NET also supports the scalability required by Web-based data-sharing applications. Web applications must serve tens, hundreds, or even thousands of users. ADO.NET does not retain lengthy database locks or active connections that monopolize limited resources. This allows the number of users to grow with only small increases of the demands on the resources of a system. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

6 Introducción a ADO.NET ¿Por qué ADO.NET?
Para acomodar un modelo de aplicación Web Unido de manera flexible Mantiene el estado entre solicitudes Utiliza HTTP KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: As application development has evolved, new applications have become loosely coupled based on Web application model. More and more of today’s applications use XML to encode data to be passed over network connections. Web applications use HTTP as the fabric for communication between tiers, and therefore must explicitly handle maintaining state between requests. This new model is very different from the connected, tightly coupled style of programming that characterized the client/server era, where a connection was held open for the duration of the program’s lifetime and no special handling of state was required. ADO.NET was designed to meet the needs of this new programming model: Disconnected data architecture, tight integration with XML, common data representation with the ability to combine data with multiple and varied data sources, and optimized facilities for interacting with a database, all native to .NET Framework. ADO.NET is designed with several design goals: Leverage Current ADO Knowledge: Microsoft's design for ADO.NET addresses many of the requirements of today's application development model. At the same time, the programming model stays as similar as possible to ADO, so current ADO developers don't have to start from scratch in learning a brand new data access technology. ADO.NET is an intrinsic part of the .NET Framework without seeming completely foreign to the ADO programmer. ADO.NET coexists with ADO. While most new .NET applications will be written using ADO.NET, ADO remains available to the .NET programmer through .NET COM interoperability services. Support the N-Tier Programming Model: ADO.NET provides first-class support for the disconnected, n-tier programming environment for which many new applications are written. The concept of working with a disconnected set of data has become a focal point in the programming model. ADO.NET's solution for N-Tier programming is the DataSet. XML Support: XML and data access are intimately tied — XML is all about encoding data, and data access is increasingly becoming all about XML. The .NET Framework does not just support Web standards — it is built entirely on top of them. XML support is built into ADO.NET at a very fundamental level. The XML class framework in .NET and ADO.NET are part of the same architecture — they integrate at many different levels. You no longer have to choose between the data access set of services and their XML counterparts — the ability to cross over from one to the other is inherent in the design of both. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

7 Introducción a ADO.NET Comparación entre ADO y ADO.NET
Función ADO ADO.NET Representación de datos residentes en la memoria RecordSet puede contener una tabla DataSet puede contener una o más tablas representadas por Objeto DataTable Relación entre múltiples tablas Requiere la consulta JOIN (UNIRSE) Soporta el objeto DataRelation Visita de datos Escanea de manera secuencial la filas RecordSet Utiliza un paradigma de exploración para acceso no secuencial Acceso desconectado Proporcionado por RecordSet pero generalmente soporta el acceso conectado Se comunica con llamadas estandarizadas al DataAdapter KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: The biggest architectual difference between ADO.NET and ADO is that: No cursor support, giving better scaling but can be more difficult to code Extremely flexible, but generally requires targeting a specific data source Much better XML support than ado Other differences include: <read the differences straight from the slide> SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

8 Introducción a ADO.NET Comparación entre ADO y ADO.NET
Función ADO ADO.NET Programabilidad Utiliza el objeto de conexión para transmitir comandos Utiliza características de programación de XML escritas de manera sólida Uso compartido de datos desconectados entre niveles y componentes Utiliza la clasificación COM para transmitir el conjunto de registros desconectados Transmite un DataSet con un archivo XML Transmisión de datos a traves de Firewalls Problemático ya que los firewall generalmente se configuran para evitar solicitudes a nivel sistema Los objetos DataSet soportados utilizan XML, los cuales pueden atravezar firewalls Escalabilidad Seguros de base de datos y conexiones activas de base de datos para largas duraciones Acceso desconectado a la base de datos sin retener los seguros de la base de datos KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: Other differences include: <read the differences straight from the slide> SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

9 Introducción a ADO.NET Objetos de datos .NET
Controls, Designers, Code-gen, etc XSL/T, X-Path, Validation, etc KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: The Managed Provider consists of DataAdapter (previously known as DataSetCommand in VS.NET Beta 1), DataReader, Command, and Connection objects. DataReader is a fast pipe to the data but has restrictions, which will be discussed later. The DataSet is acting as a scratch pad, storing information and can discard them at will. XmlReader uses a pull model, parse level interface. It can easily implement a SAX style push model parser on top of pull, but not the other way around. XmlDocument is in memory cache and is W3C compliant. Combine it with XSL/T and XPath for data manipulations and validations SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER: Sync DataSet XmlData- Document XmlReader XmlText- Reader XmlNode- DataAdapter DataReader Command Connection .NET Data Provider

10 Introducción a ADO.NET Objetos de datos .NET

11 Agenda Introducción a ADO.NET Programación con ADO.NET Soporte XML
Funciones avanzadas ¿Cuándo utilizar qué? KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

12 Programación con ADO.NET .NET Data Provider
Administra la interacción a una fuente de datos Administrado equivalente a capa OLE DB Expone directamente las interfaces del consumidor Específico para (optimizada para) DataSource Modelo de objeto de .NET Data Provider Conexión Comando DataReader DataAdapter KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: Manages Interaction To A Data Source Managed equivalent of OLE DB layer Directly exposes consumer interface: No more COM/Automation dichotomy Not a full featured data store interface Specific to (Optimized for) DataSource The managed provider object model is similar to the ADO data access model. For example: Connection: Like ADODB.Connection Command: Like ADODB.Command DataReader: Similar to FO/RO ADODB.RecordSet SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

13 Programación con ADO.NET .NET Data Provider
SQL Server .NET Data Provider OLE DB .NET Data Provider Microsoft OLE DB Provider for SQL Server Microsoft OLE DB Provider for Oracle Microsoft OLE DB Provider for Microsoft Jet ODBC .NET Data Provider

14 Programación con ADO.NET Conexión
Representa una conexión a la Fuente de datos En una conexión, usted puede… Personalizar la conexión a la base de datos Iniciar, comprometer y abortar transacciones Equivalente al objeto ADODB.Connection KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: To connect to a specific data source, a data Connection object is used. It establishes a connection to a specific data source. It is possible to customize the connection to the database, and perform transactions like begin, commit and abort. The Connection object is equivalent to the ADODB.Connection Object. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

15 Programación con ADO.NET Conexión
// Ejemplo en C# //Especificar el Namespace System.Data.SQL Using System.Data.SqlClient; // Crear una instancia del objeto SQLConnection SQLConnection cnn = new SQLConnection(); // Definir la cadena de conexión cnn.ConnectionString = "server=localhost;uid=sa;database=pubs"; //Abrir la conexión cnn.Open(); KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

16 Programación con ADO.NET Comando
Representa un comando que se va a ejecutar No necesariamente SQL Con un comando ADO usted puede: Definir un enunciado para que se ejecute en el servidor Establecer información de parámetros para ese comando Recuperar valores de retorno de la ejecución del comando Corresponde al objeto ADODB.Command Puede contener parámetros Valores que se van a utilizar cuando se ejecute el enunciado KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: After establishing a connection, you can execute commands and return results from a data source using a Command object. A Command object can be created using the Command constructor, or by calling the CreateCommand method of the Connection object. When creating a Command object using the Command constructor, specify a SQL statement to execute at the data source, and a Connection object. The Command object's SQL statement can be queried and modified using the CommandText property. The Command object exposes several Execute methods to perform the intended action. When returning results as a stream of data, ExecuteReader is used to return a DataReader object. ExecuteScalar is used to return a singleton value. ExecuteNonQuery is used to execute commands that do not return rows. When using the Command object with a Stored Procedure, you may set the Command object's CommandType property to StoredProcedure. With a CommandType of StoredProcedure, you may use the Parameters property of the Command to access input and output parameters and return values. Command Parameters can be accessed regardless of the Execute method called. However, when calling ExecuteReader, return values and output parameters are not accessible until the DataReader is closed. When using a DataAdapter with a DataSet, Command objects are used to return and modify data at the data source through the DataAdapter's SelectCommand, InsertCommand, UpdateCommand and DeleteCommand properties. The DataAdapter's SelectCommand property must be set before the Fill method is called. The InsertCommand, UpdateCommand and DeleteCommand properties must be set before the Update method is called. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

17 Programación con ADO.NET Comando
ExecuteNonQuery ExecuteReader ExecuteScalar ExecuteXmlReader (únicamente para el objeto SqlCommand) KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: The SqlCommand class represents a transact-SQL statement or stored procedure to execute at a SQL Server data source. There are a few different options: ExecuteNonQuery executes a Transact-SQL statement that doesn’t return any rows against the connection. ExecuteReader executes the query and returns a SqlDataReader object, which is a read-only, forward-only ExecuteScalar executes the query and returns the first column of the first row in the resultset returned by the query. Extra columns or rows are ignored. ExecuteXmlReader sends the Transact-SQL statement or stored procedure to the connection to build a XmlReader. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

18 Programación con ADO.NET DataReader
Acceso a datos rápido, únicamente hacia delante, únicamente de lectura Funciona como un socket Permite un acceso escrito de manera sólida Debe ser cerrado KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: You can use the DataReader to retrieve a read-only, forward-only stream of data from the database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory. The Read method of the DataReader object is used to obtain a row from the results of the query. Each column of the returned row may be accessed by passing the name or ordinal reference of the column to the DataReader, or, for best performance, the DataReader provides a series of methods that allow you to access column values in their native data types (GetDateTime, GetDouble, GetGuid, GetInt32, and so on. For a list of typed accessor methods, see the reference topics on the OleDBDataReader and SqlDataReader). Using the typed accessor methods when the underlying data type is known will reduce the amount of type conversion required when retrieving the column value. The following example iterates through a DataReader object, and returns two columns from each row. Using DataReader has the following advantages: more efficient than dataset or ado recordset because it stores only one row of data in memory at a time. minimizes caching and copying don’t have to wait for all records to arrive sql reads directly off of the wire Although it is important to remember to close DataReader once finished. Connection is busy until reader is closed. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

19 Programación con ADO.NET DataSet
Almacén en memoria para datos del cliente Vista relacional de datos Tablas, columnas, filas, restriciones, relaciones Persisten los datos y el esquema como XML Modelo desconectado explícito Objeto remoto, desconectado Índice en forma de arreglo No hay conocimiento de Fuente de datos o Propiedades Modelo común sobre datos heterogéneos Características de rendimiento predecibles KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: The DataSet is a major component of the ADO.NET architecture. It can be helpful to consider it an in-memory cache of data retrieved from a database. The DataSet consists of a collection of tables, relationships, and constraints. DataTable objects can be related to each other through DataRelation objects. UniqueConstraint and ForeignKeyConstraint objects ensure data integrity by enforcing data-specific rules. While DataTable objects contain the data, the DataRelationCollection allows you to navigate though the table hierarchy. The tables are contained in a DataTableCollection accessed through the Tables property. For more information about working with DataTable objects, see Creating a DataTable. A DataSet reads and writes data and schema as XML documents. The data and schema can be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the WriteXmlSchema method, and the schema and data can be saved using the WriteXml method. If you need to read an XML document that includes both schema and data, use the ReadXml method which infers and creates a schema from the document. In an application where more than one view of a DataSet is needed, create a DataView with customized DataTable objects. To customize the view of the current DataSet, add DataTable objects to the DataView returned by the DefaultViewManager property. If you use the Visual Studio Class Designer, classes are automatically created that derive from DataSet, DataTable, and DataRow. With such a set of derived classes, the methods and properties are retained, but custom methods are generated to help you easily navigate through the tables of the DataSet. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

20 Programación con ADO.NET DataSet
DataTable DataSet DataTable DataColumn KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: One of key benefits of DataSet is that it can contain one or more tables. So unlike ADO, DataSet can store a number of tables simultaneously for a more centralized data storage. The DataTable is a central object in the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView. If you are creating a DataTable programmatically, you must first define its schema by adding DataColumn objects to the DataColumnCollection (accessed through the Columns property). The schema of a table is defined by the DataColumnCollection, the collection of DataColumn objects. The DataColumnCollection is accessed through the Columns property. See the DataColumn and DataColumnCollection for more information about defining a schema for the table. The DataTable contains a collection of Constraint objects that can be used to ensure the integrity of the data. For more information about constraints, see Adding Constraints to a Table. To determine when changes are made to a table, use one of the following events: RowChanged, RowChanging, RowDeleting, and RowDeleted. See Working with DataTable Events. When an instance of DataTable is created, some of the read/write properties are set to initial values. For a list of these values, see the DataTable constructor. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER: DataRow Relationes Restricciones Esquema XML

21 Programación con ADO.NET DataRelation
¿Qué es DataRelation? Se utiliza para relacionar dos objetos DataTable Las relaciones se crean entre columnas equivalentes en las tablas padre e hijo Las relaciones también pueden presentar en cascada varios cambios de la fila padre hacia las filas hijo KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: A DataRelation is used to relate two DataTable objects to each other through DataColumn objects. For example, in a Customer/Orders relationship, the Customers table is the parent and the Orders table is the child of the relationship. Relationships are created between matching columns in the parent and child tables. That is, the DataType value for both columns must be identical. Relationships can also cascade various changes to the parent row down to it's child rows. To control how values are changed in child rows, add a ForeignKeyConstraint to the DataTable class's ConstraintCollection, which determines what happens when a value in a parent table is deleted or updated. When a DataRelation is created, it verifies that the relationship can be established. Once it is added to the Relations collection, this is maintained by disallowing any changes that would invalidate this relation. However, before it is added to the Relations collection, this can change. So, every access of the object between construction and collection add verifies that the state is still valid, and generates an exception if it is no longer a viable relation. DataRelation objects are contained in a DataRelationCollection, and both the DataSet and the DataTable classes have properties to access the collection. the DataSet class's Relations property, and the DataTable class's ChildRelations and ParentRelations properties all access different DataRelationCollection objects. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

22 Programación con ADO.NET Typed DataSet
Clase generada al momento del diseño Hereda de DataSet Esquema codificado en la clase Beneficios IntelliSense Verificación de tipos en tiempo de compilación Código legible, conciso KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: Along with late bound access to values through weakly typed variables, the DataSet provides access to data through a strongly typed metaphor. Tables and columns that are part of the DataSet can be accessed using user-friendly names and strongly typed variables. A typed DataSet is a class that derives from a DataSet. As such, it inherits all of the methods, events and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events and properties. In practice, this means you can access tables and columns by name, instead of using collection-based methods. Aside from the improved readability of the code, a typed DataSet also allows the compiler to automatically complete lines as you type. Additionally, the strongly typed DataSet provides access to values as the correct strongly typed value at compile-time. With a strongly typed dataset, type mismatch errors are caught when the code is compiled rather than at run-time. Using Visual Studio .NET data designer tools, developers can produce typed DataSets from a database or XSD schema. This enables ADO.NET programmers to refer to rows inside the DataSet as if they were strongly typed objects, a capability that ADO programmers have often requested for the recordset. Typed DataSets are subclasses of the DataSets that are generated automatically by the data designer tool based on some schema, and they have strongly typed properties that reflect the data model of the schema. The advantage that typed DataSets embody is the ability to access data using a typed class metaphor, while still being able to tap into all of the services of ADO.NET. Only one copy of the data exists—the data stored inside the DataSet. Thus, you can view typed DataSets as an object-view mechanism on top of the DataSet. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

23 Programación con ADO.NET DataAdapter
Administra el Intercambio de datos entre DataSet y la Fuente de datos Llenar (DataSet o DataTable) Actualizar (DataSet o DataTable) Ofrece Cruces de información entre tablas y columnas El usuario puede anular los comandos Insertar / actualizar / eliminar Componente de autogeneración disponible Permite que un único DataSet se llene de varios Orígenes de datos diferentes KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: The DataAdapter serves as a bridge between a DataSet and data source for retrieving and saving data. The DataAdapter provides this bridge by using Fill to load data from the data source into the DataSet, and using Update to send changes made in the DataSet back to the data source. The DataAdapter also includes the SelectCommand, InsertCommand, DeleteCommand, UpdateCommand, and TableMappings properties for facilitating the loading and updating of data. When you create an instance of DataAdapter, the read/write properties are set to their initial values. For a list of these values, see the DataAdapter constructor. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

24 Programación con ADO.NET DataAdapter
Base de datos DataAdapter KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: Once you hold a DataAdapter object in your hands, you call its Update method. DataSetCommand exposes properties like InsertCommand, DeleteCommand, UpdateCommand, and SelectCommand. They're Command objects but you don't have to set them unless the default behavior doesn't fulfill your expectations. This is the same as in ADO. During Update, if any of the command properties is not set but primary key information is present, the Command object will be automatically generated. Notice that for this to work, having a primary key set for the involved data tables is mandatory. Also, DataAdapter allows single DataSet to be populated from multiple different DataSources. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER: SelectCommand InsertCommand UpdateCommand DeleteCommand DataSet TableMappings

25 Programación con ADO.NET DataAdapter
// Ejemplo en C# // Crear un DataAdapter SQLDataAdapter objDataAdapter = new SQLDataAdapter( "Select * from authors",cnn); // Cargar los datos en el DataSet objDataAdapter.Fill(pubs, "Authors"); // hacer cambios de datos de clientes en el dataset pubs.Tables["Authors"].Rows[0]["au_lname"]="smith"; objDataAdapter.Update(pubs, "Authors"); KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

26 Programación con ADO.NET Recursos para DataBinding
DataReader DataTable DataView DataSet Arreglo Colección IList KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: Here is a list of sources for DataBinding provided by ADO.NET. As you can see, the list is quite extensive, hence making it very convenient to bind data to many controls available from the .NET Framework. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

27 Programación con ADO.NET DataBinding
DataView Concibe a ésta como una vista en DataTable Permite establecer una solicitud de clasificación y Filtro en una vista de la tabla Puede crear cualquier número de DataViews en una tabla para permitir diferentes vistas de la misma tabla KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: A major function of the DataView is to allow data binding on both Windows Forms and Web Forms. Additionally, a DataView can be customized to present a subset of data from the DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data. For example, one control may be bound to a DataView showing all of the rows in the table, while a second may be configured to display only the rows that have been deleted from the DataTable. The DataTable also has a DefaultView property which returns the default DataView for the table. For example, if you wish to create a custom view on the table, set the RowFilter on the DataView returned by the DefaultView. To create a filtered and sorted view of data, set the RowFilter and Sort properties. Then use the Item property (DataView indexer) to return a single DataRowView. You can also add and delete from the set of rows using the AddNew and Delete methods. When you use those methods, the RowStateFilter property can set to specify that only deleted rows or new rows be displayed by the DataView. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

28 Demostración 1 DataSet, DataAdapter y DataReader
KEY MESSAGE: SLIDE BUILDS: SLIDE SCRIPT: This demonstration will show the audience how to use ADO.NET to retrieve data from a SQL database. Both OLEDB and SQL Data Providers will be used in this demonstration. It will also introduce new concepts of DataSet, DataReader, DataAdapter and DataRow. TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER:

29 Agenda Introducción a ADO.NET Programación con ADO.NET Soporte XML
Funciones avanzadas ¿Cuándo utilizar qué? KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

30 Soporte XML ADO.NET y XML
DataSet Carga / guarda datos XML dentro / fuera de DataSet El esquema se puede cargar / guardar como XSD El esquema se puede inferir de datos XML XmlDataDocument Expone una vista relacional sobre XML estructurado Permite una escritura, unión de control, acceso relacional sólidos de datos XML Permite herramientas XML (validación de esquemas, XSL/T, consultas Xpath) contra datos relacionales Preserva una fidelidad total de documentos XML KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: DataSet Loads/saves XML data into/out of DataSet Schema can be loaded/saved as XSD Schema can be inferred from XML Data The DataSet can be associated with an XmlDataDocument Exposes relational view over structured XML According to the DataSet schema Allows strong typing, control binding, relational access of XML data Allows XML tools (schema validation, XSL/T, XPath queries) against relational data Preserves full fidelity of XML Document SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

31 Soporte XML ADO.NET y XML
// Ejemplo en C# // Asociar un XmlDataDocument con el DataSet XmlDataDocument xmlDocument = new XmlDataDocument(pubs); // Obtener un XmlNavigator para el XmlDataDocument DataDocumentNavigator xmlNavigator = new DataDocumentNavigator(xmlDocument); // Obtener todos los autores de CA xmlNavigator.Select("//Authors[state='CA']/au_lname"); // Mostrar todos los apellidos de autores while(xmlNavigator.MoveToNextSelected()) { Console.WriteLine("Name = " + xmlNavigator.InnerText); } KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

32 Soporte XML ADO.NET y XML
DataSet ofrece manejo directo de documentos y esquemas XML ReadXml() ReadXmlSchema() WriteXml() WriteXmlSchema() KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: ReadXml: Reads XML schema and data into the DataSet. ReadXmlSchema: Reads an XML schema into the DataSet. WriteXml: Writes XML schema and data from the DataSet. WriteXmlSchema: Writes the DataSet structure as an XML schema. There are a number of ways to read and persist data to dataset using the four methods: To a file To a System.IO.Stream To a System.IO.TextReader/TextWriter To a System.Xml.XmlReade/XmlWriter SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

33 Soporte XML SQLXML SQLXML Managed Classes 3.0 SqlXmlCommand
SqlXmlParameter SqlXmlAdapter

34 Demontración 2 Soporte XML
KEY MESSAGE: SLIDE BUILDS: SLIDE SCRIPT: This demonstration shows the audience how to read and write XML files and schemas, using XML capability of ADO.NET. TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER:

35 Agenda Introducción a ADO.NET Programación con ADO.NET Soporte XML
Funciones avanzadas ¿Cuándo utilizar qué? KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

36 Funciones avanzadas ConnectionPooling
El proveedor OLE DB utiliza agrupación de sesiones tradicional OLEDB El proveedor de clientes SQL utiliza agrupación de sesiones basada en COM+ KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: To deploy high-performance applications, you need to use connection pooling. The OLE DB .NET Data Provider automatically pools connections using OLE DB Session Pooling. For more information on OLE DB Session Pooling or Resource Pooling, as well as disabling pooling by overriding OLE DB provider service defaults, there are a number of topics and articles available in the OLE DB Programmer’s Reference in the MSDN Library (http://msdn.microsoft.com/library). UDL files can be used to supply OLE DB connection information to the OLE DB Provider. However, since UDL files can be modified externally to any ADO.NET client program, connection strings that contain references to UDL files will not be cached with the pooled connection. Instead, connection strings that contain UDL files will be parsed every time the connection is opened. This can slow performance and it is recommended that, for best performance, a static connection string that does not include a UDL file be used. The SQL Client .NET Data Provider relies on Windows 2000 Component Services to provide connection pooling using an implicit pooling model by default. The SqlConnection object also has several connection string modifiers that you can set to control implicit pooling behavior. Each connection pool is associated with one distinct connection string, using an exact matching algorithm. If no exact match is found, a new pool is created. The SqlConnection object also has several connnection string modifiers that you can set to control implicit pooling behaviour. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

37 Funciones avanzadas ConnectionPooling
// Ejemplo en C# SqlConnection conn = new SqlConnection(); conn.ConnectionString = “Integrated Security=SSPI; Initial Catalog=Northwind” conn.Open(); // Se crea el Pool A; conn.ConnectionString = “Integrated Security=SSPI; Initial Catalog=pubs” conn.Open(); // Se crea el Pool B ya que la cadena de conexión es diferente conn.Open(); // Se usa el Pool A KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: In this example, 3 new SqlConnection objects are created, but only two connections pools are required to managed them. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

38 Funciones avanzadas Transacciones distribuidas
Para utilizar las transacciones distribuidas: Utilice System.EnterpriseServices Cree un ServicedComponent para ofrecer soporte para transacciones automático Agregue funciones al ServicedComponents Ejecute transacciones en el ServicedComponents KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: One major advantage of the automatic distributed transaction programming model (Windows 2000 Component Services) is that data stores (the Resource Managers) are automatically enlisted in transactions. When the transaction group is to be completed, call SetComplete or if it is not to be completed call SetAbort. These distributed transactions can span multiple databases. ADO.NET providers (ADO Interop Provider and SQL Server Provider) automatically enlist in Component Services transactions that initiated using ComponentServices. Distributed transactions are available automatically from the Microsoft .NET Framework component services. Microsoft Transaction Server (MTS), Microsoft .NET Framework SDK, and the common language runtime support the same automatic, distributed transaction model. To use this feature, complete the following steps to provide for automatic distributed transactions to your data source. Use System.EnterpriseServices. Create a ServicedComponent to provide automatic transaction support. Add some features to the ServicedComponent. Write code to execute (distributed) transactions on the ServicedComponent. Any instance of a .NET Framework class can participate in an automatic transaction, as long as you prepare the class to do so. Each resource accessed by a class instance or object enlists in the transaction. For example, if an object uses ADO.NET to post money on an account in a database, the resource manager for the database determines if it should execute in a transaction and, if so, it enlists the database in the transaction automatically. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

39 Funciones avanzadas Manejo de errores
ADO.NET permite a los desarrolladores agregar mensajes de error a cada fila de datos en un DataSet Usted puede filtrar para filas en error El error persiste con DataSet aún cuando haya sido transferido utilizando XML O Servicios Web KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: In addition to Try/Catch and exceptions, the new ADO.NET data architecture allows you to add error messages to each row of Data in a DataSet. SqlDataAdapters attach error messages to Rows if updates or other actions fail. Furthermore, you can filter for rows in error to present them to the user, or pass them to error handling functions. Errors persist with the DataSet even when being transferred using XML or Web Services. You can use the RowError property to set the Error message of a DataRow in a DataSet. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

40 Demostración 3 Funciones avanzadas
KEY MESSAGE: SLIDE BUILDS: SLIDE SCRIPT: This demonstration will show the audience how to create additional error messages with ADO.NET. TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER:

41 Agenda Introducción a ADO.NET Programación con ADO.NET Soporte XML
Funciones avanzadas ¿Cuándo utilizar qué? KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

42 ¿Cuándo utilizar qué? Consideraciones
Acceso a datos conectados Acceso a datos desconectados Vista XML de datos relacionales KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: So at this point, you will probably ask “ When should I use what with all the new features available with ADO.NET”? To answer that, you must first to find out what sort of data connectivity will be used, and whether the data source is from a database or XML file. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

43 ¿Cuándo utilizar qué? Acceso a datos conectados
Proveedores administrados Conexión, operación Conectar a DataSource Iniciar / terminar transacciones Comando, parámetros Actualizaciones de Base de datos, selecciones, DDL DataReader Cursor de servidor (FO/RO) DataAdapter Empujar los datos dentro de un Dataset Leer los cambios fuera de DataSet KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: For connected data access, there are 2 managed providers: OLEDB and SQL, as well as the Command, DataReader and DataAdapter objects. Much like ADO, ADO.NET provides full support for the traditional data access and manipulation controls. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

44 ¿Cuándo utilizar qué? Acceso a datos desconectados
DataSet Datos de aplicación Resultados remotos SOAP, WebMethods, Remoting Resultados de memoria caché Caché ASP.NET Resultados persistentes Guardar datos como XML, esquema como XSD Interacción del usuario Desplazar, clasificar, filtrar DataView, DataViewManager Unir controles Windows KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: For disconnected data access, again there are 2 managed providers: OLEDB and SQL, as well as the DataSet and DataView objects. With disconnected data access, it is possible to cache the results. Also, user interactions such as scrolling, sorting and filtering are very useful for disconnected data management. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

45 ¿Cuándo utilizar qué? Acceso de datos XML
XmlDocument XmlDataDocument Implementa el núcleo de nivel 1 y 2 del W3C DOM XPathNavigator Ofrece acceso aleatorio de sólo lectura XslTransform Soporta sintaxis XSLT 1.0 KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: XmlDocument implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. The DOM is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document. The System.Xml.XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational System.Data.DataSet. This class allows components to mix XML and relational views of the underlying data. XPathNavigator provides read-only random access to data. It is based upon the XPath data model and provides the methods required to implement XPath queries over any data model. This class was designed to support XSLT transformations. XslTransform supports the XSLT 1.0 syntax. The XSL stylesheet must include the namespace declaration "xmlns:xsl= This class supports embedded scripting using the <msxml:script> element. However, unlike MSXML, XslTransform does not have to start a script engine execute the code block. Instead, when the stylesheet is loaded, all defined functions are compiled and wrapped in a class definition. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

46 Resumen de la sesión Una evolución natural de ADO
Diseñado para trabajar con XML Integrado estrechamente con el marco .NET Ofrece mecanismos rápidos y eficientes para acceso a datos conectados y desconectados KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: We looked at what ADO.NET is. We try to get a high level overview of what’s changed, what’s different from the world we are currently in, and what we are moving towards with the Microsoft .NET Framework. We drill down and had a look at the fundamentals of ADO.NET: the managed providers, the Connection, the DataAdapter, the DataSet, the DataReader, the DataBinding. ADO.NET is a natural evolution of ADO. It is designed to work with XML and of course it is closely integrated with the Microsoft .NET Framework. It provides fast and efficient mechanisms for connected and disconnected data access. SLIDE TRANSISTION: ADDITIONAL INFORMATION FOR PRESENTER:

47 Para mayor información…
MSDN Web site at msdn.microsoft.com .NET Framework at Visual Studio .NET at ADO KEY MESSAGE: SLIDE BUILDS: None SLIDE SCRIPT: SLIDE TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER:

48 MS Press Recursos esenciales para desarrolladores
Key Message: Talk about MS Press books and introduce the Build your own book feature SLIDE BUILDS: 2 SLIDE SCRIPT: [BUILD 1] (Add book script here) [BUILD 2] Have you ever looked at some of our books as just not bought them because there was only one chapter that interested you? Well now MS Press are offering the ability to create your own book from an ever growing selection of titles. Look through the Inside SQL and Inside Windows 2000 books and just pick a chapter from each, add a chapter on Office or Exchange. Build your own reference book then have it make into a MS Reader E-book, or a PDF file or even have it printed. Go to and try it for yourself. [Check the custom list to see if the books in build 1 are available – if not mention it in the script] SLIDE TRANSITION: ADDITIONAL INFORMATION: Ahora puede crear sus propios libros personalizados MS Press books en mspress.microsoft.com/custombook Escoja entre Windows 2000, SQL Server 200, Exchange 2000, Office 2000 y XML Créelo y después pídalo en versión MS Reader, PDF o impresa

49 MSDN Recursos esenciales para desarrolladores
Servicios de suscripción Biblioteca, Profesional, Universal Proporcionado vía CD-ROM, DVD, Web Información en línea MSDN Online, MSDN Flash KEY MESSAGE: SLIDE BUILDS: SLIDE SCRIPT: MSDN is the essential resource for developers. It contains subscriptions, such as MSDN online and MSDN flash (as the MSDN web is becoming the central portal for developers). It has membership programs which are coordinated online as well as user groups. There are print publications as well as a variety of training and events - at local, national, and international levels. SLIDE TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER: Capacitación & Eventos MSDN Training, Tech-Ed, PDC, Developer Days, MSDN/Eventos en el sitio Publicaciones impresas MSDN Magazine MSDN News Programas de membresía Grupos de usuarios MSDN

50 ¿Dónde puedo obtener MSDN?
Visite MSDN en línea en msdn.microsoft.com Regístrese para el Boletín de noticias por correo electrónico MSDN Flash en msdn.microsoft.com/resources/ msdnflash.asp Conviértase en un suscriptor del CD de MSDN en msdn.microsoft.com/subscriptions Asista a más eventos de MSDN KEY MESSAGE: Purpose of this slide is to educate developers on where to go, how to be a part of MSDN. SLIDE BUILDS: None SLIDE SCRIPT: There is one place you should go to start: MSDN.MICROSOFT.COM There is one communication you should subscribe to: MSDN Flash. Twice monthly listserve for the developer community - focuses on news, information, resources and events Look for MSDN branded events - feature SLIDE TRANSITION: So the next step in your career cycle developing using Microsoft Technologies is to become an MCSD ADDITIONAL INFORMATION FOR PRESENTER:

51

52 ANEXO

53 Application Blocks Data Access Exception Management
what we’ll tell you: what is the PAG team and what we do and how it relates to other groups, how we work, what projects we have for .net – with a focus on the application blocks for .net program We’ll drill down into published .NET guidance Tell you how we want to engage with YOU Start a dialog and initiate questions.

54 Data Access Application Block
Simplifies calling ADO.NET SqlClient Stored procedure parameter management Caches s. proc. parameter definitions Cache can be loaded manually (enforcing type manually) or automatically ‘on the fly’ Simplifies returning many formats Get DataSets, DataReaders, Scalars, XmlReaders – all in one line of code Simplifies calling with many sources Connections, Conn. Strings, SQL Transactions Plays well with COM+ dr = SqlHelper.ExecuteReader( CONN_STRING,“spSaveCustomer", “John” , “Doe” ); DataSet ds; string sConn = "SERVER=(local); INITIAL CATALOG=Pubs; INTEGRATED SECURITY=sspi;"; ds = SqlHelper.ExecuteDataset(sConn,CommandType.Text,"SELECT * FROM Authors"); dataGrid1.DataSource = ds.Tables[0];

55 Data Access Application Block

56 Data Access Application Block
SqlHelper class has the following overloaded static methods: ExecuteNonQuery - execute Transact-SQL statements or stored procedures that do not return rows ExecuteDataset - retrieve a DataSet object that contains the resultset of a Transact-SQL statement or stored procedure ExecuteReader - return a DataReader object that contains the resultset of a Transact-SQL statement or stored procedure ExecuteScalar - retrieve a single value resultset from a Transact-SQL statement or stored procedure ExecuteXMLReader - retrieve XML data

57 Demostración 4 DAAB Usando el “Data Access Application Block”
KEY MESSAGE: SLIDE BUILDS: SLIDE SCRIPT: This demonstration will show the audience how to create additional error messages with ADO.NET. TRANSITION: ADDITIONAL INFORMATION FOR PRESENTER:


Descargar ppt "ADO .NET Diego Casali SE Región Córdoba y NOA Microsoft de Argentina"

Presentaciones similares


Anuncios Google