Pages

1/16/2008

ADO vs ADO.NET

ADO vs ADO.NET

From Wikipedia, the free encyclopedia

Note: The following content requires a knowledge of database technologies.

The following is a comparison of two different database access technologies from Microsoft, namely, ActiveX Data Objects (ADO) and ADO.NET. Before comparing the two technologies, it is essential to get an overview of Microsoft Data Access Components (MDAC) and the .NET Framework. Microsoft Data Access Components provide a uniform and comprehensive way of developing applications for accessing almost any data store entirely from unmanaged code. The .NET Framework is an application virtual machine-based software environment that provides security mechanisms, memory management, and exception handling and is designed so that developers need not consider the capabilities of the specific CPU that will execute the .NET application. The .NET application virtual machine turns intermediate language (IL) into machine code. High-level language compilers for C#, VB.NET and C++ are provided to turn source code into IL. ADO.NET is shipped with the Microsoft NET Framework.

ADO relies on COM whereas ADO.NET relies on managed-providers defined by the .NET CLR. ADO.NET does not replace ADO for the COM programmer; rather, it provides the .NET programmer with access to relational data sources, XML, and application data.


ADO ADO.NET
Business Model Connection-oriented Models used mostly Disconnected models are used:Message-like Models.
Disconnected Access Provided by Record set Provided by Data Adapter and Data set
XML Support Limited Robust Support
Connection Model Client application needs to be connected always to data-server while working on the data. Client disconnected as soon as the data is processed. DataSet is disconnected at all times.
Data Passing ADO objects communicate in binary mode. ADO.NET uses XML for passing the data.
Control of data access behaviors Includes implicit behaviors that may not always be required in an application and that may therefore limit performance. Provides well-defined, factored components with predictable behavior, performance, and semantics.
Design-time support Derives information about data implicitly at run time, based on metadata that is often expensive to obtain. Leverages known metadata at design time in order to provide better run-time performance and more consistent run-time behavior.


ADO.NET

ADO.NET

From Wikipedia, the free encyclopedia

Jump to: navigation, search

ADO.NET is a set of computer software components that can be used by programmers to access data and data services. It is a part of the base class library that is included with the Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in relational database systems, though it can also be used to access data in non-relational sources. ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be conceived of as an entirely new product.



Architecture

ADO.NET consists of two primary parts:

[edit] Data provider

These classes provide access to a data source, such as a Microsoft SQL Server or Oracle database. Each data source has its own set of provider objects, but they each have a common set of utility classes:

  • Connection: Provides a connection used to communicate with the data source. Also acts as an abstract factory for command objects.
  • Command: Used to perform some action on the data source, such as reading, updating, or deleting relational data.
  • Parameter: Describes a single parameter to a command. A common example is a parameter to a stored procedure.
  • DataAdapter: A bridge used to transfer data between a data source and a DataSet object (see below).
  • DataReader: A class used to efficiently process a large list of results one record at a time.

[edit] DataSets

DataSets objects, a group of classes describing a simple in-memory relational database, were the star of the show in the initial release (1.0) of the Microsoft .NET Framework. The classes form a containment hierarchy:

  • A DataSet object represents a schema (either an entire database or a subset of one). It can contain tables and relationships between those tables.
    • A DataTable object represents a single table in the database. It has a name, rows, and columns.
      • A DataView object "sits over" a DataTable and sorts the data (much like a SQL "order by" clause) and filters the records (much like a SQL "where" clause) if a filter is set. An in-memory index is used to facilitate these operations. All DataTables have a default filter, while any number of additional DataViews can be defined, reducing interaction with the underlying database and thus improving performance.
        • A DataColumn represents a column of the table, including its name and type.
        • A DataRow object represents a single row in the table, and allows reading and updating of the values in that row, as well as retrieving any rows that are related to it through a primary-key foreign-key relationship.
        • A DataRowView represents a single row of a DataView the distinction between a DataRow and DataRowView is important when iterating over a result set.
    • A DataRelation is a relationship between tables, such as a primary-key foreign-key relationship. This is useful for enabling DataRow's functionality of retrieving related rows.
    • A Constraint describes an enforced property of the database, such as the uniqueness of the values in a primary key column. As data is modified any violations that arise will cause exceptions.

A DataSet is populated from a database by a DataAdapter whose Connection and Command properties have been set. However, a DataSet can save its contents to XML (optionally with an XSD schema), or populate itself from XML, making it exceptionally useful for web services, distributed computing, and occasionally-connected applications.

[edit] ADO.NET and Visual Studio.NET

Functionality exists in the Visual Studio .NET IDE to create specialized subclasses of the DataSet classes for a particular database schema, allowing convenient access to each field through strongly-typed properties. This helps catch more programming errors at compile-time and makes the IDE's Intellisense feature more useful.

[edit] Entity Framework

ADO.NET Entity Framework is a set of data access APIs for the Microsoft .NET Framework, targeting the version of ADO.NET that ships with .NET Framework 3.5. However, it will be released as an out-of-band update after both .NET Framework 3.5 and Visual Studio 2008 has shipped. An Entity Framework Entity is an object which has a key representing the primary key of a logical datastore entity. A conceptual Entity Data Model (Entity-relationship model) is mapped to a datastore schema model. Using the Entity Data Model, the Entity Framework allows data to be treated as entities independently of their underlying datastore representations.

Entity SQL is a SQL-like language for querying the Entity Data Model (instead of the underlying datastore). Similarly, Linq extension Linq-to-Entities provides typed querying on the Entity Data Model. Entity SQL and Linq-to-Entities queries are converted internally into a Canonical Query Tree which is then converted into a query understandable to the underlying datastore (e.g. into SQL in the case of a Relational database). The entities can be using their relationships, and their changes committed back to the datastore.






.NET vs. Java and Java EE

.NET vs. Java and Java EE

