Академический Документы
Профессиональный Документы
Культура Документы
6464A S E
L E A E
R E
Visual Studio 2008®:
R
ADO.NET
A
R E W
P FT
SO
Be sure to access the extended learning content on your
Course Companion CD enclosed on the back cover of the book.
ii Visual Studio 2008®: ADO.NET
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for
any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
E
The names of manufacturers, products, or URLs are provided for informational purposes only and
S
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
A
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
E
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
L RE
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
E
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
R A
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
E
of Microsoft of the site or the products contained therein.
R W
© 2008 Microsoft Corporation. All rights reserved.
P FT
Microsoft, Access, Internet Explorer, MSDN, PowerPoint, SQL Server, Visual Basic, Visual C#, Visual
Studio, Windows and Windows Vista are either registered trademarks or trademarks of Microsoft
SO
Corporation in the United States and/or other countries.
If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. “Academic Materials” means the printed or electronic documentation such as manuals,
workbooks, white papers, press releases, datasheets, and FAQs which may be included in the
Licensed Content.
b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions
location, an IT Academy location, or such other entity as Microsoft may designate from time to time.
c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and
conducted at or through Authorized Learning Centers by a Trainer providing training to Students
solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or
“MOC”) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions
Courseware). Each Authorized Training Session will provide training on the subject matter of one
(1) Course.
d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning
Center during an Authorized Training Session, each of which provides training on a particular
Microsoft technology subject matter.
e. “Device(s)” means a single computer, device, workstation, terminal, or other digital electronic or
analog device.
f. “Licensed Content” means the materials accompanying these license terms. The Licensed
Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student
Content, (iii) classroom setup guide, and (iv) Software. There are different and separate
components of the Licensed Content for each Course.
g. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that
may be included with the Licensed Content.
h. “Student(s)” means a student duly enrolled for an Authorized Training Session at your location.
i. “Student Content” means the learning materials accompanying these license terms that are for
use by Students and Trainers during an Authorized Training Session. Student Content may include
labs, simulations, and courseware files for a Course.
j. “Trainer(s)” means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer
and b) such other individual as authorized in writing by Microsoft and has been engaged by an
Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its
behalf.
k. “Trainer Content” means the materials accompanying these license terms that are for use by
Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content
may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and
demonstration guides and script files for a Course.
l. “Virtual Hard Disks” means Microsoft Software that is comprised of virtualized hard disks (such as
a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single
computer or other device in order to allow end-users to run multiple operating systems concurrently.
For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”.
m. “Virtual Machine” means a virtualized computing experience, created and accessed using
Microsoft® Virtual PC or Microsoft® Virtual Server software that consists of a virtualized hardware
environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the
virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard
Disks will be considered “Trainer Content”.
n. “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
license terms.
2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and
electronic), Trainer Content, Student Content, classroom setup guide, and associated media.
License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center
location or per Trainer basis.
3. INSTALLATION AND USE RIGHTS.
a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may:
i. either install individual copies of the relevant Licensed Content on classroom Devices only for
use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided
that the number of copies in use does not exceed the number of Students enrolled in and the
Trainer delivering the Authorized Training Session, OR
ii. install one copy of the relevant Licensed Content on a network server only for access by
classroom Devices and only for use by Students enrolled in and the Trainer delivering the
Authorized Training Session, provided that the number of Devices accessing the Licensed
Content on such server does not exceed the number of Students enrolled in and the Trainer
delivering the Authorized Training Session.
iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to
use the Licensed Content that you install in accordance with (ii) or (ii) above during such
Authorized Training Session in accordance with these license terms.
i. Separation of Components. The components of the Licensed Content are licensed as a single
unit. You may not separate the components and install them on different Devices.
ii. Third Party Programs. The Licensed Content may contain third party programs. These license
terms will apply to the use of those third party programs, unless other terms accompany those
programs.
b. Trainers:
i. Trainers may Use the Licensed Content that you install or that is installed by an Authorized
Learning Center on a classroom Device to deliver an Authorized Training Session.
ii. Trainers may also Use a copy of the Licensed Content as follows:
A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for
your own personal training Use and for preparation of an Authorized Training Session.
B. Portable Device. You may install another copy on a portable device solely for your own
personal training Use and for preparation of an Authorized Training Session.
4. PRE-RELEASE VERSIONS. If this is a pre-release (“beta”) version, in addition to the other provisions
in this agreement, these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not
contain the same information and/or work the way a final version of the Licensed Content will. We
may change it for the final, commercial version. We also may not release a commercial version.
You will clearly and conspicuously inform any Students who participate in each Authorized Training
Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with
any further content, including but not limited to the final released version of the Licensed Content
for the Course.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to
Microsoft, without charge, the right to use, share and commercialize your feedback in any way and
for any purpose. You also give to third parties, without charge, any patent rights needed for their
products, technologies and services to use or interface with any specific parts of a Microsoft
software, Licensed Content, or service that includes the feedback. You will not give feedback that is
subject to a license that requires Microsoft to license its software or documentation to third parties
because we include your feedback in them. These rights survive this agreement.
c. Confidential Information. The Licensed Content, including any viewer, user interface, features
and documentation that may be included with the Licensed Content, is confidential and proprietary
to Microsoft and its suppliers.
i. Use. For five years after installation of the Licensed Content or its commercial release,
whichever is first, you may not disclose confidential information to third parties. You may
disclose confidential information only to your employees and consultants who need to know
the information. You must have written agreements with them that protect the confidential
information at least as much as this agreement.
ii. Survival. Your duty to protect confidential information survives this agreement.
iii. Exclusions. You may disclose confidential information in response to a judicial or
governmental order. You must first give written notice to Microsoft to allow it to seek a
protective order or otherwise protect the information. Confidential information does not
include information that
• becomes publicly known through no wrongful act;
• you received from a third party who did not breach confidentiality obligations to
Microsoft or its suppliers; or
• you developed independently.
d. Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs
you is the end date for using the beta version, or (ii) the commercial release of the final release
version of the Licensed Content, whichever is first (“beta term”).
e. Use. You will cease using all copies of the beta version upon expiration or termination of the beta
term, and will destroy all copies of same in the possession or under your control and/or in the
possession or under the control of any Trainers who have received copies of the pre-released
version.
f. Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta
version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If
Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you
for such copies and distribution.
5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.
a. Authorized Learning Centers and Trainers:
i. Software.
ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft
Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced
Server and/or other Microsoft products which are provided in Virtual Hard Disks.
A. If the Virtual Hard Disks and the labs are launched through the Microsoft
Learning Lab Launcher, then these terms apply:
Time-Sensitive Software. If the Software is not reset, it will stop running based upon the
time indicated on the install of the Virtual Machines (between 30 and 500 days after you
install it). You will not receive notice before it stops running. You may not be able to
access data used or information saved with the Virtual Machines when it stops running and
may be forced to reset these Virtual Machines to their original state. You must remove the
Software from the Devices at the end of each Authorized Training Session and reinstall and
launch it prior to the beginning of the next Authorized Training Session.
B. If the Virtual Hard Disks require a product key to launch, then these terms
apply:
Microsoft will deactivate the operating system associated with each Virtual Hard Disk.
Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized
Training Session, you will obtain from Microsoft a product key for the operating system
software for the Virtual Hard Disks and will activate such Software with Microsoft using such
product key.
C. These terms apply to all Virtual Machines and Virtual Hard Disks:
You may only use the Virtual Machines and Virtual Hard Disks if you comply with
the terms and conditions of this agreement and the following security
requirements:
o You may not install Virtual Machines and Virtual Hard Disks on portable Devices or
Devices that are accessible to other networks.
o You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at
the end of each Authorized Training Session, except those held at Microsoft Certified
Partners for Learning Solutions locations.
o You must remove the differencing drive portions of the Virtual Hard Disks from all
classroom Devices at the end of each Authorized Training Session at Microsoft Certified
Partners for Learning Solutions locations.
o You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or
downloaded from Devices on which you installed them.
o You will strictly comply with all Microsoft instructions relating to installation, use,
activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.
o You may not modify the Virtual Machines and Virtual Hard Disks or any contents
thereof.
o You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.
ii. Classroom Setup Guide. You will assure any Licensed Content installed for use during an
Authorized Training Session will be done in accordance with the classroom set-up guide for the
Course.
iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip
art, animations, sounds, music, shapes, video clips and templates provided with the Licensed
Content solely in an Authorized Training Session. If Trainers have their own copy of the
Licensed Content, they may use Media Elements for their personal training use.
iv. iv Evaluation Software. Any Software that is included in the Student Content designated as
“Evaluation Software” may be used by Students solely for their personal training outside of the
Authorized Training Session.
b. Trainers Only:
i. Use of PowerPoint Slide Deck Templates. The Trainer Content may include Microsoft
PowerPoint slide decks. Trainers may use, copy and modify the PowerPoint slide decks only for
providing an Authorized Training Session. If you elect to exercise the foregoing, you will agree
or ensure Trainer agrees: (a) that modification of the slide decks will not constitute creation of
obscene or scandalous works, as defined by federal law at the time the work is created; and
(b) to comply with all other terms and conditions of this agreement.
ii. Use of Instructional Components in Trainer Content. For each Authorized Training
Session, Trainers may customize and reproduce, in accordance with the MCT Agreement, those
portions of the Licensed Content that are logically associated with instruction of the Authorized
Training Session. If you elect to exercise the foregoing rights, you agree or ensure the Trainer
agrees: (a) that any of these customizations or reproductions will only be used for providing an
Authorized Training Session and (b) to comply with all other terms and conditions of this
agreement.
iii. Academic Materials. If the Licensed Content contains Academic Materials, you may copy and
use the Academic Materials. You may not make any modifications to the Academic Materials
and you may not print any book (either electronic or print version) in its entirety. If you
reproduce any Academic Materials, you agree that:
• The use of the Academic Materials will be only for your personal reference or training use
• You will not republish or post the Academic Materials on any network computer or
broadcast in any media;
• You will include the Academic Material’s original copyright notice, or a copyright notice to
Microsoft’s benefit in the format provided below:
Form of Notice:
© 2008 Reprinted for personal reference use only with permission by Microsoft
Corporation. All rights reserved.
Microsoft, Windows, and Windows Server are either registered trademarks or
trademarks of Microsoft Corporation in the US and/or other countries. Other
product and company names mentioned herein may be the trademarks of their
respective owners.
6. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed
Content. It may change or cancel them at any time. You may not use these services in any way that
could harm them or impair anyone else’s use of them. You may not use the services to try to gain
unauthorized access to any service, data, account or network by any means.
7. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some
rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you
more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that
only allow you to use it in certain ways. You may not
• install more copies of the Licensed Content on classroom Devices than the number of Students and
the Trainer in the Authorized Training Session;
• allow more classroom Devices to access the server than the number of Students enrolled in and the
Trainer delivering the Authorized Training Session if the Licensed Content is installed on a network
server;
• copy or reproduce the Licensed Content to any server or location for further reproduction or
distribution;
• disclose the results of any benchmark tests of the Licensed Content to any third party without
Microsoft’s prior written approval;
• work around any technical limitations in the Licensed Content;
• reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent
that applicable law expressly permits, despite this limitation;
• make more copies of the Licensed Content than specified in this agreement or allowed by applicable
law, despite this limitation;
• publish the Licensed Content for others to copy;
• transfer the Licensed Content, in whole or in part, to a third party;
• access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not
been authorized by Microsoft to access and use;
• rent, lease or lend the Licensed Content; or
• use the Licensed Content for commercial hosting services or general business purposes.
• Rights to access the server software that may be included with the Licensed Content, including the
Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft
intellectual property in software or devices that may access the server.
8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and
regulations. You must comply with all domestic and international export laws and regulations that apply
to the Licensed Content. These laws include restrictions on destinations, end users and end use. For
additional information, see www.microsoft.com/exporting.
9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed
Content marked as “NFR” or “Not for Resale.”
10. ACADEMIC EDITION. You must be a “Qualified Educational User” to use Licensed Content marked as
“Academic Edition” or “AE.” If you do not know whether you are a Qualified Educational User, visit
www.microsoft.com/education or contact the Microsoft affiliate serving your country.
11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you
fail to comply with the terms and conditions of these license terms. In the event your status as an
Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is
terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this
agreement, you must destroy all copies of the Licensed Content and all of its component parts.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-
based services and support services that you use, are the entire agreement for the Licensed
Content and support services.
13. APPLICABLE LAW.
a. United States. If you acquired the Licensed Content in the United States, Washington state law
governs the interpretation of this agreement and applies to claims for breach of it, regardless of
conflict of laws principles. The laws of the state where you live govern all other claims, including
claims under state consumer protection laws, unfair competition laws, and in tort.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws
of that country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the
laws of your country. You may also have rights with respect to the party from whom you acquired the
Licensed Content. This agreement does not change your rights under the laws of your country if the
laws of your country do not permit it to do so.
15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed “as-is.” You bear the risk of
using it. Microsoft gives no express warranties, guarantees or conditions. You may have
additional consumer rights under your local laws which this agreement cannot change. To
the extent permitted under your local laws, Microsoft excludes the implied warranties of
merchantability, fitness for a particular purpose and non-infringement.
16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT
RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL,
INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to
• anything related to the Licensed Content, software, services, content (including code) on third party
Internet sites, or third party programs; and
• claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in
this agreement are provided below in French.
Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre
garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont
exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES
DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de
dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation
pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de
bénéfices.
Cette limitation concerne:
• tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers ; et
• les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte,
de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel
dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages
indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne
s’appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de
votre pays si celles-ci ne le permettent pas.
Visual Studio 2008®: ADO.NET iii
Contents
Module 1: Getting Started with ADO.NET
Lesson 1: Introduction to ADO.NET 3.5 1-3
Lesson 2: Connecting to a Database and Retrieving Data 1-7
Lesson 3: Best Practices for Managing Connections and Performing Queries 1-15
Lab: Connecting to a Database and Retrieving Data 1-22
E
Module 2: Modifying Data by Using ADO.NET Commands
S
Lesson 1: Inserting, Updating and Deleting Data 2-3
E A
Lesson 2: Managing Data Integrity and Concurrency
L RE
Lab: Modifying Data by Using ADO.NET Commands
2-8
2-14
R E A
R E W
Module 3: Querying and Maintaining Data by Using DataSets
P FT
Lesson 1: Creating and Using a DataSet to Retrieve Data 3-3
Lesson 2: Updating a Database by Using a DataSet 3-10
SO
Lesson 3: Using a DataSet in an Occasionally Connected Environment 3-16
Lab: Querying and Maintaining Data by Using DataSets 3-19
E
Synchronization Services
S
Lesson 1: Understanding Microsoft Synchronization Services 6-3
E A
Lesson 2: Downloading Data by Using Synchronization Services 6-7
L RE
Lesson 3: Uploading Data by Using Synchronization Services 6-12
R E
Lab: Building Occasionally Connected Solutions by Using Synchronization
A
E
Services 6-17
R W
Course Evaluation 6-33
P FT
SO
About This Course i
Course Description
This two-day instructor-led course describes the key features of application
development with Microsoft® database development technologies, including
Microsoft Visual Studio® 2008 and Microsoft ADO.NET 3.5. It explains how to
develop an application that can insert, delete, and update database records in both
a connected and occasionally connected scenario.
Audience
This course is intended for application developers. You should know how to build
windows forms and how to use the common features of the base class library. You
should have a basic understanding of Relational Database Management System
databases and Transactional Structured Query Language. You do not have to
understand concepts such as advanced UI threading and asynchronous
programming. You also do not require experience building Visual Studio add-ins
or custom designers.
Student Prerequisites
In addition to your professional experience, students who attend this training
should have technical knowledge equivalent to the following:
Intermediate experience of application development by using previous versions of
Microsoft Visual Studio. (Level 200).
Course Objectives
After completing this course, you will be able to:
• Use ADO.NET commands to insert, delete and modify database records.
• Use Datasets to access tables in an occasionally connected application.
• Use Language-Integrated Query (LINQ) to insert, delete and modify database
records.
• Use the Entity Framework for ADO.NET and Entity SQL to develop code that
insert, delete, and modify entities in a conceptual model.
• Use Synchronization Services to insert, delete, and modify records in an
occasionally connected application.
ii About This Course
Course Materials
The following materials are included with your kit:
• Course Handbook. The Course Handbook contains the material covered in
class. It is meant to be used in conjunction with the Course Companion CD.
• Course Companion CD. The Course Companion CD contains the full course
content, including expanded content for each topic page, full lab exercises and
answer keys, topical and categorized resources, and Web links. It is meant to
be used both inside and outside the class.
Note: To access the full course content, insert the Course Companion CD into the CD-
ROM drive, and then in the root directory of the CD, double-click StartCD.exe.
About This Course iii
Important: At the end of each lab, you must close the virtual machine and must not
save any changes. To close a virtual machine without saving the changes, perform
the following steps: 1. On the host computer, click Start, point to All Programs,
point to Microsoft Virtual Server, and then click Virtual Server Administration
Website. 2. Under Navigation, click Master Status. For each virtual machine that is
running, right-click the virtual machine name, click Turn off Virtual Machine and
Discard Undo Disks, and then click OK.
The following table shows the role of each virtual machine used in this course.
Software Configuration
The following software is installed on each virtual machine:
• Windows Vista® Enterprise
• Microsoft Visual Studio 2008
iv About This Course
Course Files
There are files associated with the labs in this course. The lab files are located in
the folder E:\Labfiles on the student computers.
Classroom Setup
Each classroom computer will have the same virtual machine configured in the
same way. The virtual machines do not need to be connected to a network.
Module 1
Getting Started with ADO.NET 3.5
Contents:
Lesson 1: Introduction to ADO.NET 3.5 1-3
Lesson 2: Connecting to a Database and Retrieving Data 1-7
Lesson 3: Best Practices for Managing Connections and Performing Queries 1-15
Lab: Connecting to a Database and Retrieving Data 1-22
1-2 Visual Studio® 2008: ADO.NET
Module Overview
Key Points
ADO.NET is a collection of classes that enables you to access data in a data source.
A data provider is a collection of ADO.NET classes that enable you to access data
from a specific data source. ADO.NET provides classes that access data through
disconnected datasets and also supplies data binding to controls.
Question: When you would use data through a data provider connection, and
when would you use disconnected data?
Getting Started with ADO.NET 3.5 1-5
Key Points
ADO.NET includes .NET Framework data providers that enable you to connect to
a database, execute commands, and retrieve results. The .NET Framework data
providers create a minimal layer between the data source and your code, which
increases performance and does not sacrifice functionality.
1-6 Visual Studio® 2008: ADO.NET
Key Points
ADO.NET 3.5 is a collection of classes that is part of the .NET Framework library.
In addition, Visual Studio 2008 provides tools that use ADO.NET classes in your
code, and Visual C# and Visual Basic have language features for embedding data
access in code. In addition, Visual Studio 2008 designers generate ADO.NET code
for you.
Getting Started with ADO.NET 3.5 1-7
This lesson shows how to create a connection to a data source, issue a command,
and then retrieve the data by using typed classes for the SQL Server data provider.
1-8 Visual Studio® 2008: ADO.NET
Connecting to a Database
Key Points
To create a connection you use one of the connection classes that implement
IDbConnection and supply a connection string. To create the connection, you
then call Open.
Because connection objects hold limited resources, when you have finished with a
connection object, you must release those resources. To do this, you can call the
Dispose method on the object to release it. You can also call the Close method or
use the object in a Using statement (Visual Basic) or a using statement (Visual
C#).
Question: Why is the Using statement important, and what problems might you
experience when you use it?
Getting Started with ADO.NET 3.5 1-9
Key Points
Two types of exceptions can be generated when you open a connection:
InvalidOperationException exception object is generated by the data provider on
the client computer and SqlException exception object contains errors that are
generated by the data source on the server.
Question: Can you identify some of the error conditions that are returned through
SqlException exception object?
1-10 Visual Studio® 2008: ADO.NET
Key Points
To retrieve data from a database, you must create a command object, initialize it
with information about the command, and then execute the command. If the
command returns results, you obtain a resultset through a DbDataReader object
(for the SQL Server data provider this is a SqlDataReader object). To populate the
DbDataReader object with the next row, you call the Read method and then you
can call members to obtain the columns of this row. You must close the
DbDataReader object after you have finished using it.
Question: Why do you think it is important that you close the DbDataReader
object after you have finished using it?
Getting Started with ADO.NET 3.5 1-11
Key Points
Data sources have their own data types and when you execute a command the
results that are returned use those data types. To make data useful for your code, it
must be converted into .NET Framework data types. The data provider classes
derived from the DbDataReader and DbParameter classes perform these
conversions for you.
Key Points
The SqlCommand command is not executed until the Read method is called the
first time, so if there is an error in the command you only receive these when the
Read method is called. If you perform an asynchronous call you must open the
SQL Server connection specifically to support asynchronous calls, however, if you
omit to do this the exception only occurs when the first asynchronous call is
attempted on a data reader object. You receive errors from the data source in a
SqlException exception object which has a collection of SqlError objects: one for
each SQL Server error generated.
Question: When you execute a command at what point in your code may
exceptions be thrown?
Getting Started with ADO.NET 3.5 1-13
Key Points
A connection object holds a connection to the data source. The data source
connection is a scarce resource and therefore you should only maintain this
connection for as little time as necessary. To do this you should ensure that when
you have finished using a connection you call the Close method.
Question: What is the difference between the Dispose and Close method? When
would you use each one?
1-14 Visual Studio® 2008: ADO.NET
Data
Getting Started with ADO.NET 3.5 1-15
Key Points
The connection string determines which server and which database you connect
to, so if you hard code this into your application, the database cannot be renamed,
nor can you move the database to another computer. You can store the connection
string in a separate file.
Key Points
Database connections are expensive resources to create. If your application uses
many connections then it makes sense to reuse them. To cut down on the time
taken to create connections, the SQL Server data provider uses a connection pool.
When you create a connection it is put into the pool and when your code closes a
connection the connection is not closed, but instead the entry in the pool is
marked as free so that it can be reused. The best way to use pooled connections is
to open connections as late as possible and close them as early as possible.
Key Points
Commands that are involved with an inter-process call may also involve a call to
another computer: this takes time and means that the thread is blocked until the
command completes. This means that the calling thread cannot do any work,
which is catastrophic if the calling thread is the main thread in a Windows Forms
application because it means that Windows messages are not be handled. You can
prevent this from happening by calling the command asynchronously, by creating
a connection that supports asynchronous calls.
Question: Why would you use the SQL Server asynchronous methods rather than
calling a delegate asynchronously?
Getting Started with ADO.NET 3.5 1-19
Key Points
It is important that you close various data provider objects such as the connection
object and the data reader object. If the command returns a single (or no) value
then it is easy to forget to close objects like the data reader. The DbCommand class
has methods that wrap the ExecuteReader method so that it hides the
DbDataReader object and ensures that this object is closed before the wrapper
method returns.
Question: What examples of commands can you think of that only return a single
value?
1-20 Visual Studio® 2008: ADO.NET
Key Points
Parameterized commands are useful for two reasons. First, if you call a
parameterized command several times, data sources can recognize these as being
the same command and optimize its execution. Second, they help to prevent SQL
injection attacks.
Key Points
Each data provider must supply a DbProviderFactory class that you can use to
create data provider objects for the data provider. You use references to the
provider-independent abstract base classes and so that your code is generic even
though the actual objects are specific to the data provider.
Question: Under what circumstances would data provider agnostic data access
code be used?
1-22 Visual Studio® 2008: ADO.NET
Data
Column Value
Name ContosoMedicalDBConnectionString
Note: Saving the values adds an app.config file to the project with the connection
string you have just added, however the wizard gives the value a name which
enables it to be used with the My.Settings (Visual Basic) or Properties.Settings
(Visual C#) class. You will not use these classes, so to make the code easier to read
you should rename the value name.
3. Open the app.config file in the editor. Check that the designer has added a
<connectionStrings> element and, below that, there is an <add> element with
the values that you entered in step 5 of Task 2.
4. Change the name attribute to ContosoMedicalDBConnectionString.
5. Save the changes.
Getting Started with ADO.NET 3.5 1-25
Note: The project file is empty (Visual Basic) or has an empty namespace called
ContosoMedicalUtilities (Visual C#). You will add the skeleton code for this class
from an existing file.
2. Copy the code from Ex1_Task4.txt (in the E:\Labfiles\Starter\VB for Visual
Basic or E:\Labfiles\Starter\CS for Visual C#) into the ContosoMedicalDAC
source file.
Results: After this exercise, you should have created a project that compiles correctly
and can call GetConnection without throwing an exception.
Results: After this exercise, the Get Count button should show a dialog with the
number of doctors in the database.
• Call the ExecuteReader method so that the reader object closes the
connection object (CommandBehavior.CloseConnection).
• Return the reader object from the method.
Note: For Visual C#, you use \t for the tab character. For Visual Basic you use the
Chr(9) function to insert the tab character into the string.
Results: After this exercise, you should have an application that can show all of the
doctors in the database in the list box.
Getting Started with ADO.NET 3.5 1-29
Scenario
In this exercise you will write code to execute a stored procedure in the database.
The stored procedure will return all of the doctors that have the specialty provided
through a parameter.
The main tasks for this exercise are as follows:
1. Review the stored procedure.
2 Review the Doctor class.
3. Implement the GetDoctorsForSpecialty method.
4. Implement the ShowDoctorsForSpecialty method.
5. Build and run the project.
1. In the code file for the data access component, scroll to the
GetDoctorsForSpecialty method. Copy and paste the contents of the
Ex4_Task2.txt file (E:\Labfiles\Starter\VB for Visual Basic or
E:\Labfiles\Starter\CS for Visual C#) for the implementation of this method.
2. Review the code you have just copied. This code:
• Obtains a connection from the GetConnection method.
• Creates a command to call the uspGetDoctorsForSpecialty stored
procedure.
• Initializes the @specialty parameter with the specialty requested.
• Initializes the out parameter @doctorCount and return value parameter.
• Executes the comment and uses the rowset to initialize a List<> object of
Doctor objects.
• Initializes the ByRef (out) parameters with return parameter from the
command.
• Closes the connection.
Results: After this exercise, the application should list the doctors who have a specialty
that you provide.
1-32 Visual Studio® 2008: ADO.NET
Review Questions
1. Why was it important to make GetConnection a Private function?
This method creates a connection object and returns it. A class invariant is that
every method that calls the GetConnection function must close the
connection. Every method in this class obeys this rule. If this function was
made Public then you cannot guarantee that callers will close the connection.
2. In GetNumberOfDoctors, why was the connection closed in the Finally
clause?
The connection must be closed in this method, regardless of how the method
completes. The Finally clause has code that is executed whenever code
execution leaves the Try block, regardless of how that happens. So if the Try
block has a Return, a GoTo, or even if an exception is thrown, the Finally
block is still called.
Getting Started with ADO.NET 3.5 1-33
behavior in GetAllDoctors?
The connection must be open when you access the SqlDataReader object, so
you must close the connection when you have finished using this object. The
GetAllDoctors method returns the reader object so this means that you
cannot close the connection in this method. Instead, the CloseConnection
behavior means that the SqlDataReader object closes the connection when the
reader object is closed, which will happen in the method that calls the
GetAllDoctors method.
Application memory usage problems Check to see if you are closing connections
and data readers after you have finished using
them. Consider using Max Pool Size.
Problems retrieving data Check the command strings you are using,
they may have spelling mistakes. Test query
strings by using a tool such as sqlcmd. If a
query has parameters consider using a stored
procedure.
Module 2
Modifying Data by Using ADO.NET Commands
Contents:
Lesson 1: Inserting, Updating and Deleting Data 2-3
Lesson 2: Managing Data Integrity and Concurrency 2-8
Lab: Modifying Data by Using ADO.NET Commands 2-14
2-2 Visual Studio® 2008: ADO.NET
Module Overview
This lesson describes the classes in ADO.NET that enable you to change the data in
a database, and how to handle errors that might be returned from the database.
2-4 Visual Studio® 2008: ADO.NET
Key Points
A command to modify data does not return a rowset; the only data that is returned
is the number of rows affected by the command. To execute the operation, you
create an ADO.NET command object, initialize the object with the command, and
then execute it by invoking the ExecuteNonQuery method.
Key Points
Your command might perform an action on the database that is invalid. The server
returns an error as a SqlException exception that you can catch in your code. The
Errors collection contains details about the errors.
Key Points
If a command is likely to take a long time to perform, you should not execute the
command on the main thread of a graphical application because this blocks all of
the processing of Windows messages. Such commands should be performed on a
separate thread as an asynchronous command.
Question: What visible effects are you likely to see if the main thread of a graphical
application is blocked by the performance of a lengthy operation?
Modifying Data by Using ADO.NET Commands 2-7
Transactions are an important part of data access because they ensure data
integrity. However, by their nature, transactions restrict access to data, and so
Microsoft® SQL Server® 2005 has settings that enable you to relax these
restrictions according to the type of access operation that you want to perform.
This lesson will explain how to create and use transactions effectively.
Modifying Data by Using ADO.NET Commands 2-9
Overview of Transactions
Key Points
The Atomicity, Consistency, Isolation, Durability (ACID) properties are the classic
description of the properties that all transactions should have: atomic, consistent,
isolated, and durable.
Question: What would happen if transactions are not used when transferring
money from one bank account to another, and an error occurs before the second
account is credited?
2-10 Visual Studio® 2008: ADO.NET
Key Points
In a multi-user system more than one user may try to update a row. The
concurrency model determines whether multiple users have concurrent access to
the same row.
Question: Can you identify tables that do not need concurrent access?
Question: Can you identify tables that should always allow concurrent access?
Modifying Data by Using ADO.NET Commands 2-11
Key Points
Transactions are isolated items of work. However, complete isolation can affect the
performance of your application if it runs more than one transaction at the same
time on the same table. The isolation level allows you to relax isolation and enables
you to improve concurrency.
Question: Which of these isolation levels, which gives the most concurrent access,
and which gives the most isolation?
2-12 Visual Studio® 2008: ADO.NET
Key Points
Depending on the isolation level used, a transaction locks data at some point,
which consumes server resources that are deemed to be expensive. To use
transactions efficiently you should keep the transaction as short as possible. You
can also choose an isolation level to improve concurrency.
Question: Why should you keep the lifetime of a transaction as short as possible?
Modifying Data by Using ADO.NET Commands 2-13
Commands
retrieves the information for a patient by using the Patient ID and uses this
data to update the controls on the form. To implement this method, paste the
contents of the Ex1_Task2_getPatient_Click.txt file.
• Go to the folder E:\Labfiles\Starter\VB (Visual Basic).
• Go to the folder E:\Labfiles\Starter\CS (Visual C#).
7. In Microsoft Visual Studio® 2008, open the Data Access Component source file
in the ContosoMedicalUtilities project. Open the source file is named:
• ContosoMedicalDAC.vb (Visual Basic).
• ContosoMedicalDAC.cs (Visual C#).
8. Implement the GetPatient method. The code for this method is in the
Ex1_Task2_GetPatient.txt file. This code performs the following steps:
• Opens a database connection.
• Creates a command to execute the uspGetPatient stored procedure.
• The stored procedure has an in parameter so the code initializes the
parameter on the command object.
• Calls the ExecuteReader to obtain a SqlDataReader object for the
command.
• Reads the first and only row in the SqlDataReader object and uses the
data to initialize the Patient object that is returned from the function.
9. Build and run the application. When the application starts:
• Click the Patients tab.
• In the Patient ID box, type 1
• Click Get Patient.
10. Verify that the following values are returned.
Control Value
@lastName patient.LastName
@gender patient.Gender
@dateOfBirth patient.DateOfBirth
5. Add code to add an output parameter named @patientID to the command for
the stored procedure.
6. Write code to get the PatientID from the @patientID parameter.
7. Build the project and confirm that there are no compiler errors.
2-18 Visual Studio® 2008: ADO.NET
the returned Patient ID because you will use it in the following tasks.
9. Close the application.
@firstName patient.FirstName
@lastName patient.LastName
@gender patient.Gender
@dateOfBirth patient.DateOfBirth
3. Build the project and confirm that there are no compiler errors.
Modifying Data by Using ADO.NET Commands 2-19
added in the last task. Use the number you obtained in the last task in the
Patient ID control.
5. Alter the patient data and then click Update.
6. Verify that the patient data is updated in the database.
3. Build the project and confirm that there are no compiler errors.
4. Run the application and, on the Patients tab, delete the patient that you added
in the last task. Use the number you obtained in the last task in the Patient ID
control.
5. Verify that the patient is deleted in the database.
Results: After this exercise, you should have written code that retrieves, inserts,
changes, and deletes patient data in the database.
2-20 Visual Studio® 2008: ADO.NET
Scenario
The DeletePatient method that you implemented in the last exercise deletes
patient information from the Patients table and archives information about this
patient in the ArchivedPatients table. This is an operation that should be carried
out under a transaction because if it is not possible to archive the data in the
ArchivedPatients table, the data should not be removed from the Patients table.
In this exercise you will change the DeletePatient method to use a transaction and
test this code by using a special value for the patient name that will cause
uspArchivePatient to fail.
The main tasks for this exercise are as follows:
1. Examine the ArchivedPatients table.
2. Add transactional behavior to the DeletePatient method.
3. Verify that the transaction commits if all of the operations succeed..
4. Verify that the transaction rolls back if an error occurs.
[Visual Basic]
Modifying Data by Using ADO.NET Commands 2-21
[Visual C#]
SqlTransaction transaction = null;
[Visual Basic]
Dim command As New SqlCommand( _
"uspDeletePatient", connection, transaction)
[Visual C#]
SqlCommand command = new SqlCommand(
"uspDeletePatient", connection, transaction);
Control Value
3. Delete the patient that you just inserted. Verify that the Cannot archive
Dummy Patient dialog is shown.
4. Confirm that the patient data was not deleted by retrieving the data again from
the database by clicking Get Patient.
Results: After this exercise, you should have implemented transactional semantics for
the Delete button, so that either items are deleted and archived as one operation, or
do not happen at all.
Asynchronous Processing=true
3. On the Patients tab, open the first patient by typing 1 in the Patient ID
control and clicking Get Patient.
4. Click Upload New Photo, and in the Open File dialog box, select female.jpg
in the E:\Labfiles\Starter folder.
5. In the Open File dialog box, click OK to see the photograph, which will
appear immediately on the form, and three seconds later you will see the
Photo saved successfully dialog box which indicates that the operation to
write the data into the database completed.
[Visual Basic]
GetPhoto(Int32.Parse(patientID))
[Visual C#]
GetPhoto(int.Parse(patientID));
called and harvests the results of the call. This method uses the data to
update the user interface, which is has to do on the user interface thread,
and so it calls BeginInvoke by passing a delegate to GetPhotoUI.
• The GetPhotoUI method accesses the SqlDataReader object created as a
result of the command, reads the binary data, and uses the data to update
the photograph control.
Results: After this exercise, you should have implemented asynchronous reads and
writes of data to the database. You should also have handled all user interface updates
on the user interface thread.
2-26 Visual Studio® 2008: ADO.NET
Review Questions
1. In the lab, why did you use BeginInvoke in the callback method?
The callback method is called on the thread that executes the command
asynchronously. This is not the user interface thread. The user interface can
only be changed by the user interface thread and you do this by calling
BeginInvoke by passing a delegate to the method that updates the user
interface.
2. Why would you relax the isolation level of a transaction?
If you use the most isolated level, rows used by the transaction are locked until
the transaction completes. This has the effect of serializing operations so that
they perform one after each other and, for a multi-user system, this affects the
overall performance of the system. If you relax the isolation level then you can
increase concurrency and prevent the blocking of users.
3. Why make transactions isolated at all?
Modifying Data by Using ADO.NET Commands 2-27
concurrency to make sure that the data that one user reads truly reflects the
data in the row. Only by careful analysis of the application can you determine
the concurrency model that is best for your application.
Best Practices
Supplement or modify the following best practices for your own work situations:
• Use transactions to make two or more operations atomic.
• Use the transaction isolation level to control concurrency.
• Keep the transaction time as short as possible.
• Integrate transaction rollback as part of your error handling.
Querying and Maintaining Data by Using DataSets 3-1
Module 3
Querying and Maintaining Data by Using
DataSets
Contents:
Lesson 1: Creating and Using a DataSet to Retrieve Data 3-3
Lesson 2: Updating a Database by Using a DataSet 3-10
Lesson 3: Using a DataSet in an Occasionally Connected Environment 3-16
Lab: Querying and Maintaining Data by Using DataSets 3-19
3-2 Visual Studio® 2008: ADO.NET
Module Overview
Overview of DataSets
Key Points
A DataSet object is an in-memory cache of data that is typically retrieved from a
database.
A DataSet can contain any number of DataTable objects. Each DataTable contains
a collection of columns that define the schema of the table, and a collection of rows
that contain the data for the table.
You can define relations and constraints between the DataTable objects in a
DataSet, to represent the corresponding relationships between tables in the
database.
Question: What tables and relations might you define for DataSet objects in your
own applications?
Querying and Maintaining Data by Using DataSets 3-5
Key Points
The System.Data.DataSet class is an untyped DataSet class. To access tables and
columns in an untyped DataSet, you must specify the index or string literal name
of the table or column. If you specify an invalid index or string literal name, a run
time exception occurs.
A typed DataSet is a class that you generate by using Micosoft Visual Studio®
wizards, and contains nested properties and classes that provide type-safe access to
the tables and columns. If you specify an invalid table name or column name, you
obtain a compile time error instead of a run time exception.
3-6 Visual Studio® 2008: ADO.NET
Key Points
ADO.NET 3.5 is a collection of classes that is part of the .NET Framework library.
In addition, Visual Studio® has designers that generate ADO.NET code for you.
Querying and Maintaining Data by Using DataSets 3-7
Key Points
When you create a typed DataSet class, Visual Studio generates TableAdapter
classes that provide Fill methods to fill each table in the DataSet.
If you are using an untyped DataSet, you can fill the DataSet by using a
DataAdapter class such as SqlDataAdapter. To specify the SQL query that will
retrieve data from the database, you must set the SelectCommand property on the
DataAdapter object. You can then invoke the Fill method on the DataAdapter
object, which executes the SQL query and fills a table in the DataSet.
Querying and Maintaining Data by Using DataSets 3-9
Key Points
To access rows in a typed DataSet table, you use the Rows property to get a
collection of rows, and then access columns in each row by using type-safe
properties. Alternatively, you can create a DataTableReader object on a typed or
untyped DataSet table, and then access columns by index or column name.
To find a specific row in a typed DataSet table, you invoke the FindByXxx method
on the table. The precise name of the method is generated by Visual Studio
according to the name of the primary key column in the DataSet table.
To select all of the rows in a typed or untyped DataSet table that match a specified
filter expression, you invoke the Select method on the table. The method returns
an array of untyped DataRow objects that match the specified filter expression.
3-10 Visual Studio® 2008: ADO.NET
This lesson shows how to modify data in a DataSet, validate the modifications, and
then save the modified data back to the database. The lesson also describes how to
resolve optimistic concurrency conflicts, which can occur if two or more users or
processes attempt to make conflicting changes to data in the database.
Querying and Maintaining Data by Using DataSets 3-11
Key Points
To add a row to a typed DataSet table, you invoke the AddXxxRow method on the
table. Another way to add a row to a typed or untyped DataSet table is to invoke
the Add or InsertAt method on the DataTable Rows property.
To permanently remove a row from a typed DataSet table, you invoke the
RemoveXxxRow method on the table. Another way to permanently remove a row
from a typed or untyped DataSet table is to invoke the Remove or RemoveAt
method on the DataTable Rows property.
To mark a row to be deleted from a typed or untyped DataSet table, you invoke the
Delete method on a DataRow object.
You can access the original value of data in a DataRow by specifying the
DataRowVersion.Original enumeration value when you access a column.
3-12 Visual Studio® 2008: ADO.NET
Key Points
If you attempt to save a DataSet that contains erroneous rows, a run time exception
occurs. To avoid the exception, you should first determine whether the DataSet
contains any erroneous data, and then reject the erroneous rows before you save
the DataSet
Querying and Maintaining Data by Using DataSets 3-13
Key Points
When you create a typed DataSet class, the associated TableAdapter classes
provide Update methods to save each table in the DataSet to the database.
If you are using an untyped DataSet, you can fill the DataSet by using a
DataAdapter class such as SqlDataAdapter. You must set the InsertCommand,
UpdateCommand, and DeleteCommand properties on the DataAdapter object, to
specify the SQL statement that you want to insert, update, or delete a row in the
database. You can then invoke the Update method on the DataAdapter object, to
execute the appropriate SQL statements to save the table modifications to the
database.
3-14 Visual Studio® 2008: ADO.NET
Key Points
Optimistic concurrency conflicts occur when you save a DataSet to the database,
but the rows in the database have already been modified. ADO.NET DataSets
enable you to detect optimistic concurrency conflicts and to handle them in one of
the following ways:
• Force the current row to be saved and to overwrite the existing data in the
database.
• Skip the current row and continue saving subsequent rows.
• Skip all of the subsequent rows.
Question: When might you use each optimistic concurrency strategy in your own
applications?
Querying and Maintaining Data by Using DataSets 3-15
Key Points
You can serialize the data in a DataSet object to an XML document. This is useful if
you want to preserve the data between application invocations. The next time the
application starts, you can repopulate the DataSet object from the XML document.
The ability to serialize a DataSet as XML is also useful in distributed applications, if
you want to transmit a DataSet over a network to a remote client.
To serialize a DataSet object as XML data, you invoke the WriteXml method on
the DataSet object. To fill a DataSet object by using XML data, you invoke the
ReadXml method on the DataSet object.
3-18 Visual Studio® 2008: ADO.NET
Key Points
When you serialize and deserialize XML data for a DataSet object, you specify the
DiffGram format to preserve information about the data modifications in the
DataSet.
Querying and Maintaining Data by Using DataSets 3-19
Data
Table Description
Doctors Contains information about all of the doctors who are employed by
the Contoso Medical Clinic.
3-20 Visual Studio® 2008: ADO.NET
Table Description
You will also define relations and constraints between the Doctors and
Appointments tables, and between the Patients and Appointments tables.
You will use the typed DataSet in a Windows Forms application named
AppointmentViewer, which enables a doctor to view appointments and to modify
notes for an appointment.
Note: The database server name for this lab is .\SQLEXPRESS and the database name is
ContosoMedicalDB.
select
DoctorID,
FullName=FirstName + ' ' + LastName
from
Doctors
Verify that the DataSet designer displays a table named Doctors and an
associated table adapter named DoctorsTableAdapter.
2. Add a table named Patients to the ContosoMedicalDataSet.xsd DataSet, that
contains the ID, full name, gender, and date of birth of the patient. Specify the
following SQL statement to query the patient details, but do not generate
commands to insert, update, or delete patients.
select
PatientID,
FullName=FirstName + ' ' + LastName,
Gender,
DateOfBirth
from
Patients
Verify that the DataSet designer now displays a table named Patients and an
associated table adapter named PatientsTableAdapter.
3. Add a table named Appointments to the ContosoMedicalDataSet.xsd
DataSet, that contains all of the appointment details.
3-22 Visual Studio® 2008: ADO.NET
Note: In Visual Basic, the source code specifies the namespace name as
ContosoMedicalDataSetTableAdapters. This namespace is implicitly nested in the root
namespace for the project, AppointmentViewer.
Results: After this exercise, you should have created a typed DataSet that contains
tables named Doctors, Patients, and Appointments. You should also have defined
relations and constraints between the Doctors and Appointments tables, and
between the Patients and Appointments tables.
Tip: To add a row to the grid view, invoke the doctorsGridView.Rows.Add method.
Pass two parameters into the method, to display the DoctorID and FullName properties
for the doctor.
Appointments table, add code to select rows from the DataSet Appointments
table by using the filter filter expression.
4. Where indicated by the comment TODO: Display each appointment in
appointmentsGridView, add code to display each appointment as follows:
a. Iterate through the appointment rows that you obtained in step 3.
b. Get the AppointmentID, PatientID, and AppointmentDateTime columns
for the appointment row.
c. Get the row in the Patients table that corresponds to the appointment.
d. Add an item to the appointmentsGridView control, to display the
appointment ID, patient ID, appointment time (as a short time), patient
name, patient gender, and patient date of birth (as a short date.)
Note: The appointment ID and patient ID columns are not visible in the
appointmentsGridView control. These columns are included to identify the
appointment and patient for other code in the application, which you will write shortly.
Results: After this exercise, you should have created a DataSet instance, populated it
from a database or from a local XML file, and displayed the data in a form.
4. Type new notes into the text box, and then click OK to return to the
Appointment Viewer window.
5. In the Appointment Viewer window, in the lower DataGridView control,
double-click the first appointment again.
Verify that the Appointment Notes window displays the notes that you
entered in the previous step.
6. Close the Appointment Notes window and the Appointment Viewer window,
and return to Visual Studio.
Results: After this exercise, you should have modified the appointment notes in the
Appointments table in the DataSet.
Save Locally Save the entire DataSet to a local XML file as a DiffGram,
which retains information about the modifications made
by the user.
Discard Changes Discard all of the modifications made to the DataSet since
it was downloaded from the database.
4. Type new notes into the text box, and then click OK to return to the
Appointment Viewer window.
5. Close the Appointment Viewer window. In the Save Changes? dialog box,
click Save Locally.
6. In Visual Studio, in Solution Explorer, expand the AppointmentViewer
project, expand the bin folder, and then expand the Debug folder. Verify that
the Debug folder contains a file named ContosoMedicalDataSet.xml, which
contains the DataSet data that you just saved.
7. In Visual Studio, run the application again.
8. Select the following details in the Appointment Viewer window:
• Doctor: Ian Jenkins
• Date: Monday, June 02, 2008
9. In the lower DataGridView control, double-click the first appointment. Verify
that the Appointment Notes window displays the notes that you provided
earlier. This confirms that the application has saved and restored the DataSet
data to the local XML file successfully.
10. Close the Appointment Notes window and then close the Appointment
Viewer window. In the Save Changes? dialog box, click Save to Database.
Results: After this exercise, you should have saved a DataSet to a local XML file or to
the database. You should also have detected and resolved optimistic concurrency
errors that might occur when a DataSet is saved to the database.
3-34 Visual Studio® 2008: ADO.NET
Review Questions
1. What are the benefits of using typed DataSets rather than untyped DataSets?
A typed DataSet class contains properties that provide type-safe access to the
tables in the DataSet. Each table is represented by a separated class that
provides type-safe access to the columns in the table. Each table also has an
associated TableAdapter class that contains pre-configured Fill and Update
methods to populate and save the DataSet table.
2. How do you load data into a typed DataSet table from a database, and save the
data back to the database later?
To load data into a typed DataSet table from a database, you create an instance
of the appropriate TableAdater class and invoke the Fill method. To save the
data back to the database, you invoke the Update method on the TableAdapter
instance.
3. List four ways to access rows in a typed DataSet table.
Querying and Maintaining Data by Using DataSets 3-35
Create a DataTableReader object and use it to get each row in the table.
Get a particular row by its primary key value, by invoking the
FindBy<PrimaryKey> method.
Get all of the rows that match a particular filter expression, by invoking the
Select method.
4. What is the difference between deleting a row and removing a row in a DataSet
table?
When you delete a row, you mark the row for deletion the next time the
DataSet is saved to the database; the row is not physically removed until that
time. When you remove a row, the row is physically removed immediately.
5. What is a DiffGram?
A DiffGram is an XML format that you can specify when you serialize a DataSet
instance to XML, or when you populate a DataSet instance from XML. The
DiffGram format preserves information about which rows have been added,
modified, or deleted in the DataSet.
Module 4
Querying and Maintaining Data by Using LINQ
Contents:
Lesson 1: Querying In-Memory Data by Using LINQ Query Expressions 4-3
Lesson 2: Retrieving Data by Using LINQ to SQL 4-9
Lesson 3: Modifying Data by Using LINQ to SQL 4-16
Lab: Querying and Maintaining Data by Using LINQ to SQL 4-20
4-2 Visual Studio® 2008: ADO.NET
Module Overview
This lesson describes how to define LINQ queries to access in-memory data in a
collection of objects or in a DataSet object. The lesson introduces the basic syntax
of LINQ queries, and summarizes the new language features in Microsoft Visual
Basic® development system and Microsoft Visual C#® development tool that can
be used to support and simplify LINQ queries.
4-4 Visual Studio® 2008: ADO.NET
Key Points
LINQ enables you to access data consistently, regardless of the origins of the data.
Instead of having to use specific and disparate programming models to access data
from different data sources, you can define LINQ queries that treat the data
consistently.
The .NET Framework enables you to define LINQ queries to access data in a
collection of objects, a DataSet object, a Microsoft SQL Server® database, an entity
in an Entity Data Model, or an XML document.
Additional Information: For more information about Entity Data Models, see
Module 5, " Implementing an Entity Data Model by Using the ADO.NET Entity
Framework," of this course.
Querying and Maintaining Data by Using LINQ 4-5
Key Points
LINQ introduces a set of keywords in Visual Basic and Visual C# that enable you
to define queries on an enumerable data collection, such as a collection of objects.
A LINQ query specifies the following information:
• The enumerable collection that you want to query.
• A filter expression that specifies the items that you are interested in.
• Conditions that specify whether the results should be ordered or grouped.
• The type of object that you want to obtain from the query.
4-6 Visual Studio® 2008: ADO.NET
Key Points
You can use a For Each loop (Visual Basic) or a foreach loop (Visual C#) to iterate
over the enumerable result set returned by a LINQ query.
LINQ uses a deferred execution model, so the execution of the LINQ query is
deferred until the application iterates over the result set. This means that
exceptions might occur during iteration, not in the query itself.
Querying and Maintaining Data by Using LINQ 4-7
Key Points
LINQ to DataSet enables you to execute LINQ queries against a DataTable in a
DataSet object. You can obtain the results as a collection of DataRow objects, or as
a collection of objects of an anonymous type.
Question: If you do not use LINQ, how do you access the data in a DataSet
object?
4-8 Visual Studio® 2008: ADO.NET
LINQ to SQL enables you to access and modify data in a SQL Server database by
using LINQ queries. To use LINQ to SQL, you define entity classes that map to
tables in the database. You can then perform data operations by using the entity
classes and object-oriented programming techniques, instead of using ADO.NET
data access classes such as SqlConnection, SqlCommand and SqlDataReader.
4-10 Visual Studio® 2008: ADO.NET
Key Points
You define an entity class by following these steps:
1. Define a class and map it to a database table by using the Table attribute.
2. Define properties and map them to database columns by using Column
attributes.
Question: Why might the name of the entity class and its properties differ from
the name of the database table and its columns?
Querying and Maintaining Data by Using LINQ 4-11
Key Points
To retrieve data by using an entity class, you create a DataContext object and
invoke the GetTable generic method. The GetTable method returns a generic
Table object containing entity objects from the database.
The DataContext class and the Table generic class are defined in the
System.Data.Linq namespace, and are located in the System.Data.Linq assembly.
4-12 Visual Studio® 2008: ADO.NET
Key Points
LINQ to SQL enables you to define associations between entity classes, to
represent the relationships between tables in the database. You can then define
LINQ queries that perform joins between associated entity classes.
Question: What many-to-one relationships might you want to model as entity class
associations in your own applications?
Querying and Maintaining Data by Using LINQ 4-13
Key Points
When you define associations between entity classes, you can define and execute
LINQ to SQL queries to navigate the association in either direction, as follows:
• From a parent entity to its collection of child entities.
• From a child entity to its parent entity.
4-14 Visual Studio® 2008: ADO.NET
Relational Designer
4-16 Visual Studio® 2008: ADO.NET
LINQ to SQL enables you to insert, update, and delete objects in a table in a
DataContext object. The changes are held in memory until you invoke the
SubmitChanges method on the DataContext object, to submit the changes to the
database.
When you save changes to the database, optimistic concurrency errors can occur if
other users have made conflicting changes to the data in the database. The LINQ to
SQL API enables you to catch these errors and either reject the changes or force
them through to the database.
Querying and Maintaining Data by Using LINQ 4-17
Key Points
LINQ to SQL enables you to insert, update, and delete entity objects in a
DataContext table. The modifications are not saved to the database until you
invoke the SubmitChanges method on the DataContext object, as described in
the following topic.
4-18 Visual Studio® 2008: ADO.NET
Key Points
When you insert, update, or delete entities in a DataContext table object, the
changes are made to the in-memory objects. To submit the changes to the
database, you must invoke the SubmitChanges method on the DataContext
object.
Querying and Maintaining Data by Using LINQ 4-19
Key Points
When you submit entity changes to the database, concurrency conflicts occur if
other users have made conflicting changes to the data in the database. LINQ to
SQL enables you to specify which entity columns to test for concurrency conflicts,
whether to fail as soon as a concurrency conflict is detected or attempt to complete
all updates, and how to resolve each conflict that is detected.
Questions: Why might you specify that an entity member should not be tested for
optimistic concurrency conflicts?
Which strategy do you think you would use to resolve concurrency conflicts in
your own applications?
4-20 Visual Studio® 2008: ADO.NET
LINQ to SQL
You will define an association between the Patient and Prescription entity classes
to represent the one-to-many relationship between patients and prescriptions.
The main tasks for this exercise are as follows:
1. Open the PrescriptionManager application.
2. Generate LINQ to SQL entity classes.
3. Define an association between entity classes.
4. View the generated classes.
the Patients table from Server Explorer to the Object Relational Designer
surface.
Verify that the Object Relational Designer displays a box named Patient. This
is the entity class that corresponds to the Patients database table.
4. Delete the Photo property in the Patient entity class, because the application
does not need to access or view this information.
5. Generate an entity class to represent the Prescriptions database table, by
dragging the Prescriptions table from Server Explorer to the Object Relational
Designer surface.
Verify that the Object Relational Designer displays a box named Prescription.
This is the entity class that corresponds to the Prescriptions database table.
Member Description
Patients Gets a table of Patient entity objects
Member Description
Prescriptions Property that gets or sets the prescriptions for the patient.
This property is annotated with an Association attribute
that describes the one-to-many association between the
Patient and Prescription entity classes.
4. Locate the Prescription class. This is an entity class that maps to the
Prescriptions table in the ContosoMedicalDB database. The following table
describes some of the members in the Prescription class.
Member Description
_Patient Instance variable that contains an EntityRef that refers to
the Patient entity for a prescription
Patient Property that gets or sets the patient for the prescription.
This property is annotated with an Association attribute
that describes the one-to-many association between the
4-24 Visual Studio® 2008: ADO.NET
Member Description
Patient and Prescription entity classes.
Results: After this exercise, you should have generated entity classes for the Patients
and Prescriptions tables in the ContosoMedicalDB database, and defined a one-to-
many association between the entity classes.
1. In the MainForm source file, in the View by Date tab - display data code
region, locate the go_Click method.
The application invokes this method when the user clicks the Go button on
the View by Date tab in the form, to get and display prescriptions in a
particular period. Review the code that is already provided in the method.
2. Where indicated by the TODO comment, add the code provided in the
Ex2_Task4.txt file that is located in the following folder:
• E:\Labfiles\Starter\VB (Visual Basic)
• E:\Labfiles\Starter\CS (Visual C#)
The code performs the following tasks:
a. Defines a LINQ query that gets the prescriptions in the specified date
range, ordered by issue date.
b. Iterates over the query results, and displays each prescription in the
prescriptionsInPeriodGridView control. The code gets the name of the
patient for each prescription by using the Patient.FirstName and
Patient.LastName properties on the prescription entity.
3. Build and run the application.
4. In the Prescription Manager window, click the View by Date tab.
5. View the prescriptions between January 1, 2008 and March 31, 2008. Verify
that the application displays the prescriptions in the specified date range.
6. View the prescriptions between April 1, 2008 and June 30, 2008. Verify that
the application displays the prescriptions in the specified date range.
7. Close the Prescription Manager window.
Results: After this exercise, you should have defined and executed LINQ to SQL
queries to get information about patients and prescriptions from the
ContosoMedicalDB database.
database.
The main tasks for this exercise are as follows:
1. Get a specific Prescription entity.
2. Update a Prescription entity.
3. Delete a Prescription entity.
4. Insert a Prescription entity.
5. Save changes to the database.
6. Test the application.
user. Review the code that has already been provided in the method.
2. Where indicated by the first TODO comment, add code to invoke the
GetPrescriptionEntity method to get the Prescription entity for the
prescriptionID.
3. Where indicated by the second TODO comment, add code to increment the
RepeatCount property on the Prescription entity.
Note: At the end of the repeatPrescriptions_Click method, the application invokes the
DoSave method. You will implement this method later in this exercise, to submit the
changes to the database.
comment, add the code provided in the Ex3_Task5.txt file located in the
following folder:
• E:\Labfiles\Starter\VB (Visual Basic)
• E:\Labfiles\Starter\CS (Visual C#)
The code performs the following tasks:
a. Catches ChangeConflictException exceptions, which indicate that a
concurrency conflict has occurred.
b. Iterates over the collection of change conflicts, and displays information
about the object that caused a concurrency conflict; the members in
conflict; and the current, original, and database values of each such
member.
c. Invokes the Resolve method to refresh the current values in memory with
the latest values from the database.
occurred. The message box should indicate the current, original, and
database values of the RepeatCount property, and then update the value
in the application with the value from the database.
• For the prescriptions that you did not modify in the other instance of the
application, the current instance of the application should update the
prescriptions successfully.
16. Close the Prescription Manager window.
17. Close Visual Studio.
Results: After this exercise, you should have implemented functionality to enable the
user to insert, update, and delete entities by using LINQ to SQL, and to detect and
resolve optimistic concurrency conflicts.
4-34 Visual Studio® 2008: ADO.NET
Review Questions
1. What are the benefits of using LINQ to SQL rather than using ADO.NET
classes such as SqlConnection and SqlCommand?
Using LINQ to SQL can be more productive for developers than using
ADO.NET classes. Developers can define simple queries and delegate the
complexities of database interactions to the LINQ to SQL provider.
2. What attributes do you use to designate a class as an entity class, and to
specify that a member maps to a database column?
To specify that a class is an entity class, annotate the class with the Table
attribute. To specify that a member maps to a database column, annotate the
member with the Column attribute?
3. How do you define an association between two entity classes?
In the parent class, define an EntitySet instance variable and a property to get
and set it. In the child class, optionally define an EntityRef instance variable
Querying and Maintaining Data by Using LINQ 4-35
Supplement or modify the following best practices for your own work situations:
• Retain entity changes in memory for as short a time as possible. Submit the
changes to the database as soon as possible, to minimize the risk of
concurrence conflicts with other users.
• Enclose updates in a transaction if appropriate, for example, to ensure all data
is updated or no data updates.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-1
Module 5
Implementing an Entity Data Model by Using
the ADO.NET Entity Framework
Contents:
Lesson 1: Creating an Entity Data Model by Using the ADO.NET Entity
Framework 5-3
Lesson 2: Querying and Modifying Data by Using the ADO.NET Entity
Framework 5-9
Lab: Implementing an Entity Data Model by Using the ADO.NET Entity
Framework 5-17
5-2 Implementing an Entity Data Model by Using the ADO.NET Entity Framework
Module Overview
The ADO.NET Entity Framework enables you to create data access applications by
programming against a conceptual application model instead of programming
directly against a relational storage schema. The goal of the ADO.NET Entity
Framework is to decrease the amount of code and maintenance that is required for
data-oriented applications.
This module describes how to create an Entity Data Model by using the ADO.NET
Entity Framework, and how to query and modify data by using the Entity
Framework.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-3
This lesson describes how to how to create an Entity Data Model (EDM) by using
tools provided by the ADO.NET Entity Framework.
An EDM contains a conceptual model that defines entity types that you use in your
application, and a storage model that describes how the data is stored in the
database. The EDM also contains a mapping specification that connects the entity
types in the conceptual model to the database metadata in the storage model.
5-4 Implementing an Entity Data Model by Using the ADO.NET Entity Framework
Key Points
The ADO.NET Entity Framework is a set of technologies that supports
development of data-oriented software applications. The Entity Framework enables
developers to work with data in the form of domain-specific objects and properties,
such as customers and customer addresses, without having to consider the
underlying database tables and columns where this data is stored.
The ADO.NET Entity Framework reduces the amount of data access code in object-
oriented data applications and services, and makes it faster to create object-
oriented data applications and services from an existing database.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-5
Key Points
An .edmx Entity Data Model file defines the following information:
• Conceptual model
• Storage model
• Mapping specification
5-6 Implementing an Entity Data Model by Using the ADO.NET Entity Framework
Key Points
The Entity Framework provides the tools that enable you to create and modify an
EDM. The EMD can be created for a console, a Windows application or an
ASP.NET applications.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-7
Key Points
Object Services is a component of the Entity Framework that enables you to query,
insert, update, and delete data, expressed as strongly-typed objects that are
instances of entity types. Object Services supports both Entity SQL and LINQ to
Entities queries against types that are defined in an EDM.
Object Services represents data from the data store as objects, and propagates
object changes back to the persisted data store. Object Services also provides
facilities for tracking changes, binding objects to controls, and handling
concurrency.
Object Services is implemented by classes in the System.Data.Objects and
System.Data.Objects.DataClasses namespaces.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-11
Key Points
The Entity Framework provides a generic class named ObjectQuery that enables
you to execute queries against an EDM and return data as objects.
The ObjectQuery class provides a set of query builder methods, such as Where
and Include, that enable you to filter and shape the query results.
5-12 Implementing an Entity Data Model by Using the ADO.NET Entity Framework
Key Points
LINQ to Entities enables you to define LINQ queries on the entities that are
returned by an object query. In a typical scenario, an application defines an object
query to retrieve data from the persistent data store into a collection of entities in
memory, and then uses LINQ to Entities to query the entities without requiring
additional roundtrips to the database.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-13
Key Points
Entity SQL is an SQL-like language that is provided by the Entity Framework and
enables you to query and manipulate rich graphs of objects that are based on the
EDM.
5-14 Implementing an Entity Data Model by Using the ADO.NET Entity Framework
Key Points
The ObjectContext class provides methods that enable you to insert and delete
entities in the cache of entities held in memory by the object context object. You
can also locate existing entities and modify their property values in memory.
To save entity changes to the persistent data store, you must invoke the
SaveChanges method on the ObjectContext object and handle any concurrency
errors that might occur.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-15
Note: When you map an association, you must select the table that contains the foreign
keys for the association in the database. In this example, the Prescriptions database
table contains foreign keys to the Patients database table, to identify the patient for
each prescription.
Results: After this exercise, you should have generated an EDM that represents the
Patients and Prescriptions tables in the ContosoMedicalDB database, and defined a
one-to-many association between the entities in the EDM.
query to get Patient entities for all of the patients in the database, and then
bind the entities to a DataGridView control.
• When the user clicks a patient in the DataGridView control, you will define an
object query to get the prescriptions for that patient. You will display the
prescriptions in another DataGridView control.
Note: For simplicity, the application does not enable the user to insert or delete
prescriptions.
3. At the top of the source file, where indicated by the second TODO comment,
import the System.Data.Objects namespace.
4. In the MainForm class, expand the Display data code region, and then locate
the DisplayPatients method.
The application invokes this method during startup, to display the patients in
the patientsGridView control.
5. Where indicated by the TODO comment, add the code provided in the
Ex2_Task2.txt file located in the following folder:
• If you are using Visual Basic: E:\Labfiles\Starter\VB
• If you are using Visual C#: E:\Labfiles\Starter\CS
The code creates a ContosoMedicalDBEntities object, and contains TODO
comments that you will implement in the following steps.
6. Where indicated by the TODO: Define an object query comment, define an
ObjectQuery object to get all Patient entities from the database.
7. Where indicated by the TODO: Bind the retrieved entities comment, bind the
entities that are returned by the query to the patientsGridView control.
8. Build and run the application.
9. Verify that the Prescription Manager window appears, and that the upper
DataGridView control displays 18 patients.
10. Close the Prescription Manager window.
Results: After this exercise, you should have defined and executed object queries to
get information about patients and prescriptions from the ContosoMedicalDB
database.
Results: After this exercise, you should have modified entities and saved the changes
back to the database.
Implementing an Entity Data Model by Using the ADO.NET Entity Framework 5-25
Review Questions
1. What information does an .edmx Entity Data Model file contain?
The .edmx file defines the conceptual model, the logical model, and the
mapping specification for the EDM.
2. How do you define an association between entities, and what information does
the code generator add to the entity classes?
In the EDM designer window, you right-click an entity, point to Add, and then
click Association. You must verify the multiplicity at both ends of the
association. When you define an association, the code generator adds a
navigation property to each entity, to enable you to navigate the association
programmatically.
3. What is an object context?
An object context encapsulates the underlying connection to the database, so
that you can execute object queries.
5-26 Implementing an Entity Data Model by Using the ADO.NET Entity Framework
object query?
LINQ to Entities is useful when you have already executed an object query to
retrieve a collection of entities, and you want to obtain selective entities or
properties from the result set in memory without performing another database
roundtrip.
Module 6
Building Occasionally Connected Solutions by
Using Synchronization Services
Contents:
Lesson 1: Understanding Microsoft Synchronization Services 6-3
Lesson 2: Downloading Data by Using Synchronization Services 6-7
Lesson 3: Uploading Data by Using Synchronization Services 6-12
Lab: Building Occasionally Connected Solutions by Using Synchronization
Services 6-17
Course Evaluation 6-33
6-2 Visual Studio® 2008: ADO.NET
Module Overview
Key Points
Synchronization is the process where the data in one data source is used to update
the data in another data source. Microsoft Synchronization Services provides
ADO.NET classes to enable you to synchronize between data sources. The server
side can be a data source for which there is an ADO.NET 2.0 data provider and the
client side can be Microsoft SQL Server® or Microsoft SQL Server® Compact
Edition 3.5 and later. Synchronization Services can handle multiple clients
uploading and downloading data from a server simultaneously. The services
ensure that only data that has changed since the last synchronization is exchanged,
and indicates conflicts.
Question: How does the client find out that there have been changes in the server?
Building Occasionally Connected Solutions by Using Synchronization Services 6-5
Services
Key Points
Synchronization Services supports four synchronization modes. You chose the
mode that best suits your application.
Question: What are the principal differences between snapshot and download-
only?
6-6 Visual Studio® 2008: ADO.NET
Synchronization Services
Key Points
Synchronization Services supports two tier, n-tier, and service-based architecture.
Key Points
You must alter the server database so that Synchronization Services can track
changes. You do not make any changes to the client database.
Key Points
Synchronization Services provides classes to co-ordinate synchronization and to
access data sources on the client and on the server.
Key Points
Synchronization applies the changes made on one database over a period of time
to another database. At synchronization time, Synchronization Services generates
anchor values and uses these values to determine which rows have changed.
Question: Where do the values for anchor session variables come from?
Building Occasionally Connected Solutions by Using Synchronization Services 6-11
Synchronization Services
6-12 Visual Studio® 2008: ADO.NET
This lesson describes how your applications can upload data to the server. This
lesson also explains how your applications are informed about synchronization
conflicts and how you can handle these conflicts.
Building Occasionally Connected Solutions by Using Synchronization Services 6-13
Key Points
When you use upload-only or bidirectional synchronization there is a possibility
that more than one client could attempt to change the same row.
Question: Why can you not use transactions to solve the type of concurrency issue
that occurs with synchronization?
6-14 Visual Studio® 2008: ADO.NET
Key Points
The synchronization provider indicates conflicts by raising the
ApplyChangeFailed event. You can resolve conflicts by changing the properties of
the event argument.
Question: How can you reduce the possibility of conflicts during synchronization?
Building Occasionally Connected Solutions by Using Synchronization Services 6-15
Key Points
You can monitor the progress of the synchronization through events that are raised
on the synchronization providers and the synchronization agent.
Question: What is the significance of the fact that the events that are used to
monitor progress are raised on the thread that called Synchronize?
6-16 Visual Studio® 2008: ADO.NET
Services
Building Occasionally Connected Solutions by Using Synchronization Services 6-17
Class Description
clientClientSyncProvider This is the local synchronization provider
and holds the code to connect to the
local cache.
Item Description
LastEditDate A datetime column used to track when a row
was last updated. This is a new column.
Trigger Description
Appointments_DeletionTrigger Adds an entry in the tombstone table for the
deleted row, together with the appointment
identifier and the current time. If the row has
Building Occasionally Connected Solutions by Using Synchronization Services 6-21
Trigger Description
been deleted before then the tombstone entry is
updated to show the current time.
Item Description
AppointmentID This is the primary key of the row that was
deleted.
DeletionDate This is the time and date when the row was
deleted.
Results: After this exercise, you should have altered the database to enable
synchronization and generated supporting classes to initiate synchronization.
Control Description
doctorID Use this text box to provide the identifier for the doctor.
saveCache Click this button to save data in the grid to the local cache. (Will
be used in a later exercise.)
Command Description
InsertCommand This is called to insert a row in the server
database. The command first sets the
IDENTITY_INSERT T-SQL option so that a
value can be provided for the identity row.
The command then inserts a row into the
table. All of the column values are provided
through parameters. The command
provides values for the date tracking
columns, which is redundant because the
insertion trigger will perform this action.
Finally, the @sync_row_count session
variable is initialized by the value of the
number of rows inserted.
Command Description
client has indicated that the client changes
must be made regardless of any conflicts
with the server data. The AppointmentID
value, which identifies the appointment
row to be deleted, is provided through a
parameter. The @sync_row_count session
variable is initialized by the value of the
number of rows inserted.
the local cache and the dataset that was generated for you.
a. Remove the ContosoMedicalDB.sdf file from the project.
b. Remove the ContosoMedicalDB.sdf file from the output build folder.
c. Remove the clientDataSet.xsd file from the project.
In the following steps you will generate new versions of these files.
4. Provide an implementation of OnInitialized in the
AppointmentsSyncAdapter class to provide the commands to invoke the
uspGetAppointmentsForDoctor stored procedure. The code for this method
is in the Ex2_Task2_OnInitialized.txt file.
table adapter. Add the following line of code after the call to
agent.Synchronize.
[Visual Basic]
Me.appointmentsTableAdapter.Fill(Me.clientDataSet.Appointments)
[Visual C#]
this.appointmentsTableAdapter.Fill(this.clientDataSet.Appointments);
Control Description
appointmentsGrid This data grid shows values from the Appointments table. If
you add a new row, you must provide values for DoctorID,
PatientID and AppointmentDateTime.
Note: Visual Studio only starts the process for the project that is marked as the
startup project. To start processes created by other projects, you must start the
process directly from the build output folder.
Column Value
DoctorID 1
PatientID 5
Column Value
DoctorID 2
PatientID 10
5. Verify that the Mobile Calendar application reads its data from the local cache
rather than the server database. Close the application, then restart and verify
that there are no new rows.
6. On the Mobile Calendar form click Synchronize. Verify that the Mobile
Calendar now has the row you entered on Desktop Calendar.
Building Occasionally Connected Solutions by Using Synchronization Services 6-27
you just inserted for doctor 1. Click the Save button. In the Mobile Calendar
click Synchronize, and confirm that the change has been copied to the cached
database.
8. In the Desktop Calendar, delete the new row. Click the Save button to save
the results to the database. In the Mobile Calendar, click Synchronize, and
confirm that the previous row has been deleted.
9. Close Mobile Calendar but keep Desktop Calendar running for the other
exercises.
Results: After this exercise, you should have implemented an application that
performs download-only synchronization with a SQL Server database. You should have
shown that synchronization works for inserted, updated, and deleted rows.
[Visual Basic]
Me.Validate()
Me.appointmentsBindingSource.EndEdit()
Me.appointmentsTableAdapter.Update(Me.clientDataSet.Appointments)
[Visual C#]
this.Validate();
this.appointmentsBindingSource.EndEdit();
this.appointmentsTableAdapter.Update(this.clientDataSet.Appointments);
Control Description
The following conflict has This text box displays the conflict that has
occurred occurred. It gives the type of conflict and the
conflicting client and server rows.
How do you want to handle this? This radio button group enbles you to
determine if you will allow the default action to
occur, or if you want to force another action.
2. View the code for this form. There are two properties:
a. The Action property returns an ApplyAction value based on the radio
button selected.
b. The ConflictType property displays information about the conflict in the
text box on the form.
Building Occasionally Connected Solutions by Using Synchronization Services 6-29
Save.
b. In Mobile Calendar, change the Notes field for this row. Click Save to
Cache.
c. Synchronize.
Confirm that a conflict is detected: Mobile Calendar updated a row that
Desktop Calendar deleted.
d. In the Handle Conflict dialog box, select Force this write.
e. Confirm that the row remains in the local cache.
f. In Desktop Calendar, click Refresh, and confirm that the row has been
re-inserted into the server database.
5. Close Desktop Calendar and close Mobile Calendar.
Results: After this exercise, you should have implemented the application so that it
handles synchronization conflicts and you can specify whether changes in the client
override changes in the server.
Building Occasionally Connected Solutions by Using Synchronization Services 6-31
Review Questions
1. Why is it important that values for time tracking anchor values are generated
by the server?
For synchronization to work, it is vital that the time source used by all of the
code that can change data is the same. If different time sources are used, even a
difference in a few milliseconds can prevent Synchronization Services from
working. A single time source prevents this problem.
2. What role do transactions play in Synchronization Services?
Transactions can only be used within individual commands, for example to
update the server. A transaction must not be used between the
Synchronization Services commands.
3. What role does the tombstone table play?
The tombstone table has sufficient information about the rows that have been
deleted for Synchronization Services to determine which rows have been
deleted since the last synchronization. This table is not an archive of deleted
6-32 Visual Studio® 2008: ADO.NET
that it is associated with, tracking information (like the time the row was
deleted), and the identifier of the user who deleted the row.
Your evaluation of this course will help Microsoft understand the quality of your
learning experience.
Please work with your training provider to access the course evaluation form.
Microsoft will keep your answers to this survey private and confidential and will
use your responses to improve your future learning experience. Your open and
honest feedback is valuable and appreciated.