See also: Comparison of the Java and .NET platforms and Comparison of C# and Java

The CLI and C# have many similarities to Sun's JVM and Java. They are strong competitors. Both are based on a virtual machine model that hides the details of the computer hardware on which their programs run. Both use their own intermediate byte-code, Microsoft calling theirs Common Intermediate Language (CIL; formerly MSIL) and Sun Java bytecode. On .NET, the byte-code is always compiled before execution, either Just In Time (JIT), or in advance of execution using the ngen.exe utility. With Java the byte-code is either interpreted, compiled in advance, or compiled JIT. Both provide extensive class libraries that address many common programming requirements, and both address many security issues that are present in other approaches. The namespaces provided in the .NET Framework closely resemble the platform packages in Java EE API Specification both in style and invocation.

.NET in its complete form (Microsoft's implementation) is currently only fully available on Windows platforms and partially available on Linux and Mac,[23][24][25] whereas Java is fully available on nearly all platforms.[26] From its beginning, .NET has supported multiple programming languages, and at its core remains platform agnostic and standardized so that other vendors can reimplement it on other platforms (although Microsoft's implementation only targets Windows, Windows CE, and XBox based platforms). The Java platform was initially built to support only the Java language, but on many operating system platforms under the slogan, "Write once, run anywhere.".

Sun's reference implementation of Java is becoming open source (including the class library, the compiler, the virtual machine, and the various tools associated with the Java Platform) under the copyleft GNU GPL license.[27]

The third-party Mono Project, sponsored by Novell, has been developing an open source implementation of the ECMA standards that define the .NET Framework, as well as most of the other non-ECMA standardized libraries in Microsoft's .NET. The Mono implementation is meant to run on Linux, Solaris, Mac OS, BSD, HP-UX, and Windows platforms. Mono includes the CLR runtime, the class libraries, and compilers for C# and VB.NET. The current version supports nearly all the APIs in version 1.1 of Microsoft's .NET and almost 96% of the APIs in version 2.0 of Microsoft's .NET. Support for the additional libraries in .NET 3.0 and 3.5 is ongoing, and currently in the early alpha stages. Support for C# 3.0 and Linq is also in early alpha at this stage. [28]

[edit] Disadvantages

Some concerns and criticisms relating to .NET include:

  • Applications running in a managed environment such as the Microsoft framework's CLR or Java's JVM tend to require more system resources than functionally similar applications that access machine resources more directly. However, some applications have been shown to perform better in .NET than in their native version. This could be due to the runtime optimizations made possible by such an environment, the use of relatively well-performing functions in the .NET framework, JITting of managed code, or other aspects of the CLR.[29][30]
  • As JIT languages can be more easily reverse-engineered than native code to algorithms used by an application, there is concern over possible loss of trade secrets and the bypassing of license control mechanisms. However, many obfuscation techniques already developed can help to prevent this; indeed Microsoft's Visual Studio 2005 includes such a tool produced by PreEmptive Solutions (see dotfuscator).
  • In a managed environment such as the Microsoft framework's CLR or Java's JVM, the regularly occurring garbage collection for reclaiming memory suspends execution of the application for an unpredictable lapse of time (typically no more than a few milliseconds). This makes such environments unsuitable for some applications, such as those that must respond to events with sub-second timing.
  • Since the framework is not pre-installed on older versions of Windows, an application that requires it must verify that it is present, and if it is not, guide the user to install it. This requirement may deter some from using the application.

[edit] Alternative implementations

The Microsoft .NET Framework is the predominant implementation of .NET technologies. Other implementations for parts of the framework exist. Since the runtime engine is described by a ECMA/ISO specification, other implementations of it are unencumbered by copyright issues. It is more difficult to develop alternatives to the base class library (BCL), which is not described by an open standard, and may be subject to copyright restrictions. Additionally, parts of the BCL have Windows-specific functionality and behavior, so implementation on non-Windows platforms can be problematic.

Some alternative implementations of parts of the framework are listed here.

  • Microsoft's Shared Source Common Language Infrastructure is a shared source implementation of the CLR component of the .NET Framework. It runs on Microsoft Windows XP, FreeBSD, and Mac OS X 10.2.
  • Portable.NET (part of DotGNU) provides an implementation of the Common Language Infrastructure (CLI), portions of the .NET Base Class Library (BCL), and a C# compiler. It supports a variety of CPUs and operating systems.
  • Mono is an implementation of the CLI and portions of the .NET Base Class Library (BCL), and provides additional functionality. It is dual-licensed under free software and proprietary software licenses. Mono is being developed by Novell, Inc. It includes support for ASP.NET, ADO.NET, and evolving support for Windows Forms libraries. It also includes a C# compiler, and a VB.NET compiler is in pre-beta form.
  • CrossNet is an implementation of the CLI and portions of the .NET Base Class Library (BCL). It is free software. It parses .NET assemblies and generates unmanaged C++ code that can compiled and linked within any ANSI C++ application on any platform.

[edit] Support End of Life

.NET Framework 1.0: Mainstream support ended June 30th, 2007, extended support ends June 30th, 2009.

.NET Framework 1.1: September 30th, 2008 and September 30th, 2010 respectively. Since .NET 1.1 is a component of Windows Server 2003, extended support for .NET 1.1 on Server 2003 will run out when the OS does, currently June 30th, 2013.

.NET Framework Version .

.NET Framework 1.0

This is the first release of the .NET Framework. Released on February 13, 2002. Available for Windows 98, NT 4.0, 2000, and XP.

[edit] .NET Framework 1.1

This is the first major .NET Framework upgrade. It is available on its own as a redistributable package or in a software development kit, and was published on April 3, 2003. It is also part of the second release of Microsoft Visual Studio .NET (released as Visual Studio .NET 2003). This is the first version of the .NET Framework to be included as part of the Windows operating system, shipping with Windows Server 2003.

[edit] Changes since 1.0

  • Built-in support for mobile ASP.NET controls. Previously available as an add-on for .NET Framework, now part of the framework.
  • Security changes - enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet, and enable Code Access Security in ASP.NET applications.
  • Built-in support for ODBC and Oracle databases. Previously available as an add-on for .NET Framework 1.0, now part of the framework.
  • .NET Compact Framework - a version of the .NET Framework for small devices.
  • Internet Protocol version 6 (IPv6) support.
  • Numerous API changes.

[edit] .NET Framework 2.0

Released with Visual Studio .NET 2005, Microsoft SQL Server 2005, and BizTalk 2006.

[edit] Changes since 1.1

  • Numerous API changes.
  • A new hosting API for native applications wishing to host an instance of the .NET runtime. The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more (detailed reference). It was initially developed to efficiently host the runtime in Microsoft SQL Server, which implements its own scheduler and memory manager.
  • Full 64-bit support for both the x64 and the IA64 hardware platforms.
  • Language support for Generics built directly into the .NET CLR.
  • Many additional and improved ASP.NET web controls.
  • New data controls with declarative data binding.
  • New personalization features for ASP.NET, such as support for themes, skins and webparts.
  • .NET Micro Framework - a version of the .NET Framework related to the Smart Personal Objects Technology initiative.

[edit] .NET Framework 3.0

.NET Framework 3.0, formerly called WinFX, [11] includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems. It is also available for Windows XP SP2 and Windows Server 2003 as a download. There are no major architectural changes included with this release; .NET Framework 3.0 uses the Common Language Runtime of .NET Framework 2.0. [12] Unlike the previous major .NET releases, there was no .NET Compact Framework release made as a counterpart of this version.

.NET Framework 3.0 consists of four major new components:

[edit] .NET Framework 3.5

  • This version of the framework uses version 2.0 of the CLR (the same model as the use of CLR 2.0 in .NET Framework 3.0). However, it installs .NET Framework 2.0 SP1, which adds some methods and properties, required for .NET Framework 3.5 features such as LINQ, to the BCL classes in .NET Framework 2.0. These changes do not affect applications written for version 2.0 of the .NET Framework.[13]
  • Full support for .NET Framework 3.5 project types, as well as targeting .NET Framework 3.5 in builds, is included in Visual Studio 2008.
  • The source code of the Base Class Library in this release will be released under Microsoft Reference License.[1]
  • .NET Framework 3.5 SP1, codenamed "Arrowhead", will enhance support for occasionally connected applications.[14] and provide built-in support for the Microsoft ASP.NET MVC Framework.[15]
  • As with .NET Framework 1.0 and 2.0, a new .NET Compact Framework 3.5 will be released in tandem with this update, to provide e.g. LINQ, HTTP compression, and improved audio support for mobile devices.
  • Officially Released To Manufacturing (RTM) on 19 November 2007.

[edit] Changes

.NET Framework

.NET Framework

From Wikipedia, the free encyclopedia





.NET Framework
Developer Microsoft
Latest release 3.5.21022.8 / November 19, 2007
OS Windows XP, Windows 2003, Windows Vista and above
Genre System platform
License MS-EULA, BCL under Microsoft Reference License[1]
Website www.microsoft.com/net/



The Microsoft .NET Framework is a software component that is a part of Microsoft Windows operating systems. It has a large library of pre-coded solutions to common program requirements, and manages the execution of programs written specifically for the framework. The .NET Framework is a key Microsoft offering, and is intended to be used by most new applications created for the Windows platform.

The pre-coded solutions that form the framework's Base Class Library cover a large range of programming needs in areas including: user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. The class library is used by programmers who combine it with their own code to produce applications.

Programs written for the .NET Framework execute in a software environment that manages the program's runtime requirements. This runtime environment, which is also a part of the .NET Framework, is known as the Common Language Runtime (CLR). The CLR provides the appearance of an application virtual machine, so that programmers need not consider the capabilities of the specific CPU that will execute the program. The CLR also provides other important services such as security mechanisms, memory management, and exception handling. The class library and the CLR together compose the .NET Framework.

The .NET Framework is included with Windows Server 2003, Windows Server 2008 and Windows Vista, and can be installed on most older versions of Windows.




Design goals and principal features

Microsoft .NET Framework was designed with several intentions:

  • Interoperability - Because interaction between new and older applications is commonly required, the .NET Framework provides means to access functionality that is implemented in programs that execute outside the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and System.EnterpriseServices namespaces of the framework, and access to other functionality is provided using the P/Invoke feature.
  • Common Runtime Engine - Programming languages on the .NET Framework compile into an intermediate language known as the Common Intermediate Language, or CIL (formerly known as Microsoft Intermediate Language, or MSIL). In Microsoft's implementation, this intermediate language is not interpreted, but rather compiled in a manner known as just-in-time compilation (JIT) into native code. The combination of these concepts is called the Common Language Infrastructure (CLI), a specification; Microsoft's implementation of the CLI is known as the Common Language Runtime (CLR).
  • Language Independence - The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all possible datatypes and programming constructs supported by the CLR and how they may or may not interact with each other. Because of this feature, the .NET Framework supports development in multiple programming languages. This is discussed in more detail in Microsoft .NET Languages.
  • Base Class Library - The Base Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions, including file reading and writing, graphic rendering, database interaction and XML document manipulation.
  • Simplified Deployment - Installation of computer software must be carefully managed to ensure that it does not interfere with previously installed software, and that it conforms to increasingly stringent security requirements. The NET framework includes design features and tools that help address these requirements.
  • Security - The design is meant to address some of the vulnerabilities, such as buffer overflows, that have been exploited by malicious software. Additionally, .NET would provide a common security model for all applications.
  • Portability - A design goal of the .NET Framework is to remain platform agnostic, and thus be cross platform compatible. That is, a program written to use the framework should run without change on any type of system for which the framework is implemented. Microsoft's commercial implementations of the framework cover Windows, Windows CE, and the XBox 360. Microsoft has also released implementations that can run on some Unix-based platforms such as FreeBSD and Mac OSX, but license restrictions limit these to educational use only. In addition, Microsoft submits the specifications for the Common Language Infrastructure (which includes the core class libraries, Common Type System, and the Common Intermediate Language)[2][3][4], and the C# language[5], and the C++/CLI language[6] to both ECMA and the ISO, making them available as open standards. This makes it possible for third parties to freely implement compatible implementations of the framework and its languages on other platforms.

Architecture

Visual overview of the Common Language Infrastructure (CLI)
Visual overview of the Common Language Infrastructure (CLI)

[edit] CLI

The core aspects of the .NET framework lie within the Common Language Infrastructure, or CLI. The purpose of the CLI is to provide a language-agnostic platform for application development and execution, including functions for exception handling, garbage collection, security, and interoperability. Microsoft's implementation of the CLI is called the Common Language Runtime, or CLR. The CLR is composed of four primary parts:

[edit] Assemblies

Main article: .NET assembly

The intermediate CIL code is housed in .NET assemblies. As mandated by specification, assemblies are stored in the Portable Executable (PE) format, common on the Windows platform for all DLL and EXE files. The assembly consists of one or more files, but one of these must contain the manifest, which has the metadata for the assembly. The complete name of an assembly (not to be confused with the filename on disk) contains its simple text name, version number, culture and public key token. The public key token is a unique hash generated when the assembly is compiled; thus two assemblies with the same public key token are guaranteed to be identical. A private key can also be specified known only to the creator of the assembly and can be used for strong naming and to guarantee that the assembly is from the same author when a new version of the assembly is compiled (required to add an assembly to the Global Assembly Cache).




Metadata

Main article: .NET metadata

All CIL is Self-Describing through .NET metadata. The CLR checks on metadata to ensure that the correct method is called. Metadata is usually generated by language compilers but developers can create their own metadata through custom attributes. Metadata also contains information about the assembly. Metadata is also used to implement the reflective programming capabilities of .NET Framework.



Class library

Main article: Base Class Library

The Base Class Library, sometimes incorrectly referred to as the Framework Class Library (FCL) (which is a superset including the Microsoft.* namespaces), is a library of classes available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions such as file reading and writing, graphic rendering, database interaction, XML document manipulation, and so forth. The BCL is much larger than other libraries, but has much more functionality in one package.

[edit] Security

.NET has its own security mechanism, with two general features: Code Access Security (CAS), and validation and verification. Code Access Security is based on evidence that is associated with a specific assembly. Typically the evidence is the source of the assembly (whether it is installed on the local machine, or has been downloaded from the intranet or Internet). Code Access Security uses evidence to determine the permissions granted to the code. Other code can demand that calling code is granted a specified permission. The demand causes the CLR to perform a call stack walk: every assembly of each method in the call stack is checked for the required permission and if any assembly is not granted the permission then a security exception is thrown.

When an assembly is loaded the CLR performs various tests. Two such tests are validation and verification. During validation the CLR checks that the assembly contains valid metadata and CIL, and it checks that the internal tables are correct. Verification is not so exact. The verification mechanism checks to see if the code does anything that is 'unsafe'. The algorithm used is quite conservative and hence sometimes code that is 'safe' is not verified. Unsafe code will only be executed if the assembly has the 'skip verification' permission, which generally means code that is installed on the local machine.

.NET Framework uses appdomains as a mechanism for isolating code running in a process. Appdomains can be created and code loaded into or unloaded from them independent of other appdomains. This helps increase fault tolerance of the application, as faults or crashes in one appdomain does not affect rest of the application. Appdomains can also be configured independently with different security privileges. This can help increasing security of the application by separating potentially unsafe code. However, the developer has to split the application into subdomains, it is not done by the CLR.

[edit] Memory management

The .NET Framework CLR frees up the developer from the burden of managing memory (allocating and freeing up when done); instead it does the memory management itself. To this end, the memory allocated to instantiations of .NET types (objects) is done contiguously[7] from the managed heap, a pool of memory managed by the CLR. As long as there exists a reference to an object, which might be either a direct reference to an object or via a graph of objects, the object is considered to be in use by the CLR. When there is no reference to an object, and thus cannot be reached or used, it becomes garbage. However, it still holds on to the memory allocated to it. .NET Framework includes a garbage collector which runs periodically, on a separate thread than the application's thread, that enumerates all the unusable objects and reclaims the memory allocated to them.

The .NET Garbage Collector (GC) is a non-deterministic, compacting, mark-and-sweep garbage collector. The GC runs only when a certain amount of memory has been used or there is enough pressure for memory on the system. Since it is not guaranteed when the conditions to reclaim memory is reached, the GC runs are non-deterministic. Each .NET application has a set of roots , which are a set of pointers maintained by the CLR that point to objects on the managed heap (managed objects). These include references to static objects and objects defined as local variables or method parameters currently in scope, as well as objects referred to by CPU registers.[7] When the GC runs, it pauses the application, and for each objects referred to in the root, it recursively enumerates all the objects reachable from the root objects and marks the objects as reachable. It uses .NET metadata and reflection to discover the objects encapsulated by an object, and then recursively walk them. It then enumerates all the objects on the heap (which were initially allocated contiguously) using reflection and all the objects, not marked as reachable, are garbage.[7] This is the mark phase.[8] Since the memory held by garbage is not of any consequence, it is considered free space. However, this leaves chunks of free space between objects which were initially contiguous. The objects are then compacted together, by using memcpy[8] to copy them over to the free space to make them contiguous again.[7] Any reference to an object invalidated by moving the object is updated to reflect the new location by the GC.[8] The application is resumed after the garbage collection is over.

The GC used by .NET Framework is actually generational.[9] Objects are assigned a generation; newly created objects belong to Generation 0. The objects that survive a garbage collection are tagged as Generation 1, and the Generation 1 objects that survive another collection are Generation 2 objects. The .NET Framework uses up to Generation 2 objects.[9] Higher generation objects are garbage collected less frequently then lower generation objects. This helps increase the efficiency of garbage collection, as older objects tend to have a larger lifetime than newer objects.[9] Thus, by removing older (and thus more likely to survive a collection) objects from the scope of a collection run, fewer objects need to be checked and compacted.[9]

[edit] Standardization and licensing

In August 2000, Microsoft, Hewlett-Packard, and Intel worked to standardize CLI and the C# programming language. By December 2001, both were ratified ECMA standards (ECMA 335 and ECMA 334). ISO followed in April 2003 (ISO/IEC 23271 and ISO/IEC 23270).

While Microsoft and their partners hold patents for the CLI and C#, ECMA and ISO require that all patents essential to implementation be made available under "reasonable and non-discriminatory (RAND) terms." In addition to meeting these terms, the companies have agreed to make the patents available royalty-free.

However, this does not apply for the part of the .NET Framework which is not covered by the ECMA/ISO standard, which includes Windows Forms, ADO.NET, and ASP.NET. Patents that Microsoft holds in these areas may deter non-Microsoft implementations of the full framework.

On October 3, 2007, Microsoft announced that much of the source code for the .NET Framework Base Class Library (including ASP.NET, ADO.NET and Windows Presentation Foundation) will be made available with the final release of Visual Studio 2008 towards the end of 2007 under the shared source Microsoft Reference License.[1] The source code for other libraries including Windows Communication Foundation (WCF), Windows Workflow Foundation (WF) and Language Integrated Query (LINQ) will be added in future releases. Being released under the Microsoft Reference License means this source code is made available for debugging purpose only, primarily to support integrated debugging of the BCL in Visual Studio.

[edit] Versions

Microsoft started development on the .NET Framework in the late 1990s, originally under the name of Next Generation Windows Services (NGWS). By late 2000, the first beta versions of .NET 1.0 were being released. [10]

The .NET Framework stack.
The .NET Framework stack.
Version Name Version Number Release Date
Pre-beta ?.?.????.? 2000-07-11
1.0 Beta 1 1.0.????.0 November 2000
1.0 Beta 2 1.0.2914.0 2001-06-20
1.0 RTM 1.0.3705.0 2002-01-05
1.0 SP1 1.0.3705.209 2002-03-19
1.0 SP2 1.0.3705.288 2002-08-07
1.0 SP3 1.0.3705.6018 2004-08-31
1.1 RTM 1.1.4322.573 2003-04-01
1.1 SP1 1.1.4322.2032 2004-08-30
1.1 SP1 (W2k3) 1.1.4322.2300 2005-03-30
2.0 RTM 2.0.50727.42 2005-11-07
2.0 RTM (Vista) 2.0.50727.312 2007-01-30
2.0 (KB928365) 2.0.50727.832 2007-07-10
2.0 SP1 2.0.50727.1433 2007-11-19
3.0 RTM 3.0.4506.30 2006-11-06
3.0 RTM (Vista) 3.0.4506.26 2007-01-30
3.0 SP1 3.0.4506.648 2007-11-19
3.5 RTM 3.5.21022.8 2007-11-19

Introducing ADO.NET and the Typed DataSet

Introducing ADO.NET and the Typed DataSet

Introduction

Several weeks ago, I met with the CIO and development staff of a local customer. We discussed their current development strategies and project load. In the last several years they had developed several Visual Basic 6 and ASP based applications that had been extremely successful and represented the core application infrastructure for the business. These applications had become so successful that the business users had recently requested several new applications and pretty substantial enhancements to their existing applications. In reviewing these new requirements the CIO had made the decision that it was quicker and easier to rebuild the applications using .NET and design them using a Service Oriented Application approach.

In reviewing the applications it seemed everything they were doing involved database reads, writes, and manipulation. The development staff had been reviewing the articles and code samples for ADO.NET. They had spent many years refining their existing ADO based infrastructure and perfecting their use of ADO. The problem was when they starting looking at the .NET Framework, they found this new object called the DataSet. It seemed after all their research they continued to remain confused about this object when compared to the ADO recordset object they had used and loved for many years. In this article I will explain the benefits of ADO.NET and how the ADO.NET object model fits into the .NET Framework. Additionally, how the features of the DataSet object can be combined with XML to create a new type of object called the typed DataSet, which simplifies the task of data navigation.

ADO Revisited


Figure 1: The object structure for recordsets

The ADO recordset object represents a collection or records returned when a request is made to the database. This object represents the entire set of records returned from a base table or the complete results of an executed SQL command. At any time during the life of this object, it refers to a single record within the entire set of records. The object structure of the recordset collection is shown in Figure 1.

ADO contains the recordset object, which enables it to manipulate SQL data. One of the primary advantages of recordsets is the ability to loop through records stored in a recordset, accessing each of the individual records and changing, modifying, or deleting specific fields within each.

ADO also makes extensive use of cursors as the way of providing data views. Cursors enable the navigation between records in a recordset. The cursor actually sits on the current record specified in the recordset. The supported ADO cursor types are shown in Table 1.

Table 1: ADO cursor types

Cursor TypeDescription
Dynamic CursorEnables the viewing of additions, changes, and deletions made by other users and allows forward and backward movement through a recordset object.
Keyset cursors Acts the same as the dynamic cursor except that is prevents users from seeing records that others have added and prevents access to deleted records.
Static Cursor Provides a static copy of a set of records that allows the location of data. Enables forward and backward movement through the recordset. Additions, changes, or deletions by other users will not be visible.
Forward-only cursor Acts the same as the dynamic cursor except that is allows only forward scrolling. This improves performance and is the default type of recordset.

Note:
The recordset object automatically positions the current record as the first record and sets the Bottom of File (BOF) and End of File (EOF) properties to false. If there are no records, both the BOF and EOF properties are automatically set to true.



Defining a Recordset

Defining a recordset was a pretty trivial task that could be accomplished in less than 10 lines of code. For example, the following code shows how this can be done in an ASP page.

 
<html>
<body>
 
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("northwind.mdb"))
set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
 
do until rs.EOF
    for each x in rs.Fields
       Response.Write(x.name)
       Response.Write(" = ")
       Response.Write(x.value & "<br />") 
    next
    Response.Write("<br />")
    rs.MoveNext
loop
 
rs.close
conn.close
%>
 
</body>
</html>
 


Enter ADO.NET

ADO.NET is not an upgrade to ADO but a complete redesign. At the core of ADO.NET is a set of libraries that are designed to communicate with a variety of back-end data stores. The ADO.NET libraries are part of the System.Data namespace and encompass a variety of additional libraries that enable data source connection, query submission, and processing results. One of the goals of the redesign of ADO.NET was to provide a hierarchical, disconnected data cache that works offline and online. The central disconnected object, called the DataSet, allows the search, filtering, navigation and storage of pending data changes. The design of ADO.NET is based on XML and enables ADO.NET to bridge the gap between the traditional database access and XML development. Developers are able to work with both XML data and database data using a common set of data interfaces as shown in Figure 2.


Figure2: The ADO.NET Object Model

ADO.NET is designed to provide consistent access to common data sources through a managed data provider. This provides a common interface for data sources like SQL Server as well as those exposed through OLE-DB and XML interfaces. Each of the managed providers is designed specifically for the type of data access it will provide. These results can either be processed directly or placed in an ADO.NET DataSet object that can then be exposed to the user, combined together, or even remoted between application tiers.

One of the strongest advantages of the DataSet object is that it can be used independently within the .NET Framework to manage locally stored data or XML files. ADO has really been the mainstay of database access for years, but there were several inherent design issues that ADO.NET was created to overcome. One of the main problems that ADO.NET is designed to solve is the lack of features needed to easily build applications that were part of .NET and the Service Oriented Architecture. For example, XML was added as an afterthought to ADO as the standard started to emerge within the industry. ADO.NET on the other hand was designed based on XML. Additionally, the ADO cursor engine makes it possible to pass disconnected ADO recordset objects between tiers in applications, but it doesn't provide a way to combine multiple recordset objects together. ADO also provides a way to submit cached changes to the database but doesn't provide programmatic control over the logic used to submit the updates. One of the major limitations for developing scalable SOA based applications that is lacking within the ADO cursor engine is the ability to submit pending changes to the database via stored procedures. Many database administrators allow users to only modify the contents of their databases through stored procedures, which is not possible through the binary object of the ADO recordset object.

.NET Data Providers

Within the .NET Framework a data provider is a collection of classes designed to allow you to communicate with a specific type of data store. The .NET Framework comes pre-built with providers for SQL Server, OLE-DB sources, Oracle, and ODBC. In addition there are several additional providers that have been released independently including DB2 and MYSQL.

The OLE DB .NET Data Provider is designed to communicate with various data stores through the OLE DB providers. The SQL Client .NET Data provider is designed to solely communicate with SQL Server databases. Each of these managed providers implements the same base classes - Connection, Command, Data Reader, Parameter and Transaction. The names and specific namespaces may change depending on the specific provider and the underlying database requirements. For example, the SQL Managed Provider uses a SQLConnection object, while the OLE DB provider uses an OLEDbConnection object. Each provider is designed to take advantage of the specific performance and limitations of the specific data source.

Regardless of which .NET data provider you use, the provider's Connection object implements the same basic set of interfaces. When opening a connection to the data store, developers create an instance of the providers connection object, set the ConnectionString and then call its Open method.

Connecting to a Data Source

The connection object represents a connection to your data source. For SQL Server you use the namespace System.Data.SQLClient.SQLConnection, and for OleDB you use System.Data.OleDb.OleDbConnection. When specifying the datasource you can provide a variety of amplifying information that describes the data source that includes its location and connection type.

The connection object is similar to the ADO Connection object in that it is used to connect and disconnect from a data source. The connection object acts as the glue through which other objects like the DataAdaptor and the Command objects communicate with the database and submit queries and retrieve results. The following code example shows how to connect to a local SQL Server database using the managed provider.


Dim sqlConn As SqlConnection
Dim sqlCmd As SqlCommand
Dim strConstring As String
Dim intUserID As Integer

strConstring = ConfigurationSettings.AppSettings("constring")
strConstring = "Data Source=(local);Initial Catalog= _
Northwind;Integrated Security=SSPI"
sqlConn = New SqlConnection(strConstring)
sqlConn.Open()
Note:
The connection object also provides a BeginTransaction method that is used to create a Transaction object. This object is used to either commit or cancel the changes made to the database during the lifetime of the Transaction object.

DataAdapter Object

The DataAdapter is a new concept introduced to data access with the ADO.NET model. It acts as the bridge between the database and the disconnected objects in the ADO.NET object model. The DataAdaptor object's Fill method provides the mechanism to fetch the results of a query into a DataSet or a DataTable so that the data is easily accessed. The DataAdapter object is also used to submit pending changes stored in the DataSet back to the database.

The DataAdapter object is part of the Command object and exposes a variety of properties and methods. For example, the SelectCommand property contains a Command object that represents the query that is used to populate the DataSet object. Additionally, this object exposes the UpdateCommand, InsertCommand and DeleteCommand properties that correspond to the Command objects used when you submit modified, new or deleted data rows back to the database. With each of these properties you are able to call stored procedures or a SQL statement that performs the type of operation. Once completed you can call the Update method on the DataAdapter object, and ADO.NET will use the Command object created earlier to update the database as shown in the following code example.


Public Shared Function CreateCandyAdapter(ByVal conn As SqlConnection)_
As SqlDataAdapter

Dim da As SqlDataAdapter = New SqlDataAdapter
Dim cmd As SqlCommand
Dim parm As SqlParameter

' Create the SelectCommand.
cmd = New SqlCommand("sp_select", conn)
cmd.CommandType = CommandType.StoredProcedure

da.SelectCommand = cmd

' Create the UpdateCommand
cmd = New SqlCommand("sp_update", conn)
cmd.CommandType = CommandType.StoredProcedure

cmd.Parameters.Add("@CandyName", SqlDbType.VarChar, 5, "CandyName")
cmd.Parameters.Add("@CandyDescription", SqlDbType.VarChar, 40, _
"CandyPrice")

parm.SourceVersion = DataRowVersion.Original
da.UpdateCommand = cmd
Return da

End Function
In order to maintain what is happening to the database and the data, the DataAdapter object provides a variety of supporting properties that can track which tables in the database correspond to the tables in your DataSet object. The TableMappings collection is the property used to track which table in the database corresponds to which table in your DataSet object. Each table mapping has a similar property for mapping columns called a ColumnMappings collection.

Enter the DataSet

The DataSet object is central to supporting disconnected, distributed data scenarios using ADO.NET. This object is actually a memory resident representation of data that provides a consistent relational programming model regardless of the data source. The DataSet object represents a complete set of data including the related tables, constraints and relationships. Figure 3 shows the DataSet object model.


Figure 3: The Dataset object model.

The DataSet object as its name implies contains data. It provides a container for a number of DataTable objects that are stored in the DataSet's object tables collection. One of the biggest advantages of the DataSet is that you can package an entire structure into it. Instead of having to call multiple times into a middle tier object to retrieve data you can simply package the entire instance, including table references, directly into a single object that can be returned.

The data stored in the DataSet object is disconnected from the database. Any changes that are made are simply cached in a DataRow. When it's time to send the changes back the database, you can pass the entire object to the middle tier server. The DataSet provides a GetChanges method that can be used to extract only the modified rows from a DataSet. This enables specific changed rows to be extracted and passed and reduces the overhead of data across a network.

The DataSet also exposes a Merge method, which acts in conjunction with the GetChanges method. The middle tier server can submit changes to the database using the smaller DataSet returned by the Merge method and return a DataSet that contains the new data. Then using the Merge method this returned DataSet can then be merged back to the contents of the existing DataSet object as shown in the following example.


CandyDS.Merge(otherDS)
The DataSet also provides the ability to read and write data to it from a file or an area of memory. This means you can just save the contents of the DataSet object or the structure. ADO.NET stores the data as an XML document. It is important to remember that ADO.NET and XML are tightly coupled, which means that moving data between the two is an easy task. For example, the following code shows how to create a DataSet and then display the XML contents to the console.

Private Shared Sub DemonstrateGetXml()
' Create a DataSet with 1 table two columns and 10 rows.
Dim ds As DataSet = New DataSet("myDataSet")
Dim t As DataTable = ds.Tables.Add("Items")
t.Columns.Add("id", Type.GetType("System.Int32"))
t.Columns.Add("Item", Type.GetType("System.String"))

' Add ten rows.
Dim r As DataRow
Dim i As Integer
For i = 0 To 9
r = t.NewRow()
r("id") = i
r("Item")= "Item" & i
t.Rows.Add(r)
Next

' Display the DataSet contents as XML.
Console.WriteLine( ds.GetXml() )
End Sub

DataSet Web Services

Within the world of the Services Oriented Architecture, the Web Service is the basic unit of work. This means that often a Web Service is constructed to only return a set of data based on a query that the front-end application sends in. This provides a perfect use for the DataSet as a way of returning data. For example, the following code section shows how data can be returned directly from a Web Service using a DataSet.


Public Function GetRequests(ByVal RequestedStatus As
Boolean) As DataSet
'db connection
Dim sqlConn As SqlConnection
Dim sqlCmd As SqlCommand
Dim strConstring As String
Dim intUserID As Integer

strConstring = ConfigurationSettings.AppSettings("constring")
sqlConn = New SqlConnection(strConstring)
sqlConn.Open()
sqlCmd = New SqlCommand

With sqlCmd
.Connection = sqlConn
.CommandTimeout = 30
.CommandType = CommandType.StoredProcedure
If RequestedStatus = True Then
.CommandText = "spGetOpenRequests"
Else
.CommandText = "spGetClosedRequests"
End If

End With

Dim RequestDA As SqlDataAdapter = New SqlDataAdapter
RequestDA.SelectCommand = sqlCmd
Dim RequestDS As DataSet = New DataSet
RequestDA.Fill(RequestDS, "RequestType")

Return RequestDS
sqlConn.Close()

End Function
When a user accesses the data from a front-end application, he receives a stream of XML as shown in Figure 4.


Figure 4: XML returned from a DataSet object

The transportable nature of the DataSet and XML enables the client the ability to reconstitute the data on the receiving end as shown in the following example.


Dim ws As New localhost.wsSubmit
Dim xmlStatus As DataSet
xmlStatus = ws.GetRequests(RequestedStatus:=False)
One of the difficult parts of using the DataSet this way is that table, column, and row navigation can be difficult. The navigation is actually done through the combination of tables, columns, and rows that make up the DataSet.

Dim s As String
s = CType(dsCustomersOrders1.Tables("Customers")._
Rows(0).Item("CustomerID"), String)

Typed Vs. Untyped DataSets

The nature of a DataSet requires that it is either typed or untyped. By definition a typed DataSet is any DataSet that is derived from the base DataSet class that applies the information contained in the XSD to generate a typed class. Information from the schema that contains the tables, columns, and rows is generated and compiled into a new DataSet derived from the XSD and this promotes the DataSet to a first class object in the .NET Framework.

The process of inheriting the typed DataSet from the base DataSet class means that the typed class assumes all functionality of the DataSet class and can be used with methods that take an instance of the DataSet class as a parameter. This is the opposite of the untyped DataSet that has no corresponding schema and is exposed only as a collection.





Defining the Schema

The first step in defining a typed DataSet is to create the XSD that is used to control and provide structure for the DataSet. This can be done by adding a new XML schema to your project as shown in Figure 5.


Figure 5: Adding a new schema

This adds a new XSD item to your project. When defining the XSD structure, always make sure that you point to the existing Web Service namespace and provide a fully qualified name of the exposed DataSet, as shown in the following XSD.





<?xml version="1.0" encoding="utf-8" ?>

<xsd:schema id="candyTypeDataset"

targetNamespace="http://tempuri.org/CandyType.xsd"

elementFormDefault="qualified" xmlns="http://tempuri.org/CandyType.xsd"

xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:element name="candyTypeDataset">

<xsd:complexType>

<xsd:sequence>

<xsd:element name="candyType" minOccurs="0"

type="xsd:string" />

</xsd:sequence>

</xsd:complexType>

</xsd:element>

</xsd:schema>

The schema provides a structure that is used to define a set of classes. The schema shown above defines a single field as a string with the name "candyType". Once the schema is created, it can be viewed using the XML view of Visual Studio. This view shows the completed XML schema as shown in Figure 6.


Figure 6: Completed XSD view.

Once completed the XSD schema can be compiled into a typed DataSet using the right click menu located on the graphical XSD display as shown in Figure 7.


Figure 7: Generating a typed DataSet.

The compilation of the typed DataSet creates two additional files as shown in Figure 8.


Figure 8: Wrapper classes created in Visual Studio.

The first file which contains the .vb extension is used to define the proxy class that is generated when the DataSet is compiled. This class contains the methods and properties that are needed to access, manipulate, and serialize the DataSet. The second file with the .xsx extension contains information about the layout of the XSD on the design surface as shown in Figure 6.

Finishing the Web Service

Once created the typed DataSet is usable within the application as a first class object. This means that when the object is created IntelliSense is now aware of the objects and methods available within the object and displays these in the object viewer as shown in Figure 9.


Figure 9: Exposed typed DataSet objects.

This enables the object to be created and using the following code to fill the typed DataSet for return to the client.

<WebMethod()> Public Function GetCandyTypes() As candyTypeDataset

'db connection

Dim sqlConn As SqlConnection

Dim sqlCmd As SqlCommand

Dim strConstring As String

Dim intUserID As Integer

strConstring = ConfigurationSettings.AppSettings("constring")

sqlConn = New SqlConnection(strConstring)

sqlConn.Open()

sqlCmd = New SqlCommand

With sqlCmd

.Connection = sqlConn

.CommandTimeout = 30

.CommandType = CommandType.StoredProcedure

.CommandText = "sp_GetCandyType"

End With

Dim CandyDA As SqlDataAdapter = New SqlDataAdapter

CandyDA.SelectCommand = sqlCmd

Dim CandyDS As New candyTypeDataset

CandyDA.Fill(CandyDS, CandyDS.Tables(0).TableName)

Return CandyDS

sqlConn.Close()

End Function

When creating the WebMethod, it is important to provide a return value that matches the name of the typed DataSet. This is how the client becomes aware of the structure and is able to use the schema defined within the return stream. For example, if we run the above WebMethod and review the WSDL generated. We can see that the Namespace we created for the schema has been added as shown in Figure 10.


Figure 10: WSDL definition showing defined namespace.

If you review further down the WSDL you can see that the new XSD has been appended as shown in Figure 11.


Figure 11: Appended XSD

Client Retrieval

Once the Web Service is completed and the reference is set, any client can retrieve the data exposed by the typed DataSet. Once created the typed DataSet becomes an object that can be retrieved using the named properties directly from the client as shown in the code example below.

Dim ws As New localhost.SweetsService

Dim ds As localhost.candyTypeDataset

ds = ws.GetCandyTypes

Dim i As Integer

For i = 0 To (ds.candyTypeDataset.Count - 1)

Dim locButton As New Button

Dim ButFace As String

locButton.Text = ds.candyTypeDataset.Item(i).candyType

Me.Controls.Add(locButton)

Next

End Sub

It is important to understand that the navigation is now by property as shown above. This means that we don't have to navigate the underlying structure using the standard navigation of the DataSet, but are able to access field by property name.

Summary

At the end of the meeting, the CIO and the development team looked closely at the code samples that we had created and had a better understanding. I spoke with them the other day and was happy to hear that they had adopted ADO.NET and the type DataSet as a way of consuming and rendering their data. Hopefully while reading this article you have come to understand the benefits of ADO.NET and the typed DataSet. These include type checking at design time which gives the advantage of statement completion. For a developer this means fewer errors during runtime from misspellings and consistent navigation that is similar to the ADO.

In this article we have covered a lot of information about the features available within ADO.NET. By no means have we covered every aspect, but only scratched the surface. Hopefully you can now understand the features and benefits of ADO.NET and how important the typed DataSet is to application development. I certainly challenge all readers as I did with the staff that I was meeting with to start exploring these as a way of better developing your data access operations.

About the Author

Thom is a Senior Technology Specialist with Microsoft Corporation in New England. He specializes in working with customers on developing and implementing .NET based applications. He is a frequent speaker and contributor to various magazines. He is also a regular writer for his personal Weblog at http://radio.weblogs.com/0131777/. If you have comments or questions about this article, please visit his Weblog and contact him.