20483C - Programming in C#
20483C - Programming in C#
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
10/28/2019 20483B - Programming in C# | Skillpipe
Copyright
Information in this document, including URL and other Internet Web site references,
T
his his T
is subject
do to change without notice. Unless otherwisedo noted, the example companies,
cu cu
ma m ma
en products, domain names, e-mail addresses,
en m
organizations,
rta tb rta t b logos, people, places, and
.ba elo .ba elo
No rbo ng No rbo ng
eventsundepicted sa
@
herein
s to are fictitious, and no associationun sawith any
@
st
o M real company,
au p M a au p art
tho rim rta tho rim aplace
organization, riz product,
ed
av
era domain B arb name, e-mail address, logo,
r ized person,
a vera Ba
rbo
or event is
co b s o s c o b s s
pie be inferred.
s.c a. pie copyright s.c a.
intended or should sa om Complying with all applicable sa om laws is the
llo llo
we we
responsibility of the user. d! Without limiting the rights under copyright, d! no part of this
Thank you for taking our training! We’ve worked together with our Microsoft Certified
Partners for Learning Solutions and our Microsoft IT Academies to bring you a world-
Th Th
is is
class learning
do
c
experience—whether you’re a professional
do
c
looking to advance your
um um
ma e
n ma en
skills orrtaa.b student t be
l
preparing for a career in IT. rta
. b
tb
elo
arbo on a rbo ng
No gs No st
un sa t o u na s a oM
au @ Ma u @
tho p rim rta tho p rim art
riz av B riz av aB
Microsoft Certified Trainers and Instructors
ed
co
pie
era
b s
a rbo
s a
ed
c o pie
era
b s
arb
os
a.
s.c . s.c
sa om sa om
llo llo
Your instructor is a technical we and instructional expert who meets wongoing ed certification
d! !
requirements. And, if instructors are delivering training at one of our Certified
Partners for Learning Solutions, they are also evaluated throughout the year by
students and by Microsoft.
Th Th
Certification
is
do
c
Exam Benefits is
d oc
um um
ma ent ma en
rta be rt
a.b tb
AfterN training,
. b consider
l o taking a Microsoft Certification exam. elo Microsoft Certifications
arb ng No a r bo ng
ou os st un s st
na a@ oM a @ oM
validate youruth
ori
skills
pri on Microsoft
ma
art
aB
technologies and can a uth helppdifferentiate
ori rim art
aB
you when
ze ve a z av a
d c boosting rab your rbo e d e rab byrbIDC
finding a job or op ss sacareer. In fact, independent cresearch op ss os concluded
a.
ies .co . ies .co
m m
ow performance 1. Ask
all all
that 75% of managers ow believe certifications are important to team
ed ed
! !
your instructor about Microsoft Certification exam promotions and discounts that may
be available to you.
Our Certified Partners for Learning Solutions offer a satisfaction guarantee and we
hold them accountable for it. At the end of class, please complete an evaluation of
today’s experience. We value your feedback!
We wish you a great learning experience and ongoing success in your career!
Th Th
is is
Sincerely,do d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
u s to un oM
Microsoft
na Learning
uth
a @
pri Ma au
tho
a @
p art
ori ma rta rim aB
ze ve Ba riz av arb
dc rab rbo ed era
op s sa co bs os
ies s .co . pie s.c a.
sa om
www.microsoft.com/learning a llo
we
m llo
we
d! d!
John Sharp gained an honors degree in Computing from Imperial College, London.
He has been developing software and writing training courses, guides, and books for
over 25 years. John has experience in a wide range of technologies, from database
systems
Th and UNIX through to C, C++ and C# applications
Th for the .NET Framework,
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 3/10
10/28/2019 20483B - Programming in C# | Skillpipe
together with Java and JavaScript development. He has authored several books for
Microsoft Press, including six editions of C# Step By Step, Windows Communication
Foundation Step By Step, and the J# Core Reference.
Antony Norris is a Senior Technologist with Content Master where he has been
working with Microsoft products and technologies, especially Visual C# and ASP.NET
MVC, for several years. Antony is an experienced developer who has contributed to
many
Th successful solutions. Antony has also authored
i
Th
i
Microsoft Learning courses on
sd sd
oc oc
a variety
ma ofmtechnologies,
u
en
such as Windows Mobile,
ma Windows
um
en
Communication
rta t b r t a tb
.ba (WCF), elo .ba MCTS elo
Foundation
No rbo ng and Visual C#. Antony is currently No rbo ng certified.
un sa s t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
Carsten Thomsen – Technical Reviewer
co
pie
sa
b s s.c
om
s a .
c o pie
sa
b s s.c
om
os
a.
llo llo
we we
d! d
Carsten Thomsen is currently doing SharePoint 2010 development,! but his interests
are varied when it comes to IT and includes development of ASP.NET, Windows
Forms, Windows Store, Windows Phone and other types of applications and
components. He has authored a number of development books as well as over 20
Microsoft Learning courses.
Th Th
is is
do d oc
cum um
ma ent ma en
tb
Contents
No
rta
.ba
rbo
s
be
lon
gs No
rt a.b
arb
os
elo
ng
st
un a@ to un a @ oM
au pri Ma au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
Title Copyright sa c om sa om
llo llo
we we
d! d!
Welcome!
Acknowledgments
Course Materials
Th
is
Module Overview Th
is
do d oc
cum um
ma e ma en
Lessonrta 1
.ba
nCreating
t be Class Hierarchies a.b rt tb
elo
lon a ng
: No u rbo gs No rbo st
na s a t o u na s a oM
uth @ Ma u @
pri r t t h p r i art
ori m av aB ori m av aB
ze era a rbo Framework Classes zed era arb
Lesson 2: Extending dc
op b s .NET s a c o pie b s os
a.
ies s.c . s.c
all o m s all o m
ow ow
Lab: Refactoring ed Common Functionality into the User eClass
d!
!
Th Th
is
do
Module Review and Takeaways is
d
c oc
um um
ma ent ma en
rta tb rt
Module .9:
ba Designing
be
lon the User Interface for a Graphical
a.b
a
elo Application
n
No rbo gs No rbo gs
un sa to un sa
to
au @ Ma au @
Ma
tho Module pri
m Overview
rta pri
tho
m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
Lesson 1 Using s aXAML
llo
omto Design a User Interface sa
llo
om
we we
: d! d!
Lesson 3: Styling a UI
Th Th
Lesson
is 3:
d
Synchronizing Concurrent Access is to Data
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 7/10
10/28/2019 20483B - Programming in C# | Skillpipe
Course Evaluation
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 10/10
10/28/2019 20483B - Programming in C# | Skillpipe
The developers targeted by this training are professional developers who have 3-6
months of experience creating software applications for a production environment
and who have a basic understanding of Windows client application development.
Students
T should have a minimum of the following
T experience:
his his
do do
cum cu
ma e ma me
rta nt rt nt
be a be
• 3Nmonths
. barb of experience
l ong creating .NET Framework N
. b arapplications.
b
lon
gs
ou os s t o un o s to
na a@ oM a@ Ma
uth pri art a uth pri
ori ma aB ori ma rta
• 1 month of ze experience
dc
ve
rab using
a rbo Visual Studio 2010 or Visual
ze dc Studio
ve rab 2012.
Ba
rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
This course is not designed for students who are new to programming; it is targeted
at professional developers with at least one month of experience programming in an
object-oriented environment.
Th Th
is is
Studentum Prerequisites
do
c
d oc
um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 1/8
10/28/2019 20483B - Programming in C# | Skillpipe
Before attending this course, students must have at least three months professional
development experience.
Additionally, developers attending this course should already have gained some
limited experience using Visual C# to complete basic programming tasks. More
specifically, students should have hands-on experience using Visual C# that
Th Th
sd i i
demonstrates
oc
u
their understanding of the following:s docu
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
u s a to u a to
• Hownato uth name, @
pri declare,Ma
rta
initialize and assign values
na to variables
uth @
pri Mawithin an
rta
ori ma Ba ori ma Ba
ze ve ze ve
application. dc
op
rab rbo
sa
dc
op
rab rbo
sa
ies s s . ies s s .
.co .co
all m all m
ow ow
• How to use: ed ed
! !
• How to create a simple looping structure using a for statement to iterate through a
data
Th array. Th
is is
do oc d
cum um
ma n e ma en
• Howtato
r
.ba
usebthet
elo Visual Studio IDE to locate simple r ta. logic
b
t b errors.
elo
No r bo n gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri a method art a uth pri art
• How tothocreate
riz m av a Ba
that accepts arguments and o riz returns m av a value aB of a specified
ed era rbo e d e r arb
co bs co ab os
type. pie s.c sa
. pie ss
.co a.
sa om sa m
llo llo
we we
d! d!
• How to design and build a simple user interface by using standard controls from
the Visual Studio toolbox.
• How to connect to a SQL Server database and the basics of how to retrieve and
store data.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 2/8
10/28/2019 20483B - Programming in C# | Skillpipe
Course Objectives
Th Th
is is
do do
After completing
cu
me this course, students will be able to: cu
me
ma n m a nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r b gs
un sa st ou os to
@ o M n a @ Ma
• Describe au
tho thepcore rim syntax
art
a
and features of Visual aC#.
uth
o
pri
m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
• Create methods, s a handle
llo
om exceptions, and describe the monitoring sa
llo
orequirements
m of
we we
large-scale applications. d! d!
• Create
T
classes, define and implement interfaces,
T
and create and use generic
his his
do
collections. do
cu cu
ma m en ma me
rta tb rt nt
.ba elo be
a.b
ng lon
arb
• Use rbo
No inheritance s to N
to create a class hierarchy and
o u to extend a@ a t.NET Framework
os gs
un sa na oM
au @ Ma uth
p pri art
class. thorize rimave rta Ba ori
ze
ma
ve
aB
arb
dc rab rbo dc rab os
op ss sa op s s.c a.
ies .co . ies
all m all o m
• Read and write data o we by using file input/output and streams, and ow serialize and
ed
d! !
deserialize data in different formats.
• Create and use an entity data model for accessing a database and use LINQ to
query data.
• Access
Th
is and query remote data by using the types
Th
is in the System.Net namespace
do do
c
um Data Services. cu
and
ma WCFen ma me
nt
rta tb a rt be
.ba elo .ba lon
No rbo ng No rbo gs
s
un a graphical s t un s to
• Build a@ ouser
M interface by using XAML. a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
• Improve the throughput pie
sa .c om and . response time of applications i e by
sa using. com tasks
. and
llo llo
we we
asynchronous operations. d! d!
• Examine the metadata of types by using reflection, create and use custom
Th Th
is
attributes, is
generate code at runtime, and manage
do do assembly versions.
c um c um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 3/8
10/28/2019 20483B - Programming in C# | Skillpipe
Course Outline
The course outline is as follows:
Th Th
is is
do d oc
cum um
ma nt e ma en
Module
rta 1, “Review
.b be
l
of Visual C# Syntax" rt a.b elo
tb
arb on arb ng
No o gst No osst
un sa oM un a oM
au @ au @
tho pri art tho p rim art
riz ma aB riz av aB
Module 2, “Creating
ed
co
v eraMethods,
bs
arb
os
Handling Exceptions, andedMonitoring
co
era
bs
Applications"
arb
os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
Module 3, “Developing the Code for a Graphical Application"
Module
T 5, “Creating a Class Hierarchy by UsingT Inheritance"
his his
do do
cum cu
ma e ma me
rta nt rt nt
be a.b be
Module
No
.6,
ba “Reading
rbo
lon
gs
and Writing Local Data" No arb lon
gs
un sa t o un os to
au @ Ma au a@ Ma
tho pri rta tho pri rta
riz ma Ba riz m av Ba
ed ve rbo ed era rbo
Module 7, “Accessing co rab a Database" co b
pie s s.c sa pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
Module 8, “Accessing Remote Data"
Module
Th
is 10, “Improving Application Performancehiand
T
s Responsiveness"
do do
cum cu
ma e me
ma
rta nt rtnt
.ba belo a .ba be
ng lon
Module
No
un
11,rbo“Integrating
s s t
with Unmanaged Code"No
un
rbo
s
gs
to
a@ oM a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
Module 12, “Creating pie
sa Reusable
.c om
. Types and Assemblies" i e sa . com
.
llo llo
we we
d! d!
Course Materials
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 4/8
10/28/2019 20483B - Programming in C# | Skillpipe
Course Handbook: a succinct classroom learning guide that provides the critical
technical information in a crisp, tightly-focused format, which is essential for an
effective in-class learning experience.
Th Th
is is
do do
• Lessons: cu
me
guide you through the learning objectives cu and provide the key points
me
ma n m a nt
rta tb r t
that are.ba critical elo to the success of the in-class learning
ng
a.b
a experience.
be
lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
• Labs: provide riz maavreal-world,a Ba hands-on platform for you o riz to applym av the Baknowledge and
ed era rbo ed era rbo
co b s s a c o b s sa
skills learned in p s
ies the module. .co . p ies s.co .
all m all m
ow ow
ed ed
! !
• Module Reviews and Takeaways: provide on-the-job reference material to boost
knowledge and skills retention.
Th Th
is is
do oc d
cum um
ma e m en
Course
rta n t Companion
be Content: searchable, aeasy-to-browse
rta tb
elo
digital content with
.ba lon .ba
Nointegrated
rbo premium
gs online resources thatNsupplement rbo n
the
gs Course Handbook.
un sa to ou sa to
au @ M na @ Ma
tho pri art uth pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
s a companion . s a answers, .
• Modules: include llo
om content, such as questions and llo
om detailed
we we
d! d!
demo steps and additional reading links, for each lesson. Additionally, they include
Lab Review questions and answers and Module Reviews and Takeaways
sections, which contain the review questions and answers, best practices,
common issues and troubleshooting tips with answers, and real-world issues and
scenarios with answers.
Th Th
is is
do do
c
um cu
• Resources:
ma en include well-categorized additional ma resources me that give you immediate
rta tb r nt
.ba elo t a .ba be
ng l onMSDN®,
access
No
un
rto
bo the most
sa s t current premium contentNon
o u TechNet, rbo
sa
gs
to
or Microsoft®
@ o M n @ M
au pri art a uth pri art
Press®. tho ma aB ori ma aB
riz ve a z v arb
ed rab rb e d e r ab
co ss os co s os
pie .co a . p ies s.co a.
sa m a m
llo llo
we we
d! d!
Note: For this version of the Courseware on Prerelease Software,
Companion Content is not available. However, the Companion Content will
be published when the next (B) version of this course is released, and
students who have taken this course will be able to download the
Companion Content at that time from the
Th http://www.microsoft.com/learning/companionmoc
T site. Please check
is his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 5/8
10/28/2019 20483B - Programming in C# | Skillpipe
with your instructor when the ‘B’ version of this course is scheduled to
release to learn when you can access Companion Content for this course.
• Course evaluation: at the end of the course, you will have the opportunity to
complete
Th an online evaluation to provide feedback
Th on the course, training facility,
is is
oc d d oc
and
m
instructor.
um
e ma en
um
art nt rt tb
a.b be a.b elo
a l on a ng
No rbo gs No rbo st
• Toun provide
au
sa
@ additional
t o Ma
comments or feedback u on
na the s a course,
@ o M send an email to
tho p rim rta u tho p rim art
aB
support@mscourseware.com.
riz
ed
av
era B a rbo To inquire about rizthe Microsoft
ed
av
era aCertification
rbo
co b s s a c o b s sa
pie s.c . pie s.c .
Program, send s a an email om to mcphelp@microsoft.com. s a om
llo llo
we we
d! d!
This Tsection
his provides the information for settingTup
his the classroom environment to
do do
um c cu
support
ma the ebusiness scenario of the course. ma me
rta n tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho
Virtual Machine Configuration
riz
ed
ma
ve
rab
aB
a rbo
ori
ze dc
ma
ve rab
rta
Ba
rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
In this course, you will llo use Microsoft® Hyper-V™ to perform the
we
llo labs.
we
d! d!
Important: At the end of each lab, you must close the virtual machine and
must not save any changes. To close a virtual machine (VM) without saving
the changes, perform the following steps:
Th T
1.
is
do On the virtual machine, on the Actionhismenu,
do click Close.
cu cu
m me m me
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 6/8
10/28/2019 20483B - Programming in C# | Skillpipe
2. In the Close dialog box, in the What do you want the virtual machine
to do? list, click Turn off and delete changes, and then click OK.
The following table shows the role of each virtual machine that is used in this course:
Th Th
is is
do d oc
um c um
Virtual
ma machine
en Role ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un Internet os st
MSL-TMG1 @ oM Gateway computer for a @ access oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
20483B-SEA-DEV11 co bs os Development computer used for os
co buildingbsapplications. The
pie s.c a. pie s.c a.
sa om sa om
llo demonstration and lab files are located llo on the E:\ drive, in folders
we we
d! named Mod01, Mod02, and so on up to Mod13. d!
Software Configuration
The following software is installed on each VM:
Th Th
is is
do d oc
c
um um
• Microsoft
ma enWindows 8 Enterprise
tb
ma en
tb
rta elo rt a.b elo
.ba arb
No rbo ng No ng
un sa st un os st
oM a oM
• Microsoft
au
tho
Visual
@
prim
Studio art 2012 Ultimate au
tho
@
p rim art
riz av aB riz av aB
ed era arb ed era arb
co b s os co b s os
pie Professional
s.c a. pie s.c a.
• Microsoft Office sa om Plus 2010 sa om
llo llo
we we
d! d!
Course Files
The files associated with the labs in this course are located in the E:\Labfiles folder
on each
Th
i
virtual machine. Th
is
sd d
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
Classroom Setup
No
un
rbo
s a@
gs
to
No
un
arb
a
os
ng
st
oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
Each classroom v arb
e d c computer e rab rwill
bo have the same virtual machines e dc econfigured
rab os in the
op ss sa op s s a.
ies .co . ies .co
same way. all
ow
m all
ow
m
ed ed
! !
Hardware Level 6+
• Intel
T
Virtualization Technology (Intel VT) or AMD
T
Virtualization (AMD-V) processor
his his
do do
umc cu
ma 120 m me
• Dual rta
eGBnt
be
hard disks 7200 RM SATA or better*
art
a.b
nt
be
.ba lon a lon
No rbo gs No rbo gs
un sa to un sa to
@ Ma @ Ma
• 8GB aor uth higher
ori
pri
ma rta
au
tho pri
m rta
ze ve Ba riz av Ba
dc rab rbo ed era rbo
op s sa co b s sa
ies s .co . pie s.c .
• DVD drive all m sa
llo
om
ow we
ed d!
!
• Network adapter with Internet connectivity
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 8/8
Module 1: Review of Visual C# Syntax
Contents:
Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a tb
e elo
rbo Module Overview
.ba lon . ba
No gs No rbo ng
un sa to un sa st
@ M @ oM
au p a au p art
tho rim rta tho rim a
Lesson 1: rizeOverview
dc
av
era ofB Writing
arb Application by Using r i z ed Visual a v era C#Barb
op bs o sa co bs os
ies s.c . pie s.c a.
all om sa om
Lesson 2: Data Types, l
ed Operators, and Expressions
ow l ow
ed
! !
Objectives
After completing this module, you will be able to:
• Describe the architecture of .NET Framework applications and the features that
Visual Studio 2012 and Visual C# provide.
In this lesson, you will learn about the features that Visual Studio 2012 and the .NET
Framework
Th 4.5 provide that enable you to create
Th your own applications.
is d is d
oc oc
um um
ma en ma en
a.b rt t b rta tb
Lesson
No arbObjectives
os
elo
ng
st No
.ba
rbo
s
elo
ng
st
un a@ oM un a@ oM
au pri art au p art
tho m a tho rim aB
riz
After completing av lesson,
this Ba you will be able to: riz av arb
ed era rbo ed era
co bs sa co b s os
pie s.c . pie s.c a.
s all om sa om
ow llo
ed we
d!
• Describe the purpose! of the .NET Framework.
• The
Th Common Language Runtime (CLR).
i
Th
is d
sd
oc oc
um um
ma en ma en
• Thert.NET
a.b Framework
be
lo
class library.
t rta
.ba
tb
elo
No arb ng No rbo ng
u os to s un s st
na a@ Ma a@ oM
uth pri au p art
• A collection
ori of m developmentrta frameworks. tho rim aB
ze a ve Ba riz av arb
dc rab rbo ed era
op ss. sa co b s os
ies . pie s.c a.
co sa om
all m llo
ow we
ed d!
!
The Common Language Runtime
The .NET Framework provides an environment called the CLR. The CLR manages
the execution of code and simplifies the development process by providing a robust
and highly secure execution environment that includes:
Th Th
is d is d
oc oc
um um
ma en ma en
berta t rta tb
• Memory
.ba management.
r
lon .ba
r
elo
ng
No bo gs No bo st
u na sa to un sa oM
uth @ Ma au @
pri rta tho pri art
ori
• Transactions. mav Ba riz m av aB
ze era rbo ed era arb
dc bs co bs os
op s.c sa pie s.c a.
ies . sa
all om om
• Multithreading. ow llo
ed we
! d!
hisT T
• Server-side
do web applications, by using ActivehiServer
sd
o Pages (ASP.NET) Web
cu cu
ma e m ma me
Forms
rta or nASP.NET
tb
e
MVC. rta nt
be
.ba lon .ba lon
No rbo gs No rbo gs
un s a@ to un s a@ to
au M a Ma
• Service-oriented
tho pri
m web art applications, by using Windows
a
uth
ori Communication
pri
m rta Foundation
riz av B arb ze a ve Ba
ed era d rab r b
(WCF). co
pie bs
s.c
os
a. co
pie ss. os
a.
sa om sa co
llo llo m
we we
d! d!
• Long-running applications, by using Windows services.
Each framework provides the necessary components and infrastructure to get you
started.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be r ta. tb
. elo
No Additional
b a r bo
l o n Reading:
gs For more information
No about b a rbo the n.NET
gs Framework, see
un sa to u sa to
theau Overview
tho
@
pri ofMa the .NET Framework pageaat
rta
n
uth @
pri Ma
rta
riz ma B ori ma Ba
http://go.microsoft.com/fwlink/?LinkID=267639.
ed
co
ve
rab a rbo z e dc
v e rab rbo
pie ss. s a. op ss. sa
sa c i e sa c .
om om
llo llo
we we
d! d!
• Intuitive integrated development environment (IDE). The Visual Studio 2012 IDE
provides
Th
i
all of the features and tools that areThnecessary
i
to design, implement,
sd sd
oc oc
build,
ma test,
u me and deploy applications and components. m
um
en
rta n t arta tb
.ba be .ba elo
lon ng
No rbo gs No rbo st
• Rapid s
un application a t o development. Visual Studio 2012
u na s
provides
a o design views for
au @ Ma u @ Ma
tho prim rta tho p rim rta
graphicalrizecomponents
dc
av
era Bthat
arb enable you to easily build
o
riz
ecomplex
dc
av
era user Ba interfaces.
rbo
op b ss. sa op b ss. sa
ies . i es .
Alternatively, youallocancuse om the Code Editor views, which provide all
o
co
morem control but
we we
d! d!
are not as easy to use. Visual Studio 2012 also provides wizards that help speed
up the development of particular components.
• Server and data access. Visual Studio 2012 provides the Server Explorer, which
enables you to log on to servers and explore their databases and system services.
It Talso
his Th
provides a familiar way to create, access,
is and modify databases that your
do do
cu cu
application
ma m en uses by using the new table designer.
tb
ma me
nt
rta e rta be
.ba lon .ba lon
No rbo gs No rbo gs
un s a@ t oM un s a@ 2012 to
• Internetau Information
tho pri Services
art (IIS) Express. Visuala uth Studio pri Ma provides a
rta
riz ma aB ori ma Ba
e ve a z e v e
lightweightdversion co rabof IISrboas the default web server ford debugging
ss. s cop
rab
ss.
your
rbo web
sa
pie a. i e .
sa c om sa c om
applications. llo
we
llo
we
d! d!
• Debugging features. Visual Studio 2012 provides a debugger that enables you to
step through local or remote code, pause at breakpoints, and follow execution
paths.
• Error handling. Visual Studio 2012 provides the Error List window, which displays
any errors, warnings, or messages that are produced as you edit and build your
code.
• Help and documentation. Visual Studio 2012 provides help and guidance through
Microsoft IntelliSense®, code snippets, and the integrated help system, which
Th Th
is d is d
containso cu documentation and samples. oc
um
ma me m en
rta nt art tb
.ba b elo a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p at
t
Additional
h ori r ima Reading: r taB For more information aboutt h ori r
what
i ma is rnew a B in Visual
ze ve arb z ed v era arb
dc rab
Studio o2012, pie see
ss. thesaWhat's
o
. New in Visual Studio co 2012
p i e
bs page
s .
osat
a.
sa c om sa c om
http://go.microsoft.com/fwlink/?LinkID=267768.
llo
we
llo
we
d! d!
Visual Studio 2012 supports the development of different types of applications such
as Windows-based
Th
i
client applications, web-based
Th applications, services, and
i
sd sd
cTo o o
libraries. um help you get started, Visual Studio 2012cuprovides
me application templates
m art e nt m art nt
a.b be a.b be
thatNprovide arb a structure
l o ng for the different types ofN applications.arb lon These templates:
gs
ou o s s t o un o s to
na a@ oM a@ Ma
uth pri art auth pri
ori ma aB ori ma rta
ze ve a z e v e Ba
dc rab rbo dc rab rbo
• Provide starter op codessthat you
ies .co
s a. can build on to quickly create op functioning
ies ss.
co
sa
.
all m all m
applications. o we o we
d! d!
• Include supporting components and controls that are relevant to the project type.
• Configure the Visual Studio 2012 IDE to the type of application that you are
developing.
• Add references to any initial assemblies that this type of application usually
requires.
Types
Th of Templates
is d
Th
is d
oc oc
um um
ma en ma en
r
The following
t a.b t table
b describes some of the common r t tb
a.bapplication templates that you
elo elo
No arb ng N arb ng
o sa s to develop .NET Framework applications o o sa s
might uuse
na when
uth @ you Ma un
au @ by tousing Ma Visual Studio
pri r t t h pri rta
ori ma aB ori ma Ba
2012. ze ve arb ze ve rbo
dc rab os dc rab
op s s a o p ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
Template Description
Console Application Provides the environment settings, tools, project references, and starter code
to develop an application that runs in a command-line interface. This type of
application is considered lightweight because there is no graphical user
Th interface. Th
is d is d
oc oc
um um
ma Forms
Windows en ma tools,enproject references, and starter code
Provides the environment settings,
r t
ta. be ta.r t be
ba
Application lon to build a graphical Windows Forms bapplication.
arb lon
N
ou rbo g st N o o gs
na s a@ oM un s a@ to
uth pri art a uth pri Ma
ori m a m
ori projectareferences, rta
WPF Application ze a ve Provides
B arb the environment settings, tools, ze ve Ba and starter code
dc rab o d ra rbo
op ssto s co b ss. sa enables you
ies .cobuild aa. rich graphical Windows application. pAieWPF sa
application
co .
all m m
llo with much more control
ow to create the next generation of Windows applications, we
ed d!
!
over user interface design.
Windows Store Provides the environment settings, tools, project references, and starter code
to build a rich graphical application targeted at the Windows 8 operating
system. Windows Store applications enable you to reuse skills obtained from
WPF development by using XAML and Visual C#, but also from web
Th development by using HTML 5,ThCSS 3.0, and JavaScript.
is d is do
oc c
um um
m en m
art tools, nand e
Class aLibrary
rta tb
e Provides the environment settings, a t b starter code to build a .dll
e
.b arb lon .ba lon
No os gs No rbo gs
u na a@ to un sa to
uth Ma au @ Ma
pri r assembly.
ta You can use this type of t
file to
ho storep r functionality
im rta that you might
ori ma B r a Ba
ze ve a i z e v e
dc rab wantrbto o invoke from many other applications. dc rab rbo
op ss. s a. op ss. sa
ies co ies co .
all m all m
ow ow
ASP.NET Web edProvides the environment settings, tools, project references, ed and starter code
! !
Application to create a server-side, compiled ASP.NET web application.
Template Description
ASP.NET MVC 4 Provides the environment settings, tools, project references, and starter code
Application to create a Model-View-Controller (MVC) Web application. An ASP.NET MVC
web application differs from the standard ASP.NET web application in that the
application architecture helps you separate the presentation layer, business
Th Th
is d is d
logic layer, and data access layer.
oc o cu
um me
ma en ma nt
rta t
b r t be
WCF Service
.ba Application
elo Provides the environment settings,atools, .ba project
lon references, and starter code
No rbo ng N rb gs
sa s to o o sa to
un
au @ M to build Service Orientated Architecture
un
au
(SOA)@ services.
Ma
tho pri art t h pri rta
riz m av a Ba oriz m av Ba
ed era rbo ed era rbo
co b s s a. co b s sa
pie s.c pie s.c
Creating a .NET Framework Application
sa
llo
we
om sa
llo
we
om
.
d! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta tbe rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s t u s st
a@ o Ma na a@ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s co b o
The application templates s s.c provided a in Visual Studio 2012 enable ss.c to sstart
a.
s a you creating
pie . pie
sa om om
llo llo
we we
an application with minimal d! effort. You can then add your code and d! customize the
Th Th
1. is d
Open is d
oc Visual Studio 2012. oc
um um
ma en ma en
rta t be r ta. tb
.ba l o b elo
2. NoIn Visual
r bo Studio,
ngs on the File menu, point to
No New, a rboand then
ng
s t click Project.
un sa to u n sa oM
au @ Ma au @
tho pri rta tho pri art
riz m av Ba riz m av aB
3. In the New e d c Project e rab dialog
rbo box, do the following: d c e e rab arb
os
op s s sa o p ss a.
ies .co . ies .co
all m all m
ow ow
a. Expand Templates, ed
! Visual C#, and then click Windows. ed
!
4. Click OK.
5. The Code Editor window now shows the default Program class, which
contains the entry point method for the application.
Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a.b tb
.ba elo elo
No rbo ng N arb ng
The following
un sa code texample
@
s
oM shows the default Program
o un o sa class
@
s t that Visual Studio
oM
au p a au p art
tho rim rta tho rim aB
provides when riz
ed you av use the
era B arbConsole Application template.r i z ed
a v era arb
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
Program Class d! d!
using System;
using System.Collections.Generic;
T
his Th
using doSystem.Linq; is d
cu oc
m um
ma System.Text;
using en ma en
rta tb rta tb
.ba elo .ba elo
No bo gs r n No rbo ng
usingun System.Threading.Tasks;
sa to un s st
@ Ma a@ oM
au pr au p art
imth ta
ori ConsoleApplication1 r tho rim aB
namespace ze av
e Ba
r
riz
ed
av
era arb
dc rab bo co b os
op ss. sa pie ss.c a.
{ ies co . sa
all m om
ow llo
we
class Program ed! d!
{
static void Main(string[] args)
{
}
Th Th
}is do is d
oc
cu um
ma me ma en
} rta be
nt rta tb
.ba lon .ba elo
No rbo gs No rbo ng
u s to un sa st
na a@ Ma @ oM
uth pri au pri art
ori ma rta tho m aB
ze ve Ba riz av arb
dc rab rbo ed era
After you createopaie project, ss. you sa can
. then use the features that co
pie Visual bs Studio
s.c
os
a. provides
sa c om sa om
llo llo
to create your application. we
d!
we
d!
Th Th
is d is d
• The Quick
o cu Info option displays the complete declaration oc
um for any identifier in your
ma me m en
rta Move n a
t b the mouse so that the pointer restsrtaon ant bidentifier to display Quick
code. .ba elo .ba elo
No rbo ng No rbo ng
sa s to sa st
Infounfor
au that @identifier,
p M a
which appears in a yellow un pop-up
au @
p
box. oM
art
tho rim rta tho rim aB
riz av B arb r i z a v arb
ed era ed era
co bs o sa co bs os
• The Complete pieWord
sa
soption
.c om
.enters the rest of a variable, command,
p i e sa
s . c om or afunction
.
llo llo
we w
name after you have d!typed enough characters to disambiguateedthe ! term. Type the
first few letters of the name and then press Alt+Right Arrow or Ctrl+Spacebar to
complete the word.
Th Th
Lesson
is d
oc
u
2: Data Types, Operators,
is d
oc and Expressions
u
ma me ma me
rta nt r nt
.ba b elo t a.ba be
n lon
No rbo gs No rbo gs
un s a@ to un s a@ to
a
All applications
uth puse M
data.
art This data might be supplied a uth by the pri user Ma through a user
ori r im a ori m rta
ze a ve B arb ze a ve Ba
d r d r rbo
interface, from caop database, ab
ss. from
o sa
.
a network service, or from cop some a b other
ss. source.
sa
.
To
ies co i es co
store and use data ain llo yourmapplications, you must familiarize yourself all
ow
m
with how to
we e
d! d!
define and use variables and how to create and use expressions with the variety of
operators that Visual C# provides.
In this lesson, you will learn how to use some of the fundamental constructs in Visual
C#, such
Th
i
as variables, type members, casting, and
Th
i
string manipulation.
sd sd
oc oc
um um
ma en ma en
rta t be rta tb
ba .lon .ba elo
Lesson
No
u
rbObjectives
o s a
gs
to
No
un
rbo
sa
ng
st
oM
na @ Ma au @
uthpri rta tho pri art
ori ma Ba riz m av aB
After z
completing v arb
e d c thisralesson,
e
b
rbo you will be able to: e dc e rab os
op ss. sa op ss a.
ies co . ies .co
all m all m
ow ow
ed ed
! !
• Describe the data types provided by Visual C#.
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
A variable
No
un
rbholds
o s a
data
gs
t o
of a specific type. When you
No declare
u
rbo
s a
angvariable
st
oM
to store data in
au @ Ma na @
tho prim rta to choose an appropriate data u tho p ri a rta data. Visual C#
an application, riz
ed
you av need Ba riz typemfor
ed
av that Ba
era rbo era rbo
co b ss. which sa c op b ss. that sa
is a type-safe language, pie
sa co . means that the compiler guarantees
i es co values
.
llo m a llo m
stored in variables arewealways d! of the appropriate type. we
d!
(bytes)
T Th
stringhis d Sequence of 2 per characteriN/A
sd
oc oc
um characters um
ma en ma en
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s t u s st
a @ o Ma na a@ oM
au p u p art
tho rim r tho rim
Additional riz
ed
Reading:
av
ta B a
For more information about riz data types,
ed
av a see
Ba the
era rbo era rbo
Reference c op Tables b ss. for sTypesa. (C# Reference) page cat
op b ss. sa
ies co i es co .
all m all m
http://go.microsoft.com/fwlink/?LinkID=267770.
o we o we
d! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta tbe rta tb
.ba lon .ba elo
No rbo gs No rbo ng
u s to un sa st
na a@ Ma @ oM
uth pri au pri art
ori ma rta tho m aB
ze ve Ba riz av arb
dc rab rbo ed era
op ss. sa co bs os
ies . pie s.c a.
co sa om
all m llo
ow we
ed d!
!
Expressions are a central component of practically every Visual C# application,
because expressions are the fundamental constructs that you use to evaluate and
manipulate data. Expressions are collections of operands and operators, which you
can define as follows:
• Operands are values, for example, numbers and strings. They can be constant
Th Th
is d is d
(literal)cuvalues, variables, properties, or return values
o oc
um from method calls.
ma me m en
rta n tb a rta tb
.ba elo .ba elo
r ng r ng
• Operators
N ou b os define
a@
s t operations to perform on operands,
oM
N o un
b o safor example,
st
oM
addition or
na au @
uth pri art tho p rim a rta
multiplication.
ori
ze
m Operators
av a B exist for all of the basic mathematical
a riz
e
av operations,
Ba as well
dc e rab rbo dc e rab rbo
op sa
ss. operations op sa
ss.the manipulation
as for more advanced ies co . such as logical comparison ies or co .
all m all m
ow ow
of the bits of data that ed constitute a value.
!
ed
!
All expressions are evaluated to a single value when your application runs. The type
of value that an expression produces depends on the types of the operands that you
use Tand
his the operators that you use. There is noThlimit
d is d to the length of expressions in
oc oc
me u me u
Visual
ma C# applications,
r nt although in practice, youmare
ar limited
nt by the memory of your
ta. be ta. be
arb b lo b lo
computer
No
u
and a
ng patience when typing. However,
os yourst
o
No
u
itarbis a
ng
os usually
s t advisable to use
o
na @ Ma na @ Ma
tho u
rim and p tho rim
rta assemble the results of expression-processing
rta u p
shorter expressions
riz av Ba riz av Ba piecemeal.
ed era rbo ed era rbo
op bs c
sa bs
op as well sa c
This makes it easier
ies for s.you
co to . see what your code is doing, ies s.cas making
o
. it
all m all m
o ow
easier to debug your wcode.
ed
!
ed
!
Operators in Visual C#
Operators combine operands together into expressions. Visual C# provides a wide
range
T of operators that you can use to perform Tmost fundamental mathematical and
his his
do
logical operations.
cu
m Operators fall into the following dthree
oc
um categories:
ma en ma en
rta be t rta tb
.ba lon .ba elo
No r bo gs No rbo ng
un sa to u sa st
@ n @ oM
• Unary.uthThis type
a pri
ma
of aoperator
M
rta operates on a singleutoperand.
a
ho pri For
m
arexample,
ta
you can
ori Ba riz av Ba
ze ve rbo e e rbo
use the - operator
dc
op
raas
bs a unary
s.c sa operator. To do this, you place
dc
op
rit
abimmediately
ss. sa before
ies . i e s c .
all o m a o m
a numeric operand, ow and it converts the value of the operandllto
ed
ow its current value
ed
! !
multiplied by –1.
• Binary. This type of operand operates on two values. This is the most common
type of operator, for example, *, which multiplies the value of two operands.
• Ternary. There is only one ternary operator in Visual C#. This is the ? : operator
that is used in conditional expressions.
The following table shows the operators that you can use in Visual C#, grouped by
type.This Th
is d
do oc
cu um
ma me ma en
rta nt rta tb
.ba be .ba elo
lon ng
No rbo gs No rbo st
Type nau
u s a to Operators
un sa oM
@ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
c o b s sa co bs os
Arithmetic pie s.c . +, -, *, /, % pie s.c a.
sa om sa om
llo llo
we we
Increment, decrement d! ++, -- d!
String concatenation +
Indirection
Th and Address (unsafe code only) *, ->,Th[ ], &
is d is d
oc oc
um um
ma
Conditional en
(ternary operator) ?: ma en
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
u s to un sa st
na a@ Ma @ oM
uth pri au pri art
Expression Examples
ori
ze
ma
ve
rta
Ba
tho
riz
ed
m av
era
aB
arb
dc rab rbo os
op ss. sa co bs a.
ies co . pie s.c
sa o
You can combine the all basic
ow
m building blocks of operators and operands llo
we
m to make
ed d!
!
expressions as simple or as complex as you like.
a + 1
The T+hisoperator
d
Th
can operate on different data types,
is d and the result of this expression
oc oc
u
me the data types of the operands. Formexample,
me u
depends
ma
r
on nt ar nt if a is an integer, the result
ta. be ta. be
ba lon ba lon
of theo uexpression
N r b os gis
s t an integer with the value 1 greater N ou rb othan
s a.
gs If a is a double, the
to
na a@ o M na a@ Ma
uth pri art uth pri
result is a odouble
riz m with
av thea Bavalue 1 greater than a. The o difference
riz m av is asubtle
rt
Ba but
ed era rbo ed era rbo
co bs sa (a is a double), the Visual C# co bs sa to generate
important. In the pisecond
es s.c case
om
. picompiler
es s.c has
om
.
all all
ow ow
code to convert the constant ed
!
integer value 1 into the constant double ed
!
value 1 before
the expression can be evaluated. The rule is that the type of the expression is the
same as the type of the operands, although one or more of the operands might need
to be converted to ensure that they are all compatible.
The Tfollowing
his
d
code example shows how to use Tthe
his / operator to divide two int values.
d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
N r No rbo ng
/ Operator
ou b os
a@
gs
to un s a
st
oM
na Ma au @
uth pri rta tho p rim art
ori m a Ba riz av aB
ze ve rbo ed era arb
dc rab co b os
op ss. sa pie ss.c a.
ies co . sa
all m om
ow llo
ed we
5 / 2 ! d!
The value of the result is the integer value 2 (not 2.5). If you convert one of the
operands to a double, the Visual C# compiler will convert the other operand to a
double,
Th and the result will be a double. Th
is d is d
oc oc
um um
ma en ma en
rta t b rta tb
.ba elo . elo
TheNfollowingrbo code ng example shows how to
s
useNthe / aoperator
b
rb o
ng to divide a double
st
ou sa to ou sa oM
n @ Ma na @
value byauan
tho int pvalue.
rim rta uth
ori
pri
ma
art
aB
riz av Ba ze ve arb
ed era rbo dc rab
co bs sa op s os
pie s.c . ies s .co a.
s all om all m
/ Operator ow ow
ed ed
! !
5.0 / 2
The value of the result now is the double value 2.5. You can continue building up
expressions with additional values and operators.
The following code example shows how use the + and – operators in an expression.
Th Th
is d is d
oc oc
+ and
m
– Operators
um
e ma
um
en
art nt rta tb
a.b be .ba elo
arb lon ng
No os gs No rbo st
un a to un sa oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
a + b - 2 cop bs sa co
pie bs os
a.
ies s .co . s.c
all m sa om
ow llo
ed we
! d!
This expression evaluates to the sum of variables a and b with the value 2 subtracted
from the result.
Some operators, such as +, can be used to evaluate expressions that have a range
Th Th
sdi is d
of types. oc
u
oc
um
ma me ma en
rta nt rta tb
.ba be .ba elo
lon ng
No rbo gs No rbo st
s texample s
The following
un
au code
a@
pri
oM
art
shows how to use thena+
u
uthoperator
a@
pri
to
o Mconcatenate
art
two
tho m aB ori m aB
riz av ze av
string values. ed
co
era
b
arb
os dc era
bs
arb
os
pie s s.c a. op s.c a.
sa om ies o
llo all m
we ow
d! ed
!
+ Operator
Th Th
is d is d
oc oc
um um
maoperator
The + en uses an operand that is a result m
ofarta method
en call, ToString(). The
rta tb a tb
.ba elo .ba elo
N r b ng N rb ng
ToString()
ou
na
method
o sa s tconverts
oM the value of a variable
o u into sa
na
o
a@string,
s t whatever
oM type it is.
uth @ uth
pri art pri art
ori ma aB ori ma aB
ze ve a rbo z e v e arb
dc rab dc rab os
op s s sa o p ss a.
The .NET Framework ies class
.co .
library contains many additional iemethods
s .co that you can
all m all m
ow ow
ed
use to perform mathematical ! and string operations on data, such eas d! the
System.Math class.
Additional Reading: For more information about operators, see the C#
Operators page at http://go.microsoft.com/fwlink/?LinkID=267771.
Before you can use a variable, you must declare it so that you can specify its name
and characteristics. The name of a variable is referred to as an identifier. Visual C#
has Tspecific
his
do rules concerning the identifiers thatThyou
is d can use:
o
cu cu
ma me ma me
rta nt r nt
.ba b elo t a.ba be
n lon
No rbo gs No rbo gs
• An uidentifier
na s a@ can only
to
M
contain letters, digits, andun underscore s a@ tocharacters.
Ma
uth pri art a uth pri
ori ma aB ori ma rta
ze ve arb ze ve Ba
dc rab d ra rbo
• An identifier omust pie start
ss. with o sa a letter or an underscore. op
.
c
i es
b ss. sa
.
sa co co
llo m a llo m
we we
d! d!
• An identifier for a variable should not be one of the keywords that Visual C#
reserves for its own use.
Visual C# is case sensitive. If you use the name MyData as the identifier of a
Th Th
is d i
variable,octhis
u
is not the same as myData. You cans ddeclare
oc
u
two variables at the same
m me m me
art nt art not nconfuse
time called
a.b MyData
be
lo
and myData and Visual C# will
a.b tb
elo them, although this is
N arb ng No arb ng
ou os st os st
not goodna coding
u
a@ practice.
p
oM
a
un
au a@
pri
oM
art
tho rim rta thori ma aB
riz av Ba z ve arb
ed era rbo ed rab
co bs sa os co ss.
pie . s.c ies a. p
o s o c
When declaring variables
all
ow
myou should use meaningful names for
all yourmvariables,
ow
ed ed
because this can make your code easier to understand. You should! also adopt a
!
The following code example shows how to use the = operator to assign a value to a
variable.
Th Th
is d is d
oc oc
Assigning
m
uma Variable
e ma
um
en
art nt rta tb
a.b be .ba elo
arb lon ng
No os gs No rbo st
na u a@ to un sa oM
uth Ma au @
pri rta tho pri art
ori ma Ba riz m av aB
ze ve rbo ed era arb
// variableName dc r=
a b value; co bs os
op ss. sa pie s.c a.
ies co . sa
all m om
price = 10; ow llo
ed we
! d!
The value on the right side of the expression is assigned to the variable on the left
side of the expression.
You can declare a variable and assign a value to it at the same time.
When you declare a variable, it contains a random value until you assign a value to it.
This behavior was a rich source of bugs in C and C++ programs that created a
variable and accidentally used it as a source of information before giving it a value.
T T
VisualhisC# his
do does not allow you to use an unassigned dovariable. You must assign a value
cu cu
ma m ma program
enbefore you can use it; otherwise, your en m
to a variable
rta tb rta tb might not compile.
.ba elo .ba elo
No rbo ng No rbo ng
u sa s to un sa st
na @ Ma @ oM
uth pri au pri art
m rta th ma aB
ImplicitlyorizTyped
ed
av Variables
era Ba
rb
ori
zed ve
rab arb
co bs os co ss. os
pie s.c a. p ies a.
s om c om
all all
When you declare variables,
ow
e you can also use the var keyword oinstead
we of specifying
d! d!
an explicit data type such as int or string. When the compiler sees the var keyword,
it uses the value that is assigned to the variable to determine the type.
In the following example shows how to use the var keyword to declare a variable.
Th Th
is d is d
oc oc
Declaring uma Variable by Using the var Keyword um
ma en ma en
rta tb rta tb
.ba elo .ba elo
No r bo ng No rbo ng
un sa st un sa st
@ oM @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
var price =co20; bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
In this example, the price variable is an implicitly typed variable. However, the var
keyword does not mean that you can later assign a value of a different type to price.
The type of price is fixed, in much the same way as if you had explicitly declared it to
be an integer variable.
Implicitly typed variables are useful when you do not know, or it is difficult to establish
explicitly, the type of an expression that you want to assign to a variable.
Th Th
is d is d
Object Variables
um
oc oc
um
ma en ma en
rta b t r t a.b tb
.ba elo elo
n arb ng To use an object
WhenNo uyou declare
r b os g san
to
object variable, it is initially
N o unassigned.
un o sa st
na a@ M @ oM
uth pri art au p art
variable, you ori must ma create a B an instance of the corresponding t h ori r class,
i ma by a B using the new
ze ve arb z ed v era arb
dc rab o co bs os
operator, and assign op itsto
s the sobject
a variable. p s a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
The new operator does two things: it causes the CLR to allocate memory for your
object, and it then invokes a constructor to initialize the fields in that object. The
version of the constructor that runs depends on the parameters that you specify for
the new operator.
Th Th
is d is d
oc oc
um me u
The following
ma
rt
en code example shows how to create
tb
ma an instance
rt nt
b
of a class by using the
a.b elo a.b elo
N arb ng No a rbo ng
new ooperator.
un o s a
st
oM un sa st
oM
au @ au @
tho prim art th pri art
riz av aB ori ma aB
ed era arb zed ve arb
co b os co rab os
pie s s.c a. p ss. a.
The new Operator sa om ies
all
c om
llo ow
we ed
d! !
Th Th
Additional
is d Reading: For more information isabout
do declaring and assigning
oc cu
u
mvariables,
art
me
nt see the Implicitly Typed LocalmVariables
art
me
nt (C# Programming
a.b be a be
N Guide) arb page lon at http://go.microsoft.com/fwlink/?LinkID=267772.
.ba lon
ou os g st N rb g
ou os st
na a@ oM na a@ oM
uth pri art uth pri art
ori mav aB ori ma aB
ze era arb zed ve arb
dc bs os co rab os
op s.c a. p ss. a.
ies ies c
Accessing Type
ow Members
e
all om all
ow
ed
om
d! !
Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
To access au a member
tho
@
prim
Mof
a an
rta
instance of a type, use athe
u tho name @
p rim the
of art instance, followed
riz av B r a aB
ed eraby the arb i z ed known v era as dotarb
by a period, followed co bs name
o sa of the member. This is co bs onotation.
sa
pie s.c . pie s.c .
sa om sa om
Consider the following llo rules and guidelines when you access allomember of an
we we
d! d!
instance:
• To access a method, use parentheses after the name of the method. In the
parentheses, pass the values for any parameters that the method requires. If the
method
Th does not take any parameters, the parentheses
Th are still required.
is d is d
oc oc
um um
ma en ma en
• To access
rta
.ba
tabepublic property, use the property name. rta
.ba
You
t b can then get the
elo value of
lon ng
No rbo gs No rbo st
thatunproperty
au
s a @ or set
t o Ma
the value of that property. u na s a @ oM
tho prim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s co b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d
The following code example shows how to invoke the members that
! d! the
Invoking Members
Th Th
is d is d
oc oc
um um
m en ma en
var aconfig
rta
.ba
t b= new ServiceConfiguration();
elo rta
.ba
tb
elo
No r bo ngs No rbo ng
// Invoke
un sathe LoadConfiguration
to method. u sa st
@ M n @ oM
a uth pr ar a uth pr ar
ori im ta ori im ta
var loadSuccessful
ze av =Barconfig.LoadConfiguration();
ze av Ba
dc era b d era rbo
op b ss. o s cop b ss. sa
i e a. i e .
// Get the value s a from c om the ApplicationName property. sa c om
llo llo
we we
d! = config.ApplicationName;
var applicationName d!
Additional Reading: For more information about using properties, see the
Properties (C# Programming Guide) page at
Thhttp://go.microsoft.com/fwlink/?LinkID=267773.
Th
is do is do
cu cu
ma me ma me
rta nt r nt
.ba b elo t a.b be
ng a lon
No rbo st N ou rb os gs
un sa o n a to
au @ M au @ Ma
pri art pri
Additional
t h ori
ze
mReading:
av a Ba For more information about t h oriz using m avmethods,rta
Ba see the
dc e rab rbo e dc e rab rbo
Methods o(C# pie Programming
ss. sa
.
Guide) page at op
ies ss .co
sa
.
sa co
llo m
http://go.microsoft.com/fwlink/?LinkID=267774. a llo m
we we
d! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ Ma a@ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
llo m llo
we we
d! d!
When you are developing an application, you will often need to convert data from one
type to another type, for example, when a value of one type is assigned to a variable
of a different type. Consider the scenario where a user enters a number into a text
T
his his T
box. To duse
o
this number in a numerical calculation, doyou will need to convert the string
cu cu
m me m me
value a99
rta that t you
n
b have read from the text box intoartthe a
integer
nt
be value 99 so that you
.ba elon .ba lon
r r
can Nstore
ou
na
itboin @
gs
sa an integerto variable. The process Nof na
bo
o uconverting sa
@
ga
s tvalue of one data type
oM
uth pri M art uth pri art
to another typeo m a o m aB
ed is called type conversion or casting.
riz av Ba riz av arb
era rbo e d e ra
co bs sa co bs os
pie s.c . p ies s .co a.
sa om a m
llo llo
w we
There are two types ofedconversions ! in the .NET Framework: d!
• Explicit conversion, which requires you to write code to perform a conversion that
otherwise could lose information or produce an error.
Th Th
is d do is
The following
oc
um code example shows how data is converted
cu
m implicitly from an integer to
ma en ma en
tb tb
a long,rtwhich
a.b
a rbo
iselotermed
ng
widening. rta
.ba
rbo
elo
ng
No s No st
un s a@ to un s a oM
au Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
Implicit Conversion co
pie b ss. sa co
pie b s os
a.
co . s.c
sa m sa om
llo llo
we we
d! d!
int a = 4;
long b;
b = a; // Implicit conversion of int to long.
Th Th
is d is d
oc oc
um um
This mconversion
art
a.
en
e
ma
t b always succeeds and never results
.
e
rta in ant loss
be of information. However,
ba lon ba lon
r r
you Ncannot
ou
na
bo
sa
@
gs
implicitly M
N
to convert a long value to an oint,
a
bo
un because
sa
@
gs
this
to conversion risks
M
uth pri art uth pri art
ori ma aB o ma aB
losing information
ze
d
(the
ve
r
longarb value might be outside therizrange
ed vsupported
er arb by the int
co ab os ab co os
pie ss. a. i ss.p a.
type). The following s a table co shows
m the implicit type conversionss that
e
all areco supported
m in
llo ow
we ed
Visual C#. d! !
From To
From To
float double
Explicit
Th Conversions Th
is d is d
oc oc
um me u
In Visual
ma
rt C#,ntyou
e
b
can use a cast operator to perform
ma
rt explicit
nt
b
conversions. A cast
a.b elo a.b elo
arb arb
specifies
Nou theosatypengto s t convert to, in round
oM
brackets
N o u before a
n
os the gvariable
st
oM
name.
na @ na @
uth pri art uth pri art
ori m av aB ori ma aB
ze era arb ze ve arb
dc bs os dc rab os
op a. op s a.
The following code ies example
all
s.c
o m
shows how to perform an explicit ies conversion.
all
s.c
o m
ow ow
ed ed
! !
Explicit Conversion
int a;
T Th
longhis b
do = 5; is d
oc
cu um
m
a =ma(int)
rta
en b;
tb // Explicit conversionmaof
rta long
en
t b to int.
.ba elo .ba elo
No rbo ng No rbo ng
un sa s to u sa st
@ M n @ oM
a uth pri art a uth pri art
ori mav aB aB
ori ma
ze era arb z arb
ed ve
dc r a
You can also perform
op
ies
ban
s s explicit
.co
os
a . conversion by using the as
co operator,
p ies
bs
s .co
but
os only
a. for
all m all m
reference type objects. ow The advantage of using the as operator ois
ed we that if the
d!
!
conversion fails due to the types being incompatible, instead of the CLR throwing an
InvalidCastException, the cast operation will return null, which you can then check
for in your code.
The following code example shows how to use the as operator to cast between two
data types.
T
his Th
do is d
int a; cu oc
um
ma me ma en
nt tb
long rtba.b = 5; be
l
rta
.ba elo
on
arb rbo ng
No gs os No st
u
a = bnaas int; a to un sa oM
uth @ Ma au @
pri rta tho p rim art
ori ma Ba riz av aB
if (a != znull)ed ve
rab rbo ed era arb
os
co s sa co bs a.
pie s.c . pie s.c
{ sa om sa om
llo llo
we we
d! d!
// Cast successful.
}
You can only perform meaningful conversions in this way, such as converting a long
to anThint. Th
is d You cannot use a cast if the format of the
is d data has to physically change,
oc oc
me u me u
suchmas
ar if you
nt are converting a string to an integer.
ma
r
To nperform
t these types of
ta. be ta. be
arb b
n lo arb ng class. b lo
conversions,
No
u os you gcan
a
s t use the methods of the System.Convert
o
No
u os
a
st
o
na @ Ma na @ Ma
uth pri rta uth pri rta
ori mav Ba ori ma Ba
ze era rbo zed ve rbo
dc bs co rab
op sa ss. sa
Using the System.Convert
a om Class ies s.c . p ies
all
c om
.
llo ow
we ed
d! !
The System.Convert class provides methods that can convert a base data type to
another base data type. These methods have names such as ToDouble, ToInt32,
ToString, and so on. All languages that target the CLR can use this class. You might
find this class easier to use for conversions than implicit or explicit conversions
because
T IntelliSense helps you to locate the conversion
T method that you need.
his his
do do
cu c
um
ma me ma en
rta nt rta tb
be
TheNfollowing
.ba
r
code
lon example converts a string
g
to
No
an .bint.
a r
elo
ng
ou bo st bo st
na sa oM un sa oM
uth @ au @
pri art tho pri art
ori mav aB riz m av aB
rboze era a ed era arb
Conversionsd by
co Using
p bs the
s
ToInt32
sa Method co
pie bs
s.c
os
a.
ies .co . sa
all m om
ow llo
ed we
! d!
Additional Reading: For more information about casting variables, see the
Casting and Type Conversions (C# Programming Guide) page at
http://go.microsoft.com/fwlink/?LinkID=267775.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be rta tb
.ba .ba elo
Manipulating
No
u
rbo
s a
lon
gs Strings
to
No
un
rbo
sa
ng
st
oM
na @ Ma au @
uth pri rta tho pri art
ori mav Ba riz m av aB
ze era rbo ed era arb
dc bs co bs os
op s.c sa pie s.c a.
ies . sa
all om om
ow llo
ed we
! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa to un sa st
@ @ oM
Strings aare
uth a very pri useful
ma
Ma data type
rta that enable youato uth capture pri and
ma
artstore alphanumeric
ori Ba ori aB
ze ve rbo ze ve arb
data. dc
op
rab
s sa
dc
op
rab
s os
a.
ies s .co . ies s .co
all m all m
ow ow
ed ed
! !
Concatenating Strings
Concatenating multiple strings in Visual C# is simple to achieve by using the +
operator. However, this is considered bad coding practice because strings are
immutable. This means that every time you concatenate a string, you create a new
T T
stringhiin
s d memory and the old string is discarded.his d
o o
cu cu
ma me ma me
rta nt r nt
.ba b elo t a.ba be
n lon
No rbo gs No rbo gs
The following
un
au
s code texample
a@ oM creates five string values
un
a
asa@it runs.
s to
Ma
tho pri art uth pri rta
riz m av a B ori m a Ba
ed era arb ze ve rbo
co b o d c ra b
pie ss. sa op ss. sa
. i es .
Concatenation bys aUsing llo
co the + Operator
m a llo
co
m
we we
d! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be rta tb
.ba lon .ba elo
Validating Strings
No
un
rbo
sa
gs
to
No
un
rbo
sa
ng
st
oM
au @ Ma au @
tho pri rta tho p rim art
riz m av B riz av aB
When acquiring e d c input e rabfromarthe bo user interface of an application,ed
co
edata
ra
ar
bs is boften
os provided
op s s.c sa pie s.c a.
ies . sa
om om
as strings that you need a llo
we
to validate and then convert into a format llo that
we
your
d! d!
application logic expects. For example, a text box control in a WPF application will
return its contents as a string, even if a user specified an integer value. It is
important that you validate such input so that you minimize the risk of errors, such as
InvalidCastExceptions.
Th Th
is d is d
Regular expressions
o cu
me provide a mechanism that enablesoc
um you to validate input. The
ma n m a en
rta t be provides the System.Text.RegularExpressions rta tb
.NET Framework
.ba
rbo
lon .ba
rbo
elo
ng
namespace that
No gs No s
un s a@ to un s ain to
includes authe Regex
tho pri class.
Ma
rta
You can use the Regex aclass
uth @ your
pri applications
M art to test a
riz m av B ori m a aB
string to ensure ed e
co thatrait b s
arb
conforms os to the constraints of azregular ed
co
ve
expression.
rab
s
arb
os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The following code example shows how to use the Regex.IsMatch method to see if a
string value contains any numerical digits.
Regex.IsMatch Method
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be r ta. tb
.ba
var textToTest lon = "hell0 w0rld"; ba elo
No r bo gs No rbo ng
un sa to u sa st
@ M n @ oM
au
var regularExpression pri art = "\\d"; auth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rb e d e r
var result = co Regex.IsMatch(textToTest,
bs os
a.
regularExpression, co a bs os
a.
pie s.c pie s.c
sa om sa om
RegexOptions.None); llo llo
we we
d! d!
if (result)
{
// Text matched expression.
}
Regular expressions provide a selection of expressions that you can use to match to
a variety of data types. For example, the \d expression will match any numeric
Th
characters. Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a.b tb
.ba elo elo
No rbo ng N arb ng
s o o st
Additional
un
au
sa
@ Reading:
to
M For more information uabout
n au
susing
a @ regular
oM expressions,
tho prim a rta tho p rim art
see the riz Regex av Class Ba page at http://go.microsoft.com/fwlink/?
riz av aB
ed era rbo ed era arb
co bs sa co bs os
LinkID=267776. pie
sa
s.c
om
. pie
sa
s.c
om
a.
llo llo
we we
d! d!
Application logic often needs to run different sections of code depending on the state
Th in the application. For example, if a userThrequests to close a file, they may be
of data
is do is do
cu cu
asked ma whether m en they wish to save any changes. If
t
matheymdo, en the application must
tb
rta be rta elo
.ba lon .ba
execute
No code
rbo to save
s
gs
t
the file. If they don’t, the application
N o rbo
s
logic
ng can simply close the
st
un a @ o Ma u na a@ oM
au p u p art
file. Visual thoC# uses
riz
rim conditional
av
rta
B statements to determine tho which
riz
rim code
av a Bsection to run.
ed era a rbo ed era arb
co b s s co b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
The primary conditional we statement in Visual C# is the if statement. we There is also a
d! d!
switch statement that you can use for more complex decisions.
Conditional Statements
You Tuse if statements to test the truth of a statement.
T If the statement is true, the
his his
block ofdocode
cu
do
m associated with the if statement is executed,
cu
m if the statement is false,
ma en ma en
tb tb
controlrtpasses
a.b
ar
eover
lon the block. rta
.ba
r
elo
ng
No bo gs No bo st
u na sa to un sa oM
uth @ Ma au @
pri rta tho pri art
ori mav B riz m av aB
ze
arb era ed era ar
The followingdcode
co
p
shows
bs howos to use an if
a
statement to determine co
pie bs if abstring
os
a.
ies s.c . s.c
a om sa om
contains the value connection_failed.
llo
we
llo
we
d! d!
if Statement
string response = "….";
if (response == "connection_failed")
{
// Block of code to execute if the value of the response
variable is
"connection_failed".
T Th
his is d
do oc
} cu um
ma me ma en
rta nt rta tb
.ba be .ba elo
lon ng
No rbo gs No rbo st
un sa to un sa oM
au @ Ma au @
tho pri rta tho p rim art
m aB
if statements riz can ahave
ed ve
rab
associated
Ba
rbo else clauses. The else riz
ed blockav executes
era arb when the if
co s sa co bs os
pie s.c . pie s.c a.
statement is false.s al om sa
llo
om
low we
ed d!
!
The following code example shows how to use an if else statement to execute code
when a condition is false.
if else Statements
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un response s to = "…."; un s st
string au a@ Ma au a@ oM
tho pri rta tho p rim art
r m a Ba riz av aB
if (response ize v
d c ==er"connection_failed")
a b
rbo ed
co
era
b
arb
os
op ss. sa pie ss.c a.
ies co . sa
{ all m om
ow llo
ed we
! d!
// Block of code executes if the value of the response variable
is
"connection_failed".
}
else
Th Th
is d is d
{ oc oc
um um
ma nt e art n m e
//
rta Block
.ba be of code executes if the value
lon a.b oft btheelo response variable
No r bo gs No a rbo n gs
is not
un sa to un sa to
a uth @ M a @ M uth
pri art pri art
riz av o
Ba m a ori ma aB
"connection_failed".
ed era rb z ed ve arb
co bs os co rab os
pie s.c a. p ies ss. a.
} s om c om
all all
ow ow
ed ed
! !
if statements can also have associated else if clauses. The clauses are tested in the
order that they appear in the code after the if statement. If any of the clauses returns
true, the block of code associated with that statement is executed and control leaves
the block of code associated with the entire if construct.
The following code example shows how to use an if statement with an else if clause.
elseTif Statements Th
his is d
do oc
cu um
ma me ma en
rta nt r tb
.ba b elo t a.b elo
No rbo ng N arb ng
un response sa s to = "…."; o un o sa st
string @ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r i z a v arb
if (response ed == er"connection_failed")
a ed era
co bs o sa co bs os
pie s.c . pie s.c a.
{ sa om sa om
llo llo
we we
d! d!
// Block of code executes if the value of the response variable
is
"connection_failed".
}
else if (response == "connection_error")
Th Th
is d is d
{ oc
um
oc
um
ma en ma en
rta Block t
be of code executes rta t
// .ba lon if the value .ba of bthe elo response variable
No rbo gs No rbo ng
s to sa st
is unau a@
pri Ma un
au @
p
oM
art
tho m rta tho rim aB
riz av Ba riz av arb
"connection_error".ed era rbo ed era
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
} llo m llo
we we
d! d!
else
{
// Block of code executes if the value of the response variable
is not
"connection_failed" or "connection_error".
Th Th
is d is d
} oc
um
oc
um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
u s to un sa st
na a@ Ma @ oM
uth pri au pri art
ori ma rta tho m aB
ze ve Ba riz av arb
dc rab rbo ed era
Selection Statements op
ies ss.
co
sa
.
co
pie bs
s.c
os
a.
all m sa om
ow llo
ed we
If there are too many if/else ! statements, code can become messy dand ! difficult to
follow. In this scenario, a better solution is to use a switch statement. The switch
statement simply replaces multiple if/else statements.
The following sample shows how you can use a switch statement to replace a
collection of else if clauses.
switch Statement
Th Th
sd i is d
string ocresponse = "….";
u
oc
um
m me ma en
nt
art (response) rta tb
switch a.b be
l .ba elo
arb on rbo ng
No os gs No st
{ u na a@ to un sa oM
uth Ma au @
pri rta tho p rim art
ori mav Ba riz av aB
ze era rbo ed era arb
dc bs co bs os
op s.c sa pie s.c a.
ies . sa
all om om
ow llo
ed we
! d!
case "connection_failed":
// Block of code executes if the value of response is
"connection_failed".
break;
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
s to s st
caseun"connection_success":
au a@
pri Ma un
au a@
p
oM
art
tho m rta tho rim aB
riz av Ba riz av arb is
// Block ed era code
of rbo executes if the value eof d c responseera
co b ss. sa op bs os
pie . ies s.c a.
sa co o
"connection_success". llo m all m
we ow
d! ed
!
break;
case "connection_error":
Th
is d // Block of code executes if theThivalue
sd of response is
oc oc
um um
ma
"connection_error".en ma en
rta tb rta tb
.ba elo .ba elo
No r
break;bo ng No rbo ng
un sa st un sa st
@ oM @ oM
au pri art au pri art
default: tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
// Block p ies executess .co a.if none of the above conditions p ies s .co are a. met.
all m all m
ow ow
break; ed ed
! !
}
In each case statement, notice the break keyword. This causes control to jump to the
end of the switch after processing the block of code. If you omit the break keyword,
your code will not compile.
Notice that there is an else block labeled default:. This block of code will execute
when none of the other blocks match.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t b r t a tb
. e . elo
No Additional
lon Reading: For more information about
rbo selection statements, see
ba ba ng
rbo gs No st
un sa t o u s a o
theau Selection
tho
@
pri Statements
Ma
rta
(C# Reference) npageau
tho at prim
@ Ma
rta
riz m av Ba riz av Ba
http://go.microsoft.com/fwlink/?LinkID=267777.
ed
co
era
b
rbo ed
c
era
b
rbo
pie s s.c s a. o pie ss.c sa
sa sa .
om om
llo llo
we we
d! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ Ma a@ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
llo m llo
we we
d! d!
Iteration provides a convenient way to execute a block of code multiple times. For
example, iterating over a collection of items in an array or just executing a function
multiple times. Visual C# provides a number of standard constructs known as loops
that you can use to implement iteration logic.
Th Th
is d is d
oc oc
um um
For mLoops
art
a
en
tb
e
ma
rta
en
tb
elo
.ba lon .ba
No r bo gs No rbo ng
un sa to u sa st
n oM
The foraloop
uth executes
@
pri M a
art block of code repeatedly until
auth the @ specified
pri art expression
ori ma aB ori ma aB
z ve arb ze ve arb
evaluates to efalse.dc
op Yourab can
s
define
os
a
a for loop as follows. d co ra bs os
a.
ies s .co . p ies s .co
all m all m
ow ow
ed ed
! !
for ([initializers]; [expression]; [iterators])
{
[body]
When using a for loop, you first initialize a value as a counter. On each loop, you
check
T
that the value of the counter is within the Trange to execute the for loop, and if
his his
do
so, execute do
cu the body of the loop. cu
ma m en ma me
rta t rta nt
.ba be .ba be
lon lon
No rbo gs No rbo gs
un sa to un sa to
The following
au
tho
@code
pri example
Ma
rta
shows how to use a forau loop to
tho
@
pri execute Ma
rta
a code block 10
riz m av B riz m av B
ed era arb ed era arb
times. co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
for Loop
foreach Loop
string[] names = new string[10];
// Process each name in the array.
foreach (string name in names)
{
// Code to execute.
} T Th
his is d
do oc
cu um
ma m en ma en
rta t
be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa to un sa st
@ Ma @ oM
au pri au p art
While Loops tho
riz
ed
m av
era
rta
Ba
tho
riz
ed
rim
av
era
aB
arb
rbo os
co b s sa co bs a.
pie s.c . pie s.c
sa om sa om
A while loop enables llo you to execute
we
a block of code while a given llo
we
condition is true.
d! d!
For example, you can use a while loop to process user input until the user indicates
that they have no more data to enter.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be r ta. tb
.ba lon ba elo
Do Loops
No
un
r bo
sa
gs
to
No
u
rbo
sa
ng
st
oM
au @ M n a @
tho pri art uth pri art
riz m av a Ba o riz m av aB
A do loop is very e d c similar e rab torbaoswhile loop, with the exception e d c thatraa e do aloop
rbo will always
op s a o p bs sa
ies s .co . ies s .co .
execute at least once. all Whereas
ow
m if the condition is not initially met, all
ow a while
m loop will
ed ed
! !
never execute. For example, you can use a do loop if you know that this code will
only execute in response to a user request to enter data. In this scenario, you know
that the application will need to process at least one piece of data, and can therefore
use a do loop.
do Loop
T Th
his is d
do oc
cu um
ma me ma en
rta nt r tb
.ba b elo t a.b elo
No rbo ng N arb ng
sa s to o o sa st
do unau @
p M a
un
au @
p
oM
art
tho rim rta tho rim aB
riz av B arb r i z a v arb
{ ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
// Processs athe llo
om
data. sa
llo
om
we we
d! d!
moreDataToEnter = CheckIfUserHasMoreData();
} while (moreDataToEnter);
Additional Reading: For more information about loops, see the Iteration
Th Th
Statements
is d
oc (C# Reference) page at http://go.microsoft.com/fwlink/?
is d
oc
um um
mLinkID=267778.
ar ent m ar en
ta. be t ta. be
ba lon ba lon
No rbo gs No rbo gs
u na s a@ to un sa to
uth Ma au @ Ma
pri rta th pri rta
ori m a Ba ori ma Ba
ze ve rbo zed ve rbo
dc rab rab
Creating and Using Arrays op
ies ss.
co
sa
.
co
p ies ss.
c om
sa
.
all m all
ow ow
ed ed
! !
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t r ta. tb
.ba lon ba elo
No r bo gs No rbo ng
un sa to u sa st
@ M n @ oM
au pri art auth pri art
tho m a o m aB
riz av Ba riz av ar
ed era r e d e
An array is a set co of objects
pie bs
s.c
bthat
os are grouped together and cmanaged
a. op
ra bs asboasaunit. You
s
sa ies .co .
o
can think of an array lloas a msequence of elements, all of which are all
o the m
same type. You
we we
d! d!
can build simple arrays that have one dimension (a list), two dimensions (a table),
three dimensions (a cube), and so on. Arrays in Visual C# have the following
features:
• Every element in the array contains a value.
• Arrays are zero-indexed, that is, the first item in the array is element 0.
• The size of an array is the total number of elements that it can contain.
Creating Arrays
When you declare an array, you specify the type of data that it contains and a name
Th Th
for theis array.
do
cu
is d
Declaring an array brings the array intooc scope, but does not actually
u
m me m me
art any nmemory
allocate tb art
for it. The CLR physically creates nthe
t b array when you use the
a.b el a.b el
arb on arb on
N os st g o st N g
new okeyword.
un
a a@At this ou
o Mpoint, you should specify the nasize sof
a@the array.
oM
uth pri art uth pri art
ori mav aB ori ma aB
ze era arb z ed ve arb
dc bs os co rab os
op s.c a. p ss. a.
ies ies c
The following list describes
all
ow
om how to create single-dimensional, multidimensional,
all
ow
o m and
ed ed
jagged arrays: ! !
• Multidimensional arrays. An array can have more than one dimension. The
number of dimensions corresponds to the number of indexes that are used to
identify an individual element in the array. You can specify up to 32 dimensions,
but you will rarely need more than three. You declare a multidimensional array
variable just as you declare a single-dimensional array, but you separate the
dimensions by using commas. The following code example shows how to create
an array of integers with three dimensions.
Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a tb
. e . elo
int[ba,rb , ]lonarrayName
N g = new int[10,10,10];
N
ba
rb ng
ou os st o un o sa st
na a@ oM @ oM
uth pri art au p art
ori ma aB t h ori r i ma aB
ze ve arb z ed v era arb
dc rab o co bs os
op s s sa p s a.
ies .co . ies .co
• Jagged arrays. Aallojagged we
m array is simply an array of arrays, aand llo the
we
m size of each
d! d!
array can vary. Jagged arrays are useful for modeling sparse data structures
where you might not always want to allocate memory for every item if it is not
going to be used. The following code example shows how to declare and initialize
a jagged array. Note that you must specify the size of the first array, but you must
not
T
specify the size of the arrays that are contained
T
within this array. You allocate
his his
do
memory do
cu to each array within a jagged array separately,
cu by using the new keyword.
ma m en m ma en
rta tbe rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s t u s st
a@ o Ma na a@ oM
au p u p art
int[][] tho rim
jaggedArray rta = new int[10][]; tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s s co different b s os
jaggedArray[0] pie = s.cnew Type[5];
a . // Can specify pie s.c sizes.
a.
sa om sa om
ll llo
jaggedArray[1]ow= ed new Type[7]; we
d!
!
...
jaggedArray[9] = new Type[21];
Th Th
is d is d
oc oc
um um
Accessing
ma
rta
en Data in an Array
tb
ma
r ta.
en
tb
.ba elo b elo
No r bo ngs No a rbo ng
un sa to u sa st
You canauaccess @ data Min an array in several ways, such
n as@ by oM
specifying the index of a
pri art auth pri art
tho m a o m aB
riz av B r i a
specific element ed
co thatrayou
e
bs
arb
require
os or by iterating throughzethe d c entire
op
ve arb
rab collection os and
pie s.c a. i ss . a.
sa e sa c
returning each element llo
we
inomsequence. llo
we
om
d! d!
The following code example uses an index to access the element at index two.
Accessing Data by Index
int[] oldNumbers = { 1, 2, 3, 4, 5 };
int number = oldNumbers[2];
Th Th
is d is d
oc oc
um um
ma
Note:
rta
.ba
en
Arrays
tb
elo are zero-indexed, so the firstmelement art
a.b
en
t bin any dimension in an
elo
No arrayrbois at index ng arb ng
un sa s to zero. The last element inN a
o dimension
un o sa is
s t at index N-1, where
oM
au @ M au @
N isthothe p
sizerim of the a rta dimension. If you attempt to thoaccess p art
rim an element outside
riz av B r a aB
ed era arb i z ed v era arb
this range, co the CLR
p bs
s
throws
os
a. an IndexOutOfRangeException co
p bs exception.
s
os
a.
ies .co ies .co
all m all m
ow ow
ed ed
! !
You can iterate through an array by using a for loop. You can use the Length
property of the array to determine when to stop the loop.
The Tfollowing code example shows how to use Ta for loop to iterate through an array.
his his
do do
cu um c
ma me ma en
rta nt rta tb
Iterating .baOverbean
lon Array .ba elo
No r bo gs No rbo ng
u sa to un s st
na @ Ma a@ oM
uth pri au p art
ori m rta tho rim aB
ze av Ba riz av arb
dc era rbo ed era
op sa bs co b s os
ies . s.c pie s.c a.
a om sa om
int[] oldNumbersllow= { 1, 2, 3, 4, 5 }; llo
we
ed d!
!
for (int i = 0; i < oldNumbers.Length; i++)
{
int number = oldNumbers[i];
...
} T Th
his is d
do oc
cu um
ma me ma en
rta n tb r tb
.ba elo ta. elo
n b a ng
No r bo gs No rbo st
u sa to u sa osee
Additional
n au @
pri Reading:
M art For more information about
n auth arrays,
@
pri Ma the Arrays (C#
tho m a o m rta
Programming r ize a ve Guide) B a page at r
http://go.microsoft.com/fwlink/?
i z a v Ba
dc rab rbo e dc e rab rbo
op ss. s a. op ss. sa
LinkID=267779. ies
all
co
m
ies
all
co
m
.
ow ow
ed ed
! !
Referencing Namespaces
Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
The Microsoft
au
tho
@ .NET
prim Framework
M a rta consists of many namespaces
au
tho
@
p rim that art organize its
riz av B r a aB
ed erarelated arb i z ed v era arb
classes into logically co bs o hierarchies.
sa You can use namespaces
co bs in your os
a.
own
pie s.c . pie s.c
sa om sa om
applications to similarly llo
we organize your classes into hierarchies. lowe
l
d! d!
Namespaces function as both an internal system for organizing your application and
as an external way to avoid name clashes between your code and other applications.
Each namespace contains types that you can use in your program, such as classes,
structures,
Th enumerations, delegates, and interfaces.
Th Because different classes can
is d is d
have theocsame
um
oc
name, you use namespaces to differentiate
um the same named class
ma en ma en
r t r t
into Ntwota.different
ba
rb
be
g N
ta.
lonhierarchies to avoid interoperability
rb
be
baissues.lon
g
ou os st ou os st
na a@ oM na a@ oM
uth pri art uth pri art
ori mav aB ori ma aB
ze era arb zed ve arb
.NET Framework
op
i
bClass
ss. osLibrary Namespaces
a.
dc co
p ies
rab
ss. os
a.
es co com
all m all
ow ow
ed ed
The most important namespace
! in the .NET Framework is the System
! namespace,
which contains the classes that most applications use to interact with the operating
system. A few of the namespaces provided by the .NET Framework through the
System namespace are listed in the following table:
Th Th
is d is d
oc
Namespace Definition oc
um um
ma en ma en
rta be t r ta. tb
.ba lon ba elo
N r b g N rb ng
ou
System.Windows o sa s to Provides the classes that are o uuseful for o sa building s t WPF applications.
na @ M n @ oM
uth pri art auth pri art
ori ma aB ori ma aB
System.IO z e v e a
Provides
rbo z e
classes for reading and writingd cdata to rfiles. v e arb
dc rab a bs os
op s s sa o p s a.
ies .co . ies .co
all m all m
System.Data ow ow
ed Provides classes for data access. ed
! !
System.Web Provides classes that are useful for building web applications.
User-Defined Namespaces
User-defined namespaces are namespaces defined in your code. It is good practice
to define all your classes in namespaces. The Visual Studio environment follows this
recommendation by using the name of your project as the top-level namespace in a
project.
The following code example shows how to define a namespace with the name
Th Th
sd i sd i
FourthCoffee.Console,
oc
u
which contains the Program
oc class.
u
ma me ma me
rta nt rta nt
.ba be .ba be
lon lon
No rbo gs No rbo gs
u s to un sa to
Definingna a Namespace
uth
a@
pri Ma au @
pri Ma
ori ma rta tho m rta
ze ve Ba riz av Ba
dc rab rbo ed era rbo
op s sa co b s sa
ies s .co . pie s.c .
all m sa om
ow llo
ed we
! d!
namespace FourthCoffee.Console
{
class Program
{
static void Main(string[] args)
Th Th
is d is d
oc{ oc
um um
ma e ma en
rta } nt be rta tb
elo
.ba lon .ba
No rbo gs No rbo ng
s to s st
}unau a@
pri Ma un
au a@
p
oM
art
tho m rta tho rim aB
riz av Ba riz av arb
} ed
co
era rbo ed
co
era
os
pie b ss. sa pie b s a.
co . s.c
sa m sa om
llo llo
we we
d! d!
When you create a Visual C# project in Visual Studio, the most common base class
assemblies are already referenced. However, if you need to use a type that is in an
assembly that is not already referenced in your project, you will need to add a
reference to the assembly by using the Add Reference dialog box. Then at the top of
yourTcode
his
d file, you list the namespaces that youThuse
is d in that file, prefixed with the
oc oc
me u u
using
ma directive.
nt mathat minstructs
The using directive is a shortcut en your application that
rt b
a.b rt tb a.b
elo elo
arb ng arb ng
the Ntypes
ou inothe
sa namespace
st
o
can be referenced Ndirectly,
ou oswithout
a
s t using the fully
o
na @ Ma na @ Ma
uth
pri rta uth pri rta
qualified name.
o riz
ed
ma
ve Ba ori
zed
ma
ve Ba
rab rbo rab rbo
co ss. sa co ss. sa
pie c . p ies c .
sa om all om
llo ow
we ed
The following code example d! shows how to import the System namespace
! and use
the Console class.
Importing a Namespace
using System;
…
Console.WriteLine("Hello, World");
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s t u s st
a@ o Ma na a@ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
Debugging is an co essential
pie b s s.c part s a . of application development. co You may
pie b ss.c notice
os
a. errors as
sa om sa om
llo llo
you write code, but some we
d!
errors, especially logic errors, may only weoccur in
d!
circumstances that you do not predict. Users may report these errors to you and you
will have to correct them.
Visual Studio 2012 provides several tools to help you debug code. You might use
these
Th while you develop code, during a test phase,
is
Th
is or after the application has been
do do
cu cu
released.
ma You
me will use the tools in the same waymregardless
n a
me
n
of the circumstances.
rta tb rta tb
.ba elo .ba elo
No rbongs No rbo ng
un sa to u sa st
@ M n @ oM
au auth
You can run tho anpapplication art with or without debugging enabled. pri art
av When a B debugging is
rim a o m
riz av Ba riz ar
ed era rbo e d e r
co
enabled, your application bs coaccess a bs the bnumerous
os
pie s.c is said
sa
. to be in Debug mode. To p ies s .co a.
sa om a m
llo llo
debug functions, including we
d! the ability to step through code line by weline, you can use
d!
the items on the Debug menu, the buttons on the Debug toolbar, or keyboard
shortcuts.
Debug Controls
The following table lists the key items on the Debug menu and the Debug toolbar,
and the corresponding keyboard shortcuts.
For more information about debugging, see the Debugging in Visual Studio page at
http://go.microsoft.com/fwlink/?LinkID=267781.
Demonstration:
Th
is d
Developing the Class
Th
is d
Enrollment
Application
ma
oc
um
en
Lab ma
oc
um
en
rta tb rta tb
.ba elo .ba elo
No rbo ng No gs rbo n
In thisudemonstration, st
na sa
@ o M you will learn about the tasks
un thatsayou
@ will
to perform in the lab for
M
uth pri art a uth pri art
ori ma aB ori ma aB
this module. ze
dc
ve
rab arb zed ve
rab arb
op s os co ss. os
ies s .co a. p ies a.
com
all m all
ow ow
ed e
Lab: Developing the Class Enrollment Application
d! !
Scenario
You Tare a Visual C# developer working for a software
T
development company that is
his his
do
writing applications for The School of Fine Arts, andoelementary school for gifted
cu cu
ma m en m ma en
rta t rta tb
children. .ba be
lon .ba elo
ng
No rbo gs No rbo st
un s a t o u na s a oM
au @ Ma u @
tho prim rta tho p rim art
riz av B riz av aB
e e a e e arb
The school administrators
d co rab
s
require
rb os an application that theyccan d
o
use
rab to enroll
s os students
pie s.c a . pie s.c a.
sa om sa om
in a class. The application llo
we
must enable an administrator to addlloand we
remove students
d! d!
from classes, as well as to update the details of students.
You have been asked to write the code that implements the business logic for the
application.
Th Th
is d is d
oc oc
um um
mNote:
art eDuring
nt the labs for the first two modules ma inethis
nt course, you will write
a.b be r ta. be
No code arbfor this ng class enrollment application.N
l o b arb l o ng
un os st ou os st
a @ oM n a @ oM
au pri art auth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e ra
co bs sa co bs os
pie s.c . p ies s .co a.
sa om
When The School oflloFine we
Arts ask you to extend the application all functionality,
ow
m you
d! ed
!
realize that you will need to test proof of concept and obtain client feedback before
writing the final application, so in the lab for Module 3, you will begin developing a
prototype application and continue with this until then end of Module 8.
In the lab for Module 9, after gaining signoff for the final application, you will develop
the user interface for the production version of the application, which you will work on
for the remainder of the course.
Objectives
AfterThcompleting
is this lab, you will be able to: Th
is d
do oc
cu um
ma me ma en
rta nt rta tb
.ba be .ba elo
lon ngto edit the details of a
• Write
No u Visual
r b os C#
a
gscode that implements
to the logic
N o u necessary
rb os
a@
st
oM
na @ Ma na
uth pri rta uth pri art
student.oriz ma
ve Ba ori
ze
ma
ve
aB
arb
ed rab rbo dc rab
co s sa op s os
pie s.c . ies s .co a.
sa om m
• Write Visual C# code llo
we that implements the logic necessary toalloadd we new students.
d! d!
• Write Visual C# code that implements the logic necessary to remove students from
a class.
• Password: Pa$$w0rd
Th Th
Exercise
is d
o
1: Implementing Edit Functionality
is d
o
for the Students List
cu cu
ma me ma me
rta nt rta nt
.ba be .ba be
lon lon
No rbo gs No rbo gs
u
na s a@ to un s a@ to
Ma au Ma
Scenario uth
ori
pri
ma rta tho
riz
pri
ma rta
ze ve Ba ed ve Ba
dc rab rbo rab rbo
op ss. sa co ss. sa
i e . pie .
In this exercise, you s a will write
llo
c om the code that enables an administrator sa
llo
c omusing the
we we
application to edit a student’s d! details. d!
A list of students is displayed in the user interface of the application. When the user
selects a student and then presses a key on the keyboard, you will check whether the
key they pressed was Enter.
If they did press Enter, you will write code to display the student’s details in a
separate form, which the user can use to modify the details.
Th Th
is d is d
oc oc
um um
ma en ma en
r t r tb
When the t a.b userecloses
arb
b
lon the form, you will copy the updated
t a. ba edetails
lon back to the list box
No o g s N o rb o gs
sa sa
un
displaying au the @list oftostudents.
Ma un
au @ to
Ma
tho pri r t t h pri rta
riz m av a Ba oriz m av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
Finally, you will run the llo application to verify that your code functions
we
llo
we
as expected, and
d! d!
then use the debugging tools to examine code as it runs.
4. Run the application and verify that the edit functionality works as expected
Th Th
is d is d
oc oc
um me u
Taskm1:
ar Detect
en
t
whether the user has pressedmthe
ar Enter
nt key
ta. be ta. be
ba lon ba lon
No rbo gs No rbo gs
u
na s a@ t oM un s a@ to
uth pri art auth pri Ma
ori ma aB ori ma rta
Ba
1. Start thed MSL-TMG1
z e
co
v e rab a rvirtual
bo machine if it is not already z e d c running.
v e rab rbo
pie ss. s a. op ss. sa
sa c i e sa c .
om om
llo llo
2. Start the 20483A-SEA-DEV11-01 we virtual machine and log on we as Student with
d! d!
3. Start Visual Studio and from the E:\Labfiles\Starter\Exercise 1 folder, and then
open the School.sln solution.
5. In this method, add a switch statement to detect whether the user has pressed
ThEnter. Th
is d is d
oc oc
um um
ma en ma en
rta tb r t a.b tb
.ba elo elo
rbNote: ng arb ng
No
un o sa The
s to second argument passedN to
o un this o method
sa s t is a KeyEventArgs
oM
au @ M au @
thoobject primnamed a rta e. This object has a Key property tho p rwhich
im areturns
rta the
riz av B arb r i z a v Ba
ed era ed era r b
keyboard
co
pie key
bs associated
s.c
os
a. with the event. You can co use bthis
pie ss. inoconjunction
sa
.
sa om sa c om
with the Key llo
we
enumeration to determine which key initiated
llo
we
the KeyDown
d! d!
event.
6. If the user has pressed Enter, store the selected student in a Student object
variable.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be rta t
.ba Note: lon Later in this lab, you will be adding .bacodebeto lon detect whether the
No rbo gs No rbo gs
un s a@ presses to unso a switch s a@ to
au user pri M art the Insert or Delete keys, a uth pri statement
Ma is
tho m a o m rta
rrecommended.
ize a ve B arb r ize a ve B arb
dc rab os dc rab os
op s s.c a . o pie ss.c a.
ies o s o
all m all m
ow ow
ed ed
! !
Task 2: Initialize the StudentForm window and populate it with the details of the
currently selected student
Th Th
is d is d
oc oc
um um
ma en ma en
rta t r a.bnewt binstance
1. If the
.ba user be has pressed the Enter key, create ta
lon arb
elo
ng
of the
No rbo gs No o s
un s a@ t owindow un s t oM
StudentForm
au pri Ma au ofa@
and set the Title property the
pri window art to Edit Student
tho m rta tho m aB
riz av B arb r i ze a ve arb
Details.ed co era
bs os d co ra bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
2. Populate the following d! text boxes on the form with the corresponding d! properties
of the current student:
a. firstName
b. lastName
c. dateOfBirth
3. Display the date of birth by using the standard short date format without the
time element by using the “d” format specifier.
Th Th
is d is d
oc oc
um um
ma en
Note: To store data in a text box in amwindow,
art en set the Text property of
rta tb a.b tb
.ba elo elo
rbthe n arb ng
No
u os texts box.
g
t oM
N o u o s st
oM
na a@ na a@
uth pri art uth pri art
ori mav aB ori ma aB
ze era arb zed ve arb
dc bs os co rab os
op s.c a. p ss. a.
ies om ies c om
all all
ow ow
ed ed
! !
Task 3: Display the StudentForm window and copy the updated student details
entered back to the Student object
Th his T
1. At
is dthe end of the case Key.Enter block, display
o do the StudentForm window by
cu cu
musing me me
art nt ShowDialog method of the form.mar
the nt
a.b be ta. be
a lon ba lon
No rbo gs No rbo gs
un s a@ to un s a@ to
a M a pri theMupdated
2. If the uth userprclicks
ori im
aOK
r ta in the StudentForm window,uth
ori copy m
art
aB student
ze av B a z av a
dc er rbo ed era rbo
details from op theaStudentForm
bs
s.c sa
.
window back to the Student co
pie bobject.
ss. sa
.
ies om sa co
all llo m
ow we
ed d!
!
Note: You can detect whether the user clicked the OK button by
examining the return value of the ShowDialog method. If the Value
property is true, the user clicked OK, otherwise they clicked Cancel.
Th Th
is d is d
oc oc
um um
ma Note:
en
tb
You can use the DateTime.Parse ma method en
tb
to convert the date of
rta r ta.
.ba birthelostring from the text box to a DateTime b elo
arb type.ng
No rbo ng N
u sa s to o ou s sa to
na @ Ma na @ Ma
uth pri rta uth pri rta
ori mav Ba ori ma Ba
ze era rbo zed ve rbo
dc bs co rab
op s.c sa p ss. sa
ies . ies c .
om
all OK, also enable the Save Changes button
all om
3. If the user clicks ow ow in the user
ed ed
! !
interface.
Note: To enable an item in a user interface, set the IsEnabled property
of the item to true.
Th Th
is d is d
Task 4: Run
o cu the application and verify that the edit oc functionality works
um as
ma me m en
expected
rta
.ba
nt
b elo
art
a.b tb
elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r i z a v arb
ed era ed era
1. Build the solution
co
pie bs and
s.c
resolve
o sa any compilation errors. co
pie bs
s.c
os
a.
sa . sa
om om
llo llo
we w
2. Run the application d! and verify that it displays the initial list ofedstudents. !
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ Ma a@ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
llo m llo
we we
d! d!
3. Edit the row for Kevin Liu and verify that the Edit Student Details window
Th Th
is d is d
appears
oc
u
and displays the correct details: um
oc
ma me ma en
rta nt rta tb
.b be .ba elo
lon
NoThe aEdit
rbo Student
gs Details window shouldNlook
ou similar
rb o to
ng the following:
st
un s a@ to na sa oM
au M uth @
tho pri art pri art
riz ma aB ori ma aB
ed ve arb ze ve arb
co ra bs os dc rab os
pie s.c a. op ss a.
sa om ies .co
llo all m
we ow
d! ed
!
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be rta tb
.ba lon .ba elo
NoFIGURE rbo 01.2: gs EDIT STUDENT DETAILS FORM
N rb ng
un sa to ou os st
@ Ma na a@ oM
au pri uth pri art
tho m rta ori ma aB
riz av Ba ze ve arb
ed era rbo dc rab
4. Change the co last bname
pie s s.c ofsa Kevin
.
Liu to Cook and verify op that the
ies ss .co
updated
os
a. data is
sa om all m
copied back to othe l l we students list. ow
ed
d! !
Th Th
is d is d
oc oc
um um
ma en ma en
rta t be rta tb
. . elo
Task
No 5: Use
b a rbo the l o nVisual
gs Studio Debugger to step
No through
b a rbo ngthe code.
un s t u s st
a@ o Ma na a@ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s s co b s os
pie s a pie insert a.
s.c a breakpoint
1. In Visual Studio, s a in.cthe om studentsList_KeyDown method,
. sa om at
llo llo
we we
the statement that d!sets the Title property of the StudentForm. d!
o sf.dateOfBirth.Text
Note: When Visual Studio enters break mode, the Watch window
automatically appears in the tab group in the bottom left window.
8. In the Immediate Window, enter sf.lastName.Text and verify that the value
Th"Li" is displayed. Th
is d is d
oc oc
um um
ma en ma en
9. Enterrta
.ba
codet be to change the sf.lastName.Text rvalue ta. to
t b "Dubicki", and then verify
elo
lon ba ng
No rbo gs No rbo st
that
un value
au
s a @ changes
t o Ma
in the Watch 1 window. u na s a @ oM
tho prim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
10. Continue cdebugging op bs and s verify that the following co
information b s is os
displayed in the
ies s.c a . pie s.c a.
all o m s all o m
Edit Student Details ow ow
ed form: ed
! !
Field Value
FirstTName
h DominikTh
is d is d
oc oc
um um
Last m
Name
ar en
t Dubicki mar en
tb
ta. be ta. elo
ba lon ba ng
No rbo gs No rbo st
Date ofunBirth s a@ to 8/10/2005una sa oM
au Ma uth @
tho pri rta pri art
riz ma Ba ori ma aB
ed ve rbo zed ve arb
co rab co rab os
pie ss. sa p ss. a.
sa c . ies c
om all om
11. Stop debugging llo the application.
we ow
ed
d! !
12. In Visual Studio, on the Debug menu, click Delete All Breakpoints, and then
close the solution.
Results: After completing this exercise, users will be able to edit the details of a
student.
A list of students is displayed in the user interface of the application. When the user
presses a key on the keyboard, you will check whether the key they pressed was
Insert.
Th Th
If theyisdid is d
do press Insert, you will write code to display
c oc a form in which the user can
um um
ma en ma en
enter the
rta details
.ba
t be of a new student, including their first
lon
rta name,
.ba
tb
elo last name, and date of
No rbo gs No rbo ng
st
birth. una sa
@ t o Ma u na s a@ oM
uth pri r t u t h p r i art
ori m av a B ori m av aB
ze era a rbo z ed era arb
dc bs co b os
op s.c s a pie ss.c a.
ies .
When the user closes all themform, you will add the new student to
ow
o s all the list
ow
o m of students
ed ed
and display the details in the list box. ! !
Finally, you will run the application to verify that your code functions as expected.
4. Assign the new student to a class and enable the user to save the details of the
new student
5. Run the application and verify that the insert functionality works as expected
Task 1: Add logic to the key down method to detect if the Insert key has been
pressed.
Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a.b tb
.ba elo elo
rbo Studio, ng arb ng
1. NoIn Visual
un sa s to from the E:\Labfiles\Starter\Exercise
N o un o sa s2t folder, open
oM
the
au @ M au @
tho prim a r t h p r art
School.sln riz
ed
solution.
av
taB
arb
ori
z ed
i ma
v
aB
arb
era era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
2. In the code for the l l ow MainWindow.xaml.cs window, locate the
ed
l l ow
ed
! !
studentsList_KeyDown method.
3. In this method, add a statement to detect whether the user has pressed Insert.
Th Th
is d is d
oc oc
um um
Taskm2:
ar Initialize
en
t the student form ma
rta
en
tb
ta. be .ba elo
ba lon ng
No rbo gs No rbo st
una s a@ to un s a oM
uth Ma au @
pri rta tho p rim art
ori m a Ba riz av aB
1. If the user ze v
d c haserpressed
a b
rbo Insert, create a new instance ed of the
co
era StudentForm
b
arb
os
op ss. sa pie ss.c a.
ies co . sa
window. all m om
ow llo
ed we
! d!
2. Set the Title property of the window to New Student for Class appended to the
Class property of the teacher object.
2. If the user clicks the OK button in the StudentForm window, create a new
Th
student
is d object and copy the student detailsThifrom
sd the StudentForm window to
oc oc
um um
mthe
art new en student object. ma en
a.b tb rta tb
elo .ba elo
No arb ng No rbo ng
un o sa st un sa st
@ oM @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
Task 4: Assign the new we student
d!
to a class and enable the user we to save
d!
the
details of the new student
1. If the user clicks the OK button in the StudentForm window, use the
Students.Add method of the current teacher to assign the new student to a
Th Th
class.
is d is d
oc oc
um um
ma en ma en
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ a oM
au Note: pri YouMcan art use the this.Teacher property
au @top access art the current
tho m aB tho rim aB
riz av riz av
teacher.
ed
co
era arb
os
ed
co
era arb
os
pie b s a. pie b s a.
s.c s.c
sa om sa om
llo llo
we we
d! d!
2. Add the new student object to the list of students displayed on the form.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be application and verify that the tinsertr tb
Task 5: .Run
ba
r
thelon a.b
a r
functionality
elo
ng
works as
No bo gs No bo s
expected
un s a@ t oM un s a@ t oM
au pri art au pri art
tho m a tho m aB
riz av Ba riz av arb
ed era rbo e d e ra
co bs sa co bs os
pie s.c . p ies s .co a.
sa om a m
1. Build the solution llo and resolve any compilation errors. llo
we we
d! d!
2. Run the application and verify that it displays the initial list of students.
3. Display the new student window and verify that it contains no data.
4. Insert the details for Darren Parker, date of birth is 02/03/2006, and verify that
the new student is added to the students list.
Note: The ID of any new student will be 0 until they are saved to the
database.
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba l n Save Changes button .ba elo
5. NoVerify rbothat othe gs is now
No enabled.
rbo ng
st
un sa to un sa oM
au @ Ma au @
tho pri rta tho p rim art
m aB
6. Closerithe dc
av
ze application.e rab
Ba
rbo
riz
ed
co
av
era
bs
arb
os
op s s sa pie s.c a.
ies .co . sa
all m om
o llo
7. In Visual Studio,wclose ed
! the solution. we
d!
Results: After completing this exercise, users will be able to add new students to
a class.
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ a oM
Exercise 3: Implementing Delete Functionality for the Students List
au
tho pri
m
Ma
rta
au
tho
@
p rim art
aB
riz av Ba riz av arb
ed era rbo ed era
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
llo m llo
we we
d! d!
Scenario
In this exercise, you will write code that enables an administrator to remove a student
from the students list.
A listThof
is students is displayed in the user interface
Th of the application. If the user
is
do do
um c um c
selects
ma a student
en and then presses a key on themkeyboard,
a en you will check whether the
rta tb rta tb
.ba elo .ba elo
key Nthey
ou pressed
r b o sa
n gwas
s Delete. N ou rb o sa
ng
st
na @ to n @ oM
uth pri M art auth pri art
ori ma aB ori ma aB
ze ve a rbo z e v e arb
dc rab dc rab os
If they did pressopDelete, s s you swill
a write code to prompt the o
userp to confirm
ss athat they
ies .co . ies .co .
all m all m
ow ow
want to remove the selected ed
!
student from the class. ed
!
If they do, the student will be deleted from the students list for the appropriate class,
otherwise nothing changes.
Finally, you will run the application to verify that your code functions as expected.
1. Add logic to the key down method to detect if the Delete key has been pressed.
Th T
hisremove the selected student from
2. Prompt
is d
o
the user to confirm that they want to do
cu cu
mthe me ma me
art class nt
b r t
nt
be
a.b elo a.b lon
No a rbo ng N a rb gs
un sa st ou os to
@ o M n a @ Ma
3. au
Remove the
pri student art and enable the user to saveau the pchanges
tho m a t h o r i m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s s a. co b s sa
pie s.c pie s.c .
4. Run the application sa
llo
oand
m verify that the delete functionality s a works
llo
om as expected
we we
d! d!
Task 1: Add logic to the key down method to detect if the Delete key has been
pressed.
Th Th
i i
1. Ins dVisual
oc
u
sd
Studio, from the E:\Labfiles\Starter\Exercise
oc
u
3 folder, open the
ma me ma me
nt nt
School.sln
rta
.b be solution.
lo
rta
.ba be
lon
No a rbo n gs No rbo gs
un s a@ to un s a@ to
au pri M art a uth pri Ma
2. t
In theoricode
h m for the a MainWindow.xaml.cs window, ori find the m rta
ze a ve B arb ze a ve Ba
dc rab o d ra rbo
op ss. sa cop b ss. sa
studentsList_KeyDown ies co . method. i es co .
all m all m
ow ow
ed ed
! !
3. In this method, add a statement to detect whether the user has pressed Delete.
Task 2: Prompt the user to confirm that they want to remove the selected
Th Th
studentis d from the class
o
is d
o
cu cu
ma me ma me
rta nt rta nt
.ba b e .ba be
lon lon
No rbo gs No rbo gs
s t s to
1. Ifunthe
au user
tho
a@
presses
pri
oM
art Delete, find the details ofun
the
a uth
a@
student pri that Ma the user has
rta
riz ma aB ori ma Ba
e ve a z e v e
selectedd and co display
rab
ss.
arbomessage box showing the selected
s a.
dc
op
rastudent’s
b ss.
rbo name.
sa Ask
pie c i e c .
sa om sa om
the user to confirm llo
we that they want to remove the student. llo
we
d! d!
1. If the user confirms that they want to delete the student, delete the current
student object from the schoolContext.Students collection and enable the
Save Changes button in the user interface.
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
st
Task 4:
un Run athe
au
s
@ application
to
Ma and verify that theundelete
au
s a@functionality
oM works as
tho pri rta tho p rim art
expected rize m av Ba riz av a Ba
dc era rbo ed era rbo
op b ss. sa co b ss. sa
ies co . pie co .
all m sa m
ow llo
ed we
! d!
1. Build the solution and resolve any compilation errors.
2. Run the application and verify that it displays the initial list of students.
You will write code in the AgeConverter class that is linked to the grid column
displaying student ages. In this class, you will write code to work out the difference
between the current date and the date of birth of the student, and then convert this
value into years.
Th Th
is d is d
oc oc
um um
ma en ma en
Then yourta will run
.ba
t be the application to verify that the rAge
lon
ta.
ba
column
tb
elo now displays age in
No rbo gs No rbo ng
st
years uinstead
na sa of thetodate of birth.
@ Ma un
au
sa
@ oM
uth pri r t t h p r i art
ori m av a B ori m av aB
ze era a rbo z ed era arb
dc bs co b os
op s.c s a pie ss.c a.
ies .
The main tasks for athis llo exercise
o m are as follows: s a llo
o m
we we
d! d!
2. Add logic to the AgeConverter class to calculate a student’s age from their date
of birth
Th Th
is d is d
oc oc
3. m
Run uthe
me application and verify that the student’s
m
age
um
e
now appears correctly
art nt art nt
a.b be a.b be
arb lon a lon
No o gs No rbo gs
un s a@ to un sa to
au Ma au @ Ma
tho pri rta th pri rta
riz ma Ba ori ma Ba
e ve zed ve
Task 1: Examine dc
op
the rabMainWindow
ss.
rbo
sa XAML co rab
ss.
rbo
sa
ies co . p ies c .
all m all om
ow ow
ed ed
! !
1. In Visual Studio, open the School.sln solution from the
E:\Labfiles\Starter\Exercise 4 folder.
2. Build the solution.
4. Note how the Age column in the GridView uses databinding with a value
converter (AgeConverter).
Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba lon .ba elo
No rbo gs No rbo ng
st
Task 2:un Addsalogic
au @ to
to the AgeConverter
Ma class toun calculate
au
sa
@ a ostudent’s
Ma age from
tho pri rta tho p rim rta
their date of m
riz birthav Ba riz av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!
1. In the code for the MainWindow.xaml.cs window, find the Convert method in
the AgeConverter class.
2. In this method, add code that checks that the value parameter of the method
contains data. If it does not, return an empty string.
Th Th
is d is d
oc oc
3. mIfa the mvalue
u
en
parameter is not null, convert the ma value
um
en
parameter to a DateTime
rta t b r t a tb
.ba elo .ba elo
Noobject. rbo ng
s No rbo ng
st
un s a t o u na s a oM
au @ Ma u @
tho prim rta tho p rim art
riz avdifference B rizand the aB
av student’s
4. Calculate ed the era a rbo between the current date ed era arb date of
os
co b s s a co b s a.
pie s.c . pie s.c
birth, and thenallconvert s o m the result into a number of years. all s o m
ow ow
ed ed
! !
5. Convert the number of years into a string and return it to the calling method.
Task 3: Run the application and verify that the student’s age now appears
correctly
Th Th
is d is d
oc oc
um um
ma en ma en
rta tbe rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ Ma a@ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
FIGURE 01.4: c op
ies
THE b ss. STUDENT sa
.
LIST DISPLAYING THEIR co
pie AGES.
b ss.c
os
a.
co sa om
all m llo
ow we
ed d!
!
3. Add yourself as a student and verify that your age displays correctly in the
student list.
Console application
Statement Answer
When using the as operator to perform a cast, if the cast is not possible, the as operator will
return a -1. Is this statement true or false?
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be rta tb
.ba lon .ba elo
N r b gs No rbo ng
Test Your
ou
na
Knowledge
o s a@ to un sa st
oM
uth Ma au @
pri rta tho pri art
ori ma Ba riz m av aB
ze ve rbo ed era arb
dc rab co bs os
op ss. sa pie s.c a.
ies co . sa
m om
Question all
ow llo
we
ed d!
!
Question
Given the following for loop statement, what is the value of the count variable once the loop has
finished executing? var count = 0; for (int i = 5; i < 12; i++) { count++;
}
11
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un s to un s st
a@ Ma a@ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
llo m llo
we we
d! d!
Th Th
is d is d
oc oc
um um
ma en ma en
rta t
be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
u s to un sa st
na a@ Ma @ oM
uth pri au pri art
ori ma rta tho m aB
ze ve Ba riz av arb
dc rab rbo ed era
op ss. sa co bs os
ies . pie s.c a.
co sa om
all m llo
ow we
ed d!
!
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
Contents:
is
do
cu
is
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho Module pri tho p rim art
av Overview
m rta aB
riz Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
Lesson 1: Creating llo and Invoking
we
Methods llo
we
d! d!
Lesson
Th
is 4: Monitoring Applications Th
is
do d oc
cum um
ma e nt ma en
Lab: rta Extending the Class Enrollment Application rt tb
.ba be
lon a.b elo Functionality
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho Module rim t r
av Review and Takeaways
r taB h ori im aB
riz a z av arb
ed era rbo ed era
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Module Overview
In this module, you will learn how to create and use methods and how to handle
exceptions. You will also learn how to use logging and tracing to record the details of
any exceptions that occur.
hisT Th
Objectives
do
c
is
d oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/50
10/25/2019 20483A - Programming in C# | Skillpipe
• Handle
Th exceptions. Th
is is
do oc d
c um um
ma e ma en
• Monitor
rta
.
applications
nt
be by using logging, tracing, and
rta profiling.
.ba
tb
elo
ba lon ng
No rbo gs No rbo st
un sa to un sa oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
Lesson 1 : Creating and Invoking Methods
sa
llo
we
om sa
llo
we
om
d! d!
A key part of developing any application is dividing the solution into logical
components. In object-oriented languages such as Visual C#, a method is a unit of
code that performs a discrete piece of work.
Th Th
is is
do d oc
c um u
me
In this
malesson,
r nt you will learn how to create and invoke
e ma
r
methods.
nt
ta. be ta. be
ba lon ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ Ma au @ Ma
tho pri rta tho pri rta
Lesson Objectives riz
ed
m av
era Ba
rbo
riz
ed
m av
era Ba
rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
After completing this lesson, l l o you will be able to: llo
we we
d! d!
• Create methods.
Th Th
• Invoke
is
d
methods. is
d
oc oc
um um
ma e nt ma en
rta be rt a.b tb
• Debug
No
.bamethods.
rbo
lon
gs No arb
elo
ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
What Is a Method? llo
we
d!
llo
we
d!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
The ability
au to define
tho
@
prim and
M a rta
call methods is a fundamental au
tho component
@
p rim art of object-oriented
riz av B r a aB
ed because era methods arb ized vera arb
programming, co bs o sa enable you to encapsulate co operationsbs othat
sa protect
pie s.c . pie s.c .
sa om sa om
data that is stored inside llo
we a type.
llo
we
d! d!
Typically, any application that you develop by using the Microsoft .NET Framework
and Visual C# will have many methods, each with a specific purpose. Some methods
are fundamental to the operation of an application. For example, all Visual C#
desktop
Th applications must have a method calledThMain that defines the entry point for
is is
oc d oc d
the application.
um When the user runs a Visual C# application,
um the common language
ma en ma en
ta. r be t ta. be r t
runtime
N
(CLR)
ba
r
executes
lon
g
the Main method for that
N
application.
ba
r
lon
g
ou bo st ou bo st
na sa oM na sa oM
uth @ uth @
pri art pri art
ori m av aB ori m av aB
ze era a rbo zed era arb
Methods can dbe co designed
pie b s s.c
for s internal
a use by a type, and as
c o such
pie b are
s s.c
hidden
os
a. from
sa . sa
om om
other types. Public methods llo
we may be designed to enable other types llo
we to request that
d! d!
an object performs an action, and are exposed outside of the type.
The .NET Framework itself is built from classes that expose methods that you can
call from your applications to interact with the user and the computer.
Th Th
is is
do d oc
c
Creating
ma
rt nMethods
tb
um
e ma
rt
um
en
tb
a.b elo a.b elo
No arb ng No arb ng
un o s st un os st
a @ oM a @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do oc d
um c um
The method
m art e nspecification
t b
defines the name of thearmethod,
m
t
en
t b the parameters that the
a.b elo a.b elo
arbo take,ngthe a ng
rbo accessibility
method
No
un
can sa s to return type of the method,
Noand the
un sa st
oM
of the method.
au @ M au @
tho prim a rta tho p rim a rta
The combination riz
ed
of
av the name Ba of the method and its parameterriz
ed
av list are Ba referred to as
era rbo era rbo
co bs sa co bs sa
the method signature. p ies The
s .co definition of the return value of a imethod
. p es s .cois not . regarded
all m all m
ow ow
as part of the signature. ed Each method in a class must have a unique
!
ed signature.
!
Naming Methods
A method name has the same syntactic restrictions as a variable name. A method
mustT start with a letter or an underscore and can
T only contain letters, underscores,
his his
do do
and numeric
cu
m characters. Visual C# is case sensitive, uso
c
m a class can contain two
ma en ma en
rta be t rta be t
methods .bthat
ar have
lon the same name and differ only in .bathe casing
r
lon of one or more letters
No bo gs No bo gs
un sa to un sa to
—althoughauth this pis
@
r i
not aartgood coding practice.
M a uth @
pri Ma
rta
ori m a aB ori m a Ba
ze ve arb ze ve rbo
dc rab os d co r ab
op s s.c a pie s s.c sa
ies . sa .
a om om
The following guidelines llo
we are recommended best practices when llo you choose
we the
d! d!
name of a method:
• Use verbs or verb phrases to name methods. This helps other developers to
understand the structure of your code.
Th Th
• Useis Pascal
do
cu
is
case. Do not start public method names
do
cu with an underscore or a
m me ma me
art nt nt
lowercase
a.b letter.
be
l
rt a.b be
lon
arb on arb
No o gst No os gs
un sa oM un a@ to
au @ au Ma
tho pri art tho pri rta
riz m av aB riz ma Ba
ed era arb ed ve rbo
co bs os co rab
pie s.c a. pie ss sa
. .
Implementing a Method Body sa
llo
om sa
llo
com
we we
d! d!
The body of a method is a block of code that is implemented by using any of the
available Visual C# programming constructs. The body is enclosed in braces.
You can define variables inside a method body, in which case they exist only while
the method
Th
is is running. When the method finishes,
Th it is no longer in scope.
is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/50
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows the body for the StopService method, which
contains a variable named isServiceRunning. The isServiceRunning variable is
only available inside the StopService code block. If you try to refer to the
isServiceRunning variable outside the scope of the method, the compiler will raise a
compile error with the message The name 'isServiceRunning' does not exist in
the current context.
Th Th
is is
do d oc
cum um
ma nte ma en
Variablerta Method be Scope rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
void StopService() sa om sa om
llo llo
we we
d! d!
{
var isServiceRunning = FourthCoffeeServices.Status;
...
}
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.brt tb
elo
Specifying Parameters
No
.ba
rbo
lon
gs No a rbo ng
st
un sa t o u na s a oM
au @ Ma u @
tho p rim rta tho p rim art
aB
Parametersrizare ed local
av variables
era B a rbo that are created when the
riz method
ed
av
era runs arband are
co b s s c o b s os
pie s.c a . p s.c a.
populated with values s a that omare specified when the method isiecalled. sa All
om methods must
llo llo
we we
d
have a list of parameters. You specify the parameters in parentheses
! d! following the
For each parameter, you specify the type and the name. By convention, parameters
Th Th
is is
are nameddo by using camel case.
c
d oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
s os st
The following
un
au code
a@
pri
texample
oM
art
shows a method thatunaccepts
au a @ an
pri
int
o M parameter
art
and a
tho m a tho m aB
riz av Ba riz av
Boolean parameter. ed
co
era rbo ed
co
era arb
os
pie b ss sa pie bs a.
.c . s.c
sa om sa om
llo llo
we we
d d!
Passing Parameters to! a Method
When defining the parameters that a method accepts, you can also prefix the
parameter definition with the ref keyword. By using the ref keyword, you instruct the
CLRTto d
Th just the value of the parameter.
his pass a reference to the parameter and not
is
d
oc oc
me u meto the parameter inside the u
You must
ma
r
initialize
nt the ref parameter, and any changes
ma
r nt
ta. be ta. be
ba lon ba lon
method
N o u bodyr bos will theng st be reflected in the underlyingN o u variable
r b os gin
s t the calling method.
na a @ o M na a @ oM
uth pri art uth pri art
ori ma aB ori ma aB
ze ve arb zed vera arb
dc rab o co bs os
op s sa
The following code ies example s .co shows how to define a parameter
. p ies by usings .co the
a. ref
all m all m
ow ow
keyword. ed
!
ed
!
Th Th
void is StopAllServices(ref int serviceCount)
d
is
d
oc oc
um um
{ ma ent ma en
rta be a.b rt tb
.ba lon elo
rbo
NserviceCount No a
gs = FourthCoffeeServices.ActiveServiceCount;rbo ng
ou s t u s st
na a @ o Ma na a @ oM
uth pri r t u t h p r i art
} ori m av aB ori m av aB
ze era a rbo zed era arb
dc b c b os
op s s.c s a o pie s s.c a.
ies . s
all o m all o m
ow ow
ed ed
! !
Additional Reading: For more information about the ref keyword, see the ref
(C# Reference) page at http://go.microsoft.com/fwlink/?LinkID=267782.
Specifying
Th a Return Type Th
is is
do d oc
c um u
me
All methods
ma
rt must
nt
b
have a return type. A method mthat
e art doesnt not return a value has the
b
a.b elo a.b elo
arb ng arb ng
voidNoreturn
u otype.
sa You
s t specify the return type before
o
No
u
the osmethod
a
s t name when you
o
na @ Ma na @ Ma
uth pri rtayou declare a method tho u rim p
rta must include a
define a method.
ori
ze
mWhen
ave Ba that returns
riz
e
data,
av you Ba
dc rab rbo dc era rbo
op ss method sa op bs sa
return statement iein
sa the .c om
. block. ies s.c
o
.
llo all m
we ow
d! ed
!
The following code example shows how to return a string from a method.
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/50
10/25/2019 20483A - Programming in C# | Skillpipe
string GetServiceName()
{
return "FourthCoffee.SalesService";
}
Th Th
is
The expression is must have the same type as the
that the return statement specifies
do do
c um c um
ma en ma en
method.rta When
.
t b the return statement runs, this expression
e rta
.
t bis evaluated and passed
e
ba lon ba lon
N b r st g bo N
s t finishes, so any otherr g
un the ostatement
back oto sa
@
o u method
o M that called the method. The n sa then
@ oM
a uth pri art a uth pri art
aB m aB m
statementsorithat
ze
d
occur
av
er after
ori
arba return statement has been ze executed
d
av
er willarbnot run.
co ab os co ab os
pie ss a. pie ss a.
sa .c om sa .co
llo llo m
we we
d! d
Invoking Methods !
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un st
os
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we w
You call a method to run d! the code in that method from part of youredapplication. ! You do
not need to understand how the code in a method works. You may not even have
access to the code, if it is in a class in an assembly for which you do not have the
source, such as the .NET Framework class library.
Th Th
To callisadomethod,
c
is provide any arguments that
you specify the method name anddo
c
um um
ma en ma en
correspond
rta
.
tot bthe
e method parameters in brackets.rta
. elo
tb
ba lon ba ng
No rbo gs No rbo st
un sa to un saoM
au @ Ma au @
tho pri rta tho pri art
r ma Ba shows how riz m av aB
The following i ze codevexample
dc e rab rbo to invoke the StartService
ed era method,
arb
os
passing
op ss sa co bs a.
ies .co . pie s.c
int and Boolean variables all m to satisfy the parameter requirements s a of the
llo
om method’s
ow we
ed d!
signature. !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/50
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to capture the return value of the
GetServiceName method in a variable named serviceName.
Th Th
sd i is
Capturing
oc a Method Return Value
u
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
r m a Ba riz av aB
var serviceName ize ve = GetServiceName(); ed era arb
dc rab rbo os
op s sa co b s a.
ies s.c . pie s.c
string GetServiceName() all om sa om
ow llo
ed we
! d!
{
return "FourthCoffee.SalesService";
}
Th Th
is
Additional Reading: For more information isabout methods, see the Methods
do do
cu cu
m(C# m m
art Programming
en
tb Guide) page at http://go.microsoft.com/fwlink/?
ma
rt
en
tb
a.b elo a.b elo
arb
No LinkID=267774. ng No arb ng
un os st un os st
a @ oM a @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
Debugging Methods llo
we
d!
llo
we
d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c um um
ma nt e ma en
rta b rt
a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
When you au are debugging
tho prim
M a rta your application, you can austep through
tho p rim code
art one statement
riz av B r a aB
ed era arb ized vera arb
at a time. This cis
op an extremely
bs os useful feature because it enables
a co
p byou
s to otest
sa the logic
ies s .co . ies s.co .
a m a m
that your application ouses l l we one step at a time. l l ow
d! ed
!
Visual Studio provides a number of debugging tools that enable you to step through
code in exactly the way you want to. For example, you can step through each line in
each method that is executed, or you can ignore the statements inside a method that
you know
Th are working correctly. You can also step
Th over code completely, preventing
is is
oc d d oc
somem statements
um
e
from executing. ma en
um
art nt rt tb
a.b be a.b elo
a l on a ng
No rbo gs No rbo st
un sa t o u na s a oM
au @ Ma @
When debugging
tho p rim methods, rta you can use the following u tho three p debug
rim artfeatures
aB
to control
riz av B a riz av arb
ed era rbo ed era
whether you step c op over,ssstep into,
b sa
.
or step out of a method: c o pie b s s.c
os
a.
ies .co s o
all m all m
ow ow
ed ed
! !
• The Step Into feature executes the statement at the current execution position. If
the statement is a method call, the current execution position will move to the code
inside the method. After you have stepped into a method you can continue
executing statements inside the method, one line at a time. You can also use the
Step
Th Into button to start an application in debug
is
Th mode. If you do this, the
is
do do
cu cu
application
m me will enter break mode as soon as m
n
it starts.
me
n
art tb art tb
a.b elo a.b elo
No ar bo n gs No a r bo ng
s t s st
• TheunStep
au Over
a @
pri
feature
o M art
executes the statement u at
n a the
uth
current
a @
pri
o execution
Ma position.
tho m a o m rta
However,rizethis av
d c feature era
b
Ba
does
rbo not step into code inside za
ri
edmethod.
c
av Ba
era Instead,
b
rbo the code
op ss sa op ss sa
ies .co . ies .co .
inside the method all executes
ow
m and the executing position moves all to the
ow
m statement
ed ed
after the method call. ! The exception to this is if the code for the method ! or
property contains a breakpoint. If this is the case, execution will continue up to the
breakpoint.
• The Step Out feature enables you to execute the remaining code in a method.
Th
Execution will continue to the statement that Tcalled
his the method, and then pause at
is
d oc d oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/50
10/25/2019 20483A - Programming in C# | Skillpipe
that point.
Additional Reading: For more information about stepping through code, see
the Code Stepping Overview page at http://go.microsoft.com/fwlink/?
LinkID=267783.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
arb ng
Demonstration: Creating, Invoking, and Debugging
No
un
au
rbo
sa
@
gs
to
Ma
No
un
au
os
a @
st
oM
tho pri rta tho p rim art
Methods riz
ed
co
m av
era Ba
rbo
riz
ed
co
av
era
aB
arb
os
pie b s sa pie bs a.
s.c . s.c
sa om sa om
In this demonstration,owyou l l will create a method, invoke the method, l l ow and then debug
ed ed
! !
the method.
Demonstration Steps
Th Th
5. Click
is
do Visual Studio 2012.
is
do
cu cu
ma m en ma me
rta tb r nt
elo t a be
6. In
No
Visual
.ba
rbo Studio,
ng on the File menu, point to
No
Open, .ba and
rbo
lonthen click
gs
un s s t un s to
a@ oM a@
Project/Solution.
a uth pri
ma
art
aB
a uth pri
ma
Ma
rta
ori ori Ba
ze ve a rbo ze ve rbo
dc rab dc rab
op ss sa op ss sa
i . . i . .
7. In the Open Project esa
llo
c odialog
m box, browse to the e sa
llo
com
we we
d!
E:\Democode\Starter\FourthCoffee.MethodTestHarness folder, d! click
10. Double-click the TODO: 01: Define the Initialize method. task.
11. In the code editor, click in the blank line below the comment, and then type the
following code:
bool Initialize()
Th Th
is is
{docu um
d oc
ma me m en
nt
rta var
.ba b path
elo = GetApplicationPath();art a.b tb
elo
No rbo ng N arb ng
un return sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed!string.IsNullOrEmpty(path);
era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
} sa om sa om
llo llo
we we
d! d!
12. In the Task List window, double-click the TODO: 02: Invoke the Initialize
method. task.
13. ThIn the code editor, click in the blank line below
Th the comment, and then type the
is is
do do
following
ma
um
c
en
code: ma
cu
me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
var isInitialized=
riz m av aB Initialize(); ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
14. Right-click the call to the Initialize method, point to Breakpoint, and then click
Insert Breakpoint.
16. ThOnd
Th
is the Debug menu, click Start Debugging.is
d
oc oc
um um
ma e nt ma en
rta be a.b rt tb
17. Press .ba F11 loto step into the Initialize method. elo
No r bo n gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
18. Press riF10 ze
dc
to astep
ve
rab
to Bathe GetApplicationPath method
rbo
riz
e dc
call.
av
e rab arb
op s sa o s os
ies s .co . p ies s.co a.
all m all m
19. Press F10 to step ow over the GetApplicationPath method call. ow
ed ed
! !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
When you au define
tho prima method,
M a rta you might realize that it
au requires
tho p rim different
art sets of
riz av B r a aB
arb iz v arb
information ineddifferent
co
pie
era
bscircumstances.
os
a.
You can define overloaded ed
co
pie
era
bsmethods os
a.
to create
s.c s.c
sa o sa om
multiple methods with llo the msame functionality that accept different llo parameters
we we
d! d!
depending on the context in which they are called.
Overloaded methods have the same name as each other to emphasize their common
intent. However, each overloaded method must have a unique signature, to
differentiate
Th it from the other overloaded versions
Th of the method in the class.
is is
do d oc
cum um
ma ent en ma
rta be a.b tbrt
. elo
TheNsignature
barb ofonag method includes its name and
l
No its parameter
a rbo ng list. The return type is
ou os st u s st
a o a oM
not partnaof
uth the@signature.
ori
pri
m r taB
na
Ma Therefore, you cannot define u t h ori
@
overloaded
p r im
artmethods that differ
aB
ze av a z av arb
d era rbo ed era
only in their return c op type. b s s.c s a .
c o pie b s s.c
os
a.
ies o s o
all m all m
ow ow
ed ed
! !
The following code example shows three versions of the StopService method, all
with a unique signature.
Overloaded Methods
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
void
No StopService()
rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
{ tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
... c op ss sa co bs os
ies .co . pie s.c a.
all m sa om
o llo
} we
d!
we
d!
void StopService(string serviceName)
{
...
}
void
Th StopService(int serviceId)
i
Th
is
sd d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/50
10/25/2019 20483A - Programming in C# | Skillpipe
{
...
}
When you invoke the StopService method, you have choice of which overloaded
Th you use. You simply provide the relevant
version Th arguments to satisfy a particular
is is
d oc d oc
u
me then the compiler works out whichm version
me to invoke based on the u
overload,
ma
r
and
nt ar nt
ta. be ta. be
ba lon ba lon
arguments
N ou r bthat
os you gs passed.
to
No
un
rbo
sa
gs
to
na a @ Ma au @ Ma
uth pri rta tho pri rta
ori ma Ba riz m av Ba
ze ve rbo ed era rbo
dc rab co b
op sa sa
Creating Methods that Use Optional Parameters
ies
all
s s .co
m
. pie
sa
llo
s s.c
om
.
ow we
ed d!
!
Th Th
is is
do d oc
c um um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s c b os
By defining overloaded pie
sa
s smethods,
.co a . you can implement different o pie versions
s
s s.c
o
ofa.a method
llo m a llo m
that take different parameters. we
d! When you build an application that weuses overloaded
d!
methods, the compiler determines which specific instance of each method it should
use to satisfy each method call.
There are other languages and technologies that developers can use for building
Th
applications and components that do not follow Tthese
his rules. A key feature of Visual
is
d oc d oc
me u me u
C# ismthe
ar ability
nt to interoperate with applicationsmand
ar components
nt that are written by
ta. be ta. be
arb onb l arb on b l
using
No other
u otechnologies.
s
gs
t
One of the principal technologies
No
u o s that
gs Windows uses is the
t
na a@ oM na a@ oM
uth pri art uth pri art
Component ori Object
z
ma Model
v
a B (COM). COM does not support
ori
z
overloaded
ma
v
a B methods, but
era ed arb ed era arb
co bs os co bs os
instead uses methods
p ies that
s .co can. take optional parameters. Toiemake
a p
s
sit.coeasiera. to
all m all m
ow ow
incorporate COM libraries ed and components into a Visual C# solution,
!
ed Visual C#
!
also
supports optional parameters.
Optional parameters are also useful in other situations. They provide a compact and
simple solution when it is not possible to use overloading because the types of the
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/50
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to define a method that accepts one
mandatory parameter and two optional parameters.
Th Th
is is
d
Definingcao Method with Optional Parameters do
um cu
ma en ma me
rta tb r nt
.ba elo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed
void StopService(bool era rboforceStop, string serviceName ed era = null, rbo int
co b s s a. c o b s sa
pie s.c pie s.c .
serviceId =1) llo s a o m s a o m
llo
we we
d! d!
{
...
}
Th Th
When isdefining a method that accepts optional parameters,
do
is
do you must specify all
cu cu
me me
mandatory
ma
rt parameters
nt
b
before any optional parameters.
ma
rt nt
b
a.b elo a.b elo
No arb ng No arb ng
un o sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
The following riz codeavexample
ed era arb shows a method definitionrizthat
ed uses
av
era optional arb parameters
co b s os co b s os
pie s.c a. pie s.c a
that throws a compile s a error. om sa om
.
llo llo
we we
d! d!
The following code example shows how to invoke the StopService method, passing
only an argument for the forceStop mandatory parameter.
T
his Th
is
do
var forceStop = true; d oc
cu um
ma me ma en
rta nt rt tb
StopService(forceStop);
.b be
l a.b elo
arb on arb ng
No o gst No os st
un sa oM un a oM
au @ au @
tho pri art tho p rim art
riz ma aB riz av aB
ed v era arb ed era arb
co bs os co bs os
The following code p ies example s .co shows
a. how to invoke the StopService p ies s .cmethod,
om
a. passing
all m all
ow ow
an argument for the forceStop ed
! mandatory parameter, and an argument ed
! for the
serviceName parameter.
Th Th
is is
do d oc
c um um
var mforceStop
ar nt e
= true; ma en
rt tb
ta. be a.b elo
ba lon a ng
rbo
varNo serviceName gs = "FourthCoffee.SalesService"; No rbo st
un sa t o u na s a oM
au @ Ma u @
tho p rim r t t h p r i art
StopService(forceStop,
riz av aB serviceName); ori m av aB
ed era a rbo zed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
c um um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Traditionally, when calling a method, the order and position of arguments in the
method call corresponds to the order of parameters in the method signature. If the
arguments are misaligned and the types mismatched, you receive a compile error.
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 16/50
10/25/2019 20483A - Programming in C# | Skillpipe
In Visual C#, you can specify parameters by name, and therefore supply arguments
in a sequence that differs from that defined in the method signature. To use named
arguments, you supply the parameter name and corresponding value separated by a
colon.
The following code example shows how to invoke the StopService method by using
Th Th
i i
nameds darguments
oc
u
sd
to pass the serviceName parameter.
oc
u
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
u s to un to
Using nNamed
au a @ Arguments
pri Ma au
pri Ma a@
tho m rta m tho rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!
StopService(true, serviceName: "FourthCoffee.SalesService");
When using named arguments in conjunction with optional parameters, you can
easily omit parameters. Any optional parameters will receive their default value.
Th Th
However,
is
d if you omit any mandatory parameters, syour
i
d code will not compile.
oc oc
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
rbo a rbo ng
You Ncan
o u mix
na spositional
a @
gs
t o and named arguments. No
However,
u na s a you
@
smust
to specify all
uth pri Ma u p Ma
ori ma rta th rim rta
positional argumentsze ve before Ba any named arguments. orize av
era Ba
dc rab rbo dc rbo
op s s a o pie b s sa
ies s.c . s.c .
all om sa om
ow llo
ed we
! d!
Additional Reading: For more information about using named arguments,
see the Named and Optional Arguments (C# Programming Guide) page at
http://go.microsoft.com/fwlink/?LinkID=267784.
Creating
Th
is
do
Methods that Use Output
Th
isParameters
do
cu cu
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
au pri Ma au pri Ma
tho ma rta tho ma rta
riz ve Ba riz ve Ba
ed rab rbo ed rab rbo
co ss sa co ss sa
pie .c . pie . c .
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/50
10/25/2019 20483A - Programming in C# | Skillpipe
A method can pass a value back to the code that calls it by using a return statement.
If you need to return more than a single value to the calling code, you can use output
parameters to return additional data from the method. When you add an output
parameter to a method, the method body is expected to assign a value to that
parameter. When the method completes, the value of the output parameter is
assigned to a variable that is specified as the corresponding argument in the method
Th Th
is is
call. do
cum
d oc
um
ma e
nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
s toparameter, os st
To define
una an output
uth
a @
pri Ma you prefix the parameter
un
au ain
@
p
the method
oM
art
signature with
ori ma rta tho rim a
Ba riz av Ba
the out keyword. ze
dc
ve
rab rbo ed
co
era
b
rbo
op s s sa pie s s.c sa
ies .co . sa .
all m om
ow llo
ed we
! d!
The following code example shows how to define a method that uses output
parameters
A method can have as many output parameters as required. When you declare an
output parameter, you must assign a value to the parameter before the method
returns, otherwise the code will not compile.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/50
10/25/2019 20483A - Programming in C# | Skillpipe
To use an output parameter, you must provide a variable for the corresponding
argument when you call the method, and prefix that argument with the out keyword.
If you attempt to specify an argument that is not a variable or if you omit the out
keyword, your code will not compile.
The following code example shows how to invoke a method that accepts an output
Th Th
sd i is
parameter.
oc
u um
d oc
ma me ma
en
rta nt tb
rt
.ba belo a.b elo
No rbo ng N arb ng
un a Method sa s to o un o sa st
Invoking @ that
M Accepts an Output Parameter @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
var statusMessage = string.Empty;
var isServiceOnline = IsServiceOnline("FourthCoffee.SalesService",
out statusMessage);
Th Th
is i
Additional
do
cu Reading: For more information sabout do
cu output parameters, see the
ma m e m m
out
rta parameter
nt
b modifier (C# Reference) pageart at ent b
.ba elo a .ba elo
rbo ng
No http://go.microsoft.com/fwlink/?LinkID=267785. No rbo ng
u sa s to u sa st
na @ Ma o na @ Ma
uth pri rta uth pri rta
ori ma Ba ori ma Ba
ze ve rbo ze ve rbo
dc rab dc rab
op s s.c sa op s s.c sa
ies . ies .
all om all om
Lesson 3: Handling Exceptions ow
ed
!
ow
ed
!
Th Th
is is
do do
In this lesson,
cu
m
you will learn how to implement effective cu exception handling
me
in your
ma en ma nt
rta tb r t
applications.ba and elo how you can use exceptions in your
ng
a .ba methodsbe
lon to elegantly indicate
No rbo s No rbo gs
un condition s a@ t o the un s a@ to
an error au
tho pri to M art code that calls your methods. a uth pri Ma
rta
riz ma aB ori ma Ba
ed ve a rbo ze ve rbo
co rab dc rab
pie ss sa op ss sa
sa .c . i e sa . c .
om om
Lesson Objectives llo
we
d!
llo
we
d!
• Handle
Th
is exceptions by using a try/catch block.This
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/50
10/25/2019 20483A - Programming in C# | Skillpipe
• Throw an exception.
What Is an Exception?
Th Th
is is
do d oc
c um um
ma e
nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Many things can go wrong as an application runs. Some errors may occur due to
flawsThin
is
the application logic, but others may beTdue
his to conditions outside the control
do do
cu cu
of your
m application.
me
n
For example, your application
m cannot
me guarantee that a file exists
n
art tb art tb
.b a elo .ba elo a
on the
No filearsystem
bo ngor that a required database is
s Noonline.rbo Whenng you design an
s
un sa to un sa to
au Ma @ Ma @
application,
tho youprshould
im rtconsider
a how to ensure thatauyour
tho application
pri
m rta can recover
riz
av Ba riz av Ba
eraed rbo ed era rbo
gracefully whenopsuch
c
ies
problems
b s s.c s a . arise. It is common practice c o to
pie simply
b s s.c check sa
. the
all om sa om
return values from methodsow
ed to ensure that they have executed lcorrectly, low
ed however,
! !
this methodology is not always sufficient to handle all errors that may occur because:
• You
T
need to know why the method call has failed,
T
not just that it has failed.
his his
do do
c um cu
me
• Unexpected
ma
rt nt errors such as running out of memory
b
e ma
rt cannot
nt
b
be handled in this way.
a.b elo a.b elo
No arb ng N arb ng
un o s s t o u o s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa co s os
Traditionally, applications
p ies s .co used. the concept of a global error iobject. p es s.cWhen a. a piece of
all m all o m
o ow
code caused an error,weitd!would set the data in this object to indicate ed the cause of the
!
error and then return to the caller. It was the responsibility of the calling code to
examine the error object and determine how to handle it. However, this approach is
not robust, because it is too easy for a programmer to forget to handle errors
appropriately.
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/50
10/25/2019 20483A - Programming in C# | Skillpipe
The following table describes some of the exception classes provided by the .NET
Framework.
T Th
his is
do d oc
c um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
Exception
No rbo Class gs Namespace No arb ng Description
un s to un os st
a@ M a @ oM
au pri art au pri art
tho ma aB tho m aB
riz v arb System riz av arb any exception
Exception e dc e rab ed e
Represents
r ab
op s os co ss os
ies s .co a. pie .raised a.
s that is co during the
all m all m
ow ow
ed ed
execution of an application.
! !
Th
NullReferenceException System Th Represents an exception
is is
do d oc
c
um um that is caused when trying to
ma en ma en
rta tb rt a.b tb
.ba elo elo use an object that is null.
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
FileNotFoundException
tho rim aB System.IO tho rim Represents aB an exception
riz av arb riz av a
ed era ed e rab
caused r
whenbo a file does not
co bs os co ss sa
pie s.c a. pie . .
sa om s exist. com
llo all
we ow
d! ed
!
SerializationException System.Runtime.Serialization Represents an exception
that occurs during the
serialization or
deserialization process.
Th Th
is
Additional Reading: For more information isabout the Exception class, see
do do
cu cu
mthe m me
art Exception
en
t be
Class page at http://go.microsoft.com/fwlink/?
ma
rta nt
be
a.b lon .ba lon
No LinkID=267786.
arbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
Handling Exception by Using a Try/Catch Block
llo
we
d!
llo
we
d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
c
The try/catch blocks ais llo the
we
okey
m programming construct that enables sa
llo
we
o
you m to implement
d! d!
Structured Exception Handling (SEH) in your applications. You wrap code that may
fail and cause an exception in a try block, and add one or more catch blocks to
handle any exceptions that may occur.
Try/Catch Syntax
try
{
// Try block.
Th Th
is is
} do
c
d oc
um um
ma nt e ma en
catchrta([catch
be specification 1]) rt a.b tb
. ba lon elo
No rbo gs No arb ng
sa to os st
{ un
au @ Ma un
au a @ oM
tho pri rta tho p rim art
riz m av Ba riz av aB
// Catch ed blockera 1. rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
} sa om sa om
llo llo
we we
catch ([catch specification d! n]) d!
{
// Catch block n.
}
Th Th
is is
do do
um c c
The statements
ma en
t
that are enclosed in the braces mina theumtry en block can be any Visual C#
tb
rta be rta elo
.ba lon .ba
statements,
No rboand can
sa
gs invoke methods in other objects.
t
No rbIf
o s
any nof
gs these statements
to
un @ o M u na a @ Ma
au pri art uth pri
cause an thexception
ori
ze
m a ve
to beaB thrown, execution passes to orithe
ze
appropriate
m a ve
rta
Ba catch block.
dc rab arb d r rbo
os co ab sa catch and
The catch specification op
ies ssfor each
.co a. block determines which exceptions pie
sa
ss it will
. co .
all m llo m
ow
the variable, if any, in which ed
!
to store the exception. You can specify we catch blocks for
d!
different types of exceptions. It is good practice to include a catch block for the
general Exception type at the end of the catch blocks to catch all exceptions that
have not been handled otherwise.
try
{
} Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/50
10/25/2019 20483A - Programming in C# | Skillpipe
Additional Reading: For more information about try/catch blocks, see the try-
Th Th
catch
is
do (C# Reference) page
at http://go.microsoft.com/fwlink/?
is
do
cu cu
mLinkID=267787.
art
m en ma me
nt
a.b tb rt a.b be
elo lon
No arbo ng No arb gs
un sa st un os to
@ oM a@ Ma
au p art au pri
tho rim aB tho m rta
riz av arb riz av Ba
ed era ed era rbo
Using a Finally Block co
pie
sa
b s s.c
om
os
a. co
pie
sa
b s s.c
om
sa
.
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
Some methods e e
d c may rcontain critical code that must always e be e
run, even
op ab
s
rb os d co r ab
s osif an
ies s .co a . p ies s.co a.
a m
unhandled exceptionllowoccurs. For example, a method may needlloto a m
ensure that it
ed we
! d!
closes a file that it was writing to or releases some other resources before it
terminates. A finally block enables you to handle this situation.
You specify a finally block after any catch handlers in a try/catch block. It specifies
codeT that must be performed when the block finishes,
T irrespective of whether any
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/50
10/25/2019 20483A - Programming in C# | Skillpipe
You can also add a finally block to code that has no catch blocks. In this case, all
exceptions are unhandled, but the finally block will always run.
Th Th
is is
do
The following code example shows do a try/catch/finally block.
how to implement
cu cu
ma me m ma en
rta n tb rt tb
.ba elo a.b elo
No rbo ng No arb ng
un sa st un os st
oM a oM
Try/Catch/Finally
au
tho
@
prim
Blocks art au
tho
@
p rim art
riz av aB riz av aB
ed era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
try
{
}
catch (NullReferenceException ex)
{
Th Th
is is
//docCatch
um
do
all NullReferenceException exceptions.
cu
ma en ma me
r t r nt
} t a.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un (Exceptionsa to un sa to
catch au @
p Mex)
a a u @
p Ma
tho rim rta tho rim rta
riz av Ba riz av Ba
{ ed e rab rbo ed era rbo
co ss sa co b s sa
pie .c . pie s.c .
sa
om exceptions. sa om
// Catch allllo other llo
we we
d! d!
}
finally
{
// Code that always runs.
}
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
s t s st
Additional
un
au a @
pri
Reading:
o M art
For more information uabout
n a uth
try/catch/finally
a @
pri
oM
art
blocks, see
tho m a o m a
the try-catch-finally
riz
ed
av
era B(C#
arb Reference) page at http://go.microsoft.com/fwlink/?
riz
ed
av
era Ba
rbo
co b ss o sa c op b ss sa
LinkID=267788. pie
sa .c om
. i e sa . com
.
llo llo
we we
d! d!
Throwing Exceptions
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
You canaucreate
tho an
prim instanceM a rta of an exception class inauyour code
tho p rim and art throw the
riz av B r a aB
arb iz v arb
exception to eindicate
dc
op
era
that
bs an o exception
sa has occurred. When ed
co
p
you era
throw
bs anos exception,
a.
ies s .co . ies s.co
a m a m
execution of the current l l ow block of code terminates and the CLR passes l l ow control to the
ed ed
! !
first available exception handler that catches the exception.
To throw an exception, you use the throw keyword and specify the exception object
to throw.
Th Th
is is
do do
The followingu c code example shows how to create an cuinstance of the
ma m en ma me
rta t r nt
.ba belo t a .bex be
NullReferenceException
No rbo n gs class and then throw the
No a rbo object.
lon
gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
d r ab
Creating and Throwing co
pie b s s.c an oException
s a .
co
pie s s.c sa
.
sa om sa om
llo llo
we we
d! d!
Rethrowing an Exception
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/50
10/25/2019 20483A - Programming in C# | Skillpipe
try
{
}
catch (NullReferenceException ex)
{
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
Lesson 4: Monitoring Applications
No
un
au
rbo
sa
@
gsNo
tounMa
a
arb
a@
os
ng
st
oM
tho pri rta uth pri art
riz m av Ba ori m av aB
ed era rbo ze era arb
co b dc b os
pie s s.c sa op s s.c a.
sa . ies
om a o m
When you develop real-world llo
we applications, writing code is just one llo part of the
we
d! d!
process. You are likely to spend a significant amount of time resolving bugs,
troubleshooting problems, and optimizing the performance of your code. Visual
Studio and the .NET Framework provide various tools that can help you to perform
these tasks more effectively.
Th Th
is is
do oc d
In this
m
lesson,
um
e
you will learn how to use a range mof tools
c um and techniques to monitor
e
ar nt art nt
ta. be a.b be
and Ntroubleshoot
ba
rb
lonyour applications.
g No arb lon
gs
ou os st un os to
na a@ oM a@ Ma
uth pri art au pri
ori ma aB tho ma rta
ze ve arb riz ve Ba
dc rab ed rab rbo
Lesson Objectives op
ies s s .co
os
a. co
pie
sa
ss
. com
sa
.
all m llo
ow we
ed d!
After completing this lesson, ! you will be able to:
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Logging and tracing are similar, but distinct, concepts. When you implement logging
in your application, you add code that writes information to a destination log, such as
a text file or the Windows event log. Logging enables you to provide users and
administrators with more information about what your code is doing. For example, if
Th Th
is
your application
do
c
handles an exception, you mightiswrite
do
c
the details to the Windows
um um
ma ne ma en
event log
rta to enable
.ba
t be
lon
the user or a system administrator rta
.ba
tot bresolve
elo any underlying
No rbo gs No rbo ng
st
problems.
un
au
sa
@ to
Ma un
au
sa
@ oM
tho p rim rta tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
By contrast, developers s all
ow
use
o m tracing to monitor the execution ofallan application.
s
ow
o m When
ed ed
you implement tracing, you ! add code that writes messages to a trace ! listener, which
in turn directs your output to a specified target. By default, your trace messages are
shown in the Output window in Visual Studio. You typically use tracing to provide
information about variable values or condition results, to help you find out why your
application behaves in a particular way. You can also use tracing techniques to
Th Th
is is
interrupt dothe execution of an application in response
cu
do to conditions that you define.
cu
ma me ma me
rta nt r nt
.ba belo t a .ba be
ng lon
No rbo s No rbo gs
Writing to the Windows Event Log
un
au
tho
s a@
pri
t oM
art
un
a uth
s a@
pri
to
Ma
ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
Writing to the Windows c sseventsalog is one of the more common op logging
.co requirements
op ss sa
ies .co . ies .
all m all m
ow ow
you might encounter. The ed System.Diagnostics.EventLog class provides
!
ed
!
various
static methods that you can use to write to the Windows event log. In particular, the
EventLog.WriteEntry method includes several overloads that you can use to log
various combinations of information. To write to the Windows event log, you need to
provide a minimum of three pieces of information:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/50
10/25/2019 20483A - Programming in C# | Skillpipe
• The event log. This is the name of the Windows event log you want to write to. In
most cases you will write to the Application log.
• The event source. This identifies where the event came from, and is typically the
name of your application. When you create an event source, you associate it with
an event log.
Th Th
is is
do do
• The message.
cu
me This is the text that you want to add cu to the log.
m
ma n ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
You can alsoeduse co the eraWriteEntry
bs os method to ed
specify a category, co
eran
a bs event os ID, and an
pie s.c a. pie s.c a.
sa om sa om
event severity if required. llo
we
llo
we
d! d!
Additional Reading: Writing to the Windows event log requires a high level of
permissions. If your application does not run with sufficient permissions, it will
throw a SecurityException when you attempt to create an event source or
write to the event log.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
N r No ng arb
The following
ou bos example
a@
gs
to shows how to write a message
u oto
sa the event
st
o log:
na Ma na @ Ma
uth pri rta uth pri rta
ori ma Ba ori ma Ba
ze ve rbo ze ve rbo
dc rab dc rab
op s s sa op s s.c sa
Writing to the Windows i es
all
.coEvent
m
. Log ies
all om
.
ow ow
ed ed
! !
The Debug and Trace classes also include a method named Assert. The Assert
Th enables you to specify a condition (an expression
method Th that must evaluate to true
is is
do do
um c cu
or false)
ma together en
t
with a format string. If the condition ma mevaluates
en
tb
to false, the Assert
rta belo r t a elo
.ba .ba
method
No interrupts
rbo
sa
ngthe execution of the programNand displays
st ou rbo
s
nga dialog box with the
st
un @ o Ma na a @ oM
au p u p art
message thyou ori
ze
specify.
r i m av This
r taB method is useful if you need t h ori
z
to identify
r imav the
a B point in a long-
dc era a rbo ed era arb
b s co b os
running programpiat o
es which
s s.c an unexpected
o
a . condition arises. pies s s.c
o
a.
all m all m
ow ow
ed ed
! !
The following example shows how to use the Debug class to write messages to the
Output window, and to interrupt execution if unexpected conditions arise.
Additional Reading: For more information on tracing, see the How to trace
and debug in Visual C# page at http://go.microsoft.com/fwlink/?
LinkID=267790.
Th Th
is is
do d oc
cum um
ma nte ma en
rta be rt a.b tb
Using Application Profiling
No
.ba
rbo
sa
lon
gs
to
No arb
os
elo
ng
st
un @ Ma un a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be be rt t
When you lon applications, making your codeawork
.ba develop .ba without
lon bugs is only part of
No r bo gs r No bo gs
un sa to un sa to
the challenge.
auth @You
pri also M art have to ensure that your code a uth runspriefficiently.
@ Ma
rta
You need to
ori m a aB ori m a B
ze ve a zed whether vera it uses a
review how long d c your
op
rabcoderbtakes
ss os
a.
to accomplish tasks and co bs
rbo excessive
sa
ies .co pie s.c .
m sa om
processor, memory, lldisk, a
ow or network resources. llo
we
ed d!
!
Visual Studio includes a range of tools, collectively known as the Visual Studio
Profiling Tools, that can help you to analyze the performance of your applications. At
a high level, running a performance analysis in Visual Studio consists of three high-
levelThsteps: Th
is is
do d oc
cum um
ma ent ma en
rta be rt
a.b tb
. elo
1. Create
No
bar bo and l onrun
gs a performance session. All
No performance
a r bo ng analysis takes place
un s t u s st
a @ o M n a @ oM
a
within uth a performance session. You can create uand a
ori
pri
ma
art
aB tho run pria performance
m
art
aB
session
ze ve a riz av a
dc rbo
rabPerformance e dc e rab rbo
by launching op the ss sa
.
Wizard from the Analyze op menu ss in Visual sa
.
Studio.
ies .co ies .co
all m all m
When the performance ow
ed session is running, you run your application ow
ed as you
! !
usually would. While your application is running, you typically aim to use
functionality that you suspect may be causing performance issues.
2. Analyze the profiling report. When you finish running your application, Visual
Studio displays the profiling report. This includes a range of information that can
Th Th
is
provide
do
c
insights into the performance of youris dapplication.
oc For example, you can:
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/50
10/25/2019 20483A - Programming in C# | Skillpipe
o View a timeline that shows what your application was doing when.
3. Th
Revise your code and repeat the analysis.TWhen your analysis is complete, you
is his
do
should do
cu make changes to your code to fix any issues
cu that you identified. You can
ma m en m ma en
rta runt bae new performance session and generate
then rta tb
aenew profiling report. The
.ba lo .ba lo
No rbo ng No rbo ng
un sa to s un sa to s
Visual
au Studio
@
p Profiling
Ma Tools enable you to compare
au @two reports
p Ma to help you
tho rim rta tho rim rta
r Ba a Ba r a
identifyizeand ve
d c quantify
rab how s
i e
rbo the performance of yourzcode
dc
ve changed.
hasrab rbo
s
op ss a. op ss a.
ies .co ies .co
a llo m a llo m
we we
d! d !
his T Th
Using do Performance Counters
cu
is
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un s a@ to un a oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
om om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/50
10/25/2019 20483A - Programming in C# | Skillpipe
Performance counters are system tools that collect information on how resources are
used. Viewing performance counters can provide additional insights into what your
application is doing, and can help you to troubleshoot performance problems.
Performance counters fall into three main groups:
• Counters that are provided by the operating system and the underlying hardware
Th Th
is is
platform.d do
o cu This group includes counters that you can cu use to measure processor
ma me m me
r n t a r nt
use, aphysical
t .ba belomemory use, disk use, and network t a.b use.
a
bThe
elo details of the counters
No rbo ng N r b ng
sa s to according to the hardware that o un thescomputer o s to
available
un
au will @ vary
pri Ma au a@
pri Ma contains.
tho m r ta t h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s s c o b s sa
• Counters that iare p es provided s .co aby the .NET Framework. The i.NET
. p es Framework
s.co .
all m all m
ow ow
includes counters that ed you can use to measure a wide range of
!
edapplication
!
characteristics. For example, you can look at the number of exceptions thrown,
view details of locks and thread use, and examine the behavior of the garbage
collector.
• Counters
Th that you create yourself. You can create
Th your own performance counters
is is
oc d oc application. For example, you d
to examine
um specific aspects of the behavior of yourum
ma en ma en
ta. r be t ta. be r t
can
N
create
ba
r
a lperformance
on
g
counter to count the
N
number
ba
r
oflon calls to a particular
g
ou bo st ou bo st
n sa oM n sa oM
methoduth or to @ count @
a pri athe
rta number of times a specificuthexception
a pri is athrown.
rta
ori m av Ba ori m av Ba
ze era rbo ze era rbo
dc bs dc bs
op s.c sa op s.c sa
ies . ies .
all om all om
ow ow
ed ed
! !
Browsing and Using Performance Counters
Performance counters are organized into categories. This helps you to find the
counters you want when you are capturing and reviewing performance data. For
example, the PhysicalDisk category typically includes counters for the percentage of
time Tspent
his
d reading and writing to disk, amountsTof
his data read from and written to disk,
d
oc oc
me u me u
and the
ma queue
rt nt lengths to read data from and write
b
ma data
rt nto
t b disk.
a.b elo a.b elo
No arb ng N arb ng
un o s s t o u o s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av
Note: You e d c can rabrowse
e
bs
rbo the performance counters available e d co
e r abon your
arb computer
os
op s sa p s s a.
.
from VisualieStudio. sa
llo
.coIn Server
m Explorer, expand Servers, ies expand
a llo
.co the
m name of
we we
your computer, and d! then expand Performance Counters. d!
Typically, you capture and view data from performance counters in Performance
Monitor (perfmon.exe). Performance Monitor is included in the Windows operating
system
Th and enables you to view or capture dataThfrom performance counters in real
is is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/50
10/25/2019 20483A - Programming in C# | Skillpipe
time. When you use Performance Monitor, you can browse performance counter
categories and add multiple performance counters to a graphical display. You can
also create data collector sets to capture data for reporting or analysis.
if (!PerformanceCounterCategory.Exists("FourthCoffeeOrders"))
{ Th Th
is is
do oc d
um c um new
CounterCreationDataCollection
m e counters
m = e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/50
10/25/2019 20483A - Programming in C# | Skillpipe
CounterCreationDataCollection();
CounterCreationData totalOrders = new CounterCreationData();
totalOrders.CounterName = "# Orders";
totalOrders.CounterHelp = "Total number of orders placed";
totalOrders.CounterType = PerformanceCounterType.NumberOfItems32;
Th Th
is is
do
counters.Add(totalOrders); d oc
cu um
ma me m e
nt nt
rta
CounterCreationData
.b be
l
ordersPerSecond a=rt a.new
b
CounterCreationData();
be
l
arb on arb on
No os gs No os gs
u a to
ordersPerSecond.CounterName
na @ = u
"# Orders/Sec";
na a @ to
uth pri Ma uth pri Ma
ori ma rta ori ma rta
ze ve
ordersPerSecond.CounterHelp Ba = "Number of zorders ve placed Ba
dc rab rbo ed rab rbo per
op s sa co s sa
ies s .co . pie s.c .
second"; all m sa om
ow llo
ed we
! d!
ordersPerSecond.CounterType =
PerformanceCounterType.RateOfCountsPerSecond32;
counters.Add(ordersPerSecond);
PerformanceCounterCategory.Create("FourthCoffeeOrders", "A custom
category for
Th Th
sd i is
demonstration",
oc oc d
um um
ma e n m a en
ta. t
rPerformanceCounterCategoryType.SingleInstance,
be rta tb counters);
ba lon .ba elo
No rbo gs No rbo ng
un sa to un sa st
} au @ Ma au @ oM
tho p rim rta tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Note:
You can also create performance counter categories and performance
counters from Server Explorer in Visual Studio.
Th Th
When isyouc
is
do have created custom performance counters,
do
c
your application must provide
um um
ma en ma en
the performance
rta
.
t b counters with data. Performance
e rtcounters
a. t b provide various methods
e
ba lon ba lon
No rbo gs No rbo gs
that enable
un
au
you
s a@ to update
t oM the counter value, suchunas
a
thea@ s Increment to
Ma and Decrement
tho pri art uth pri rta
m a o m
methods. How riz theacounter
ed ve
rab
Ba processes the value will depend
rbo
riz
ed on av the base
era Ba
rbo type you
co ss sa c o b s sa
pie .co the. counter. p ies s.co .
selected when yous acreated llo m a llo m
we we
d! d!
Th Th
is is
do oc d
cum um
ma e m en
When yourta
.ba
haven t be created a custom performance counter
a rta
.ba
category,
tb
elo
you can browse to
lon n
rbo rbo
yourNocategory
un
au @
g
sa and sselectto
M
individual performance No
counters
un
a @
gs
sa in Performance
to
Ma
Monitor.
tho pri art uth pri r t
m aB ori m aB
When you run riz your
ed
av application,
era arb you can then use Performance ze
dc
av Monitor
era arb to view data
co b s o s o b s os
pie s.c a . counters in real time. pie s.c a.
from your custom sperformance
all o m s all o m
ow ow
ed ed
! !
tho
s a@
pri
gs
to
Ma
rta
No
un
au
tho
os
a @
pri
st
oM
art
riz ma riz m aB
Functionality ed
co
pie
ve
rab
ss
.
Ba
rbo
sa
.
ed
co
pie
av
era
bs
s.c
arb
os
a.
sa c om sa om
llo llo
we we
d! d!
Scenario
You have been asked to refactor the code that you wrote in the lab exercises for
module 1 into separate methods to avoid the duplication of code in the Class
Enrollment
T Application. Th
his is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/50
10/25/2019 20483A - Programming in C# | Skillpipe
Also, you have been asked to write code that validates the student information that
the user enters and to enable the updated student information to be written back to
the database, handling any errors that may occur.
Objectives
AfterThcompleting
is this lab, you will be able to: Th
is
do d oc
cum um
ma ent ma en
rta b a.b rt tb
.ba elo elo
n arb ng
• Refactor
N ou r bocode
sa to
g s facilitate
to reusability. N o un o sa st
oM
na @ M au @
uth pri art t h p r i art
ori ma aB ori ma aB
ze ve arb zed vera arb
• Write Visual d cC# code
op
rab that
s o validates
sa data entered by a user.
co
p bs os
a.
ies s .co . ies s .co
all m all m
ow ow
ed e
• Write Visual C# code ! that saves changes back to a database. d!
Th Th
is is
• Virtualdo Machine: 20483A-SEA-DEV11-02, MSL-TMG1
c
do
c
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
• User
No Name:
rbo Student
gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
• Password:edPa$$w0rd co
era
b
rbo
sa
ed
co
era
b os
pie s s.c . pie s s.c a.
sa om sa om
llo llo
we we
d! d!
Scenario
Th Th
is is
do d
In this
m
exercise,
um
e
you will refactor the existing code
c
m
toocuavoid
me writing duplicate code.
art nt art nt
a.b be a.b be
arb l o ng arb lon
No o s N o o gs
un s a@ t oM un s a@ to
a a Ma
The application
uth
ori
pcurrently
r im a r ta enables a user to edit a student’s
u t ho p details
r im rby
ta pressing Enter,
ze a ve B a r iz a v Ba
dc rab rbo e dc e rab rbo
but you now want op them
ies ss to
.co
also sa
.
be able to initiate the edit process
op
ies ss double-clicking
by .co
sa
.
all m all m
on a student in the list. o we You will begin by creating a new method that o we contains the
d! d!
code for editing a student’s details. This will avoid duplicating and maintaining the
code in both event handlers. You will then call the new method from both the
studentsList_MouseDoubleClick and StudentsList_Keydown events.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/50
10/25/2019 20483A - Programming in C# | Skillpipe
While doing this, you also decide to refactor the code for adding and deleting
students into separate methods, so that it can be called from other parts of the
application if the need arises.
You will then run the application and verify that users can press Enter or double-click
on a student to edit the student’s details, can press Insert to add a new student, and
Th Th
sd i is
can press
oc Delete to remove a student.
u um
d oc
ma me ma en
rta nt rt tb
.ba belo a.b elo
No rbo ng N arb ng
un tasks sa s to o un o sa st
The main @ for this
M exercise are as follows: @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
s om sa om
1. Copy the codeallfor ow editing a student into the studentsList_MouseDoubleClickl l ow
ed ed
! !
event handler
2. Run the application and verify that the user can now double-click a student to
edit their details
3. ThUse the Analyze Solution for Code ClonesThwizard to detect the duplicated code
is is
do do
cu cu
ma m en ma me
nt
4. Refactor
rta
.ba
t bthe
elo logic that adds and deletes a student
r t a .ba into
be the addNewStudent and
lon
No rbo n gs No rbo gs
deleteStudent
un sa tomethods un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
5. Verify that students pie s s.c can still
a be added and removed frompie the sapplication
s sa
sa . sa . co .
om m
llo llo
we we
d! d!
6. Debug the application and step into the new method calls
5. Copy the code in this block to the clipboard and then paste it into the
StudentsList_MouseDoubleClick method.
3. Verify that the updated data is copied back to the students list and that the Save
Changes button is now enabled.
Task 3: Use the Analyze Solution for Code Clones wizard to detect the
duplicated code
Th Th
is is
do do
1. On c
the Analyze menu, click Analyze Solution cu
ma formCode Clones.
u m
ma en en
rta tb r t a tb
.ba elo .ba elo
No rbo ng No rbo ng
s s s st
2. Inunathe
uth
Code a@ Clone
pri
t o M Analysis Results window,unexpand
art a uth
a @Exact
pri
o MMatch.
art
ori ma aB ori ma aB
ze ve a rbo ze ve arb
dc rab dc rab os
3. Using the results o s
of.cothe analysis in the Code Clone Analysis o
.cResults a. window,
p ies s s a . p ies s s
all m all o m
ow ow
refactor the duplicated ed
! code into a method called editStudent ed that takes a
!
Student as a parameter.
Task 4: Refactor the logic that adds and deletes a student into the
addNewStudent and deleteStudent methods
4. Call this method from the case Key.Delete code block in the
studentsList_KeyDown method.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
a ng
TaskNo5:
un
Verify
rbo
sa that gs students can still be added
t o
No andrbremoved
u o s a
s t from the
oM
au @ Ma na @
application tho
riz
p rim
av
rta u tho
riz
p rim
av
art
aB
ed era B a ed era arb
rbo os
co b s s a c o b s a.
pie s.c . pie s.c
sa om sa om
llo llo
w we
1. Build the solutioneand d! resolve any compilation errors. d!
3. Add a new student by pressing Insert to display the New Student for Class 3C
window, and verify that it contains no data.
Th Th
is is
do do
c
um cu
4. mEnter details
e for Dominik Dubicki, whose date
m me birth is 02/03/2006, and verify
of
art n tb art nt
a.b elo a . be
b lon
Nothat athe rbo new ngstudent is added to the students
s No list. arb
o gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rbo Liu and verify that the prompt e e rbo
5. Delete thecopstudent rab Run
ss sa
d c window
op
rab
ss appearssa and the
ies .co . ies .co .
student is removed all m
from the student list. all m
ow ow
ed ed
! !
TaskTh6:d
Th new method calls
is Debug the application and step into the
is
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/50
10/25/2019 20483A - Programming in C# | Skillpipe
8. Step over the code until you reach the addNewStudent method call, and then
step into that method.
Th Th
9. Step
is
do out of the addNewStudent method.
is
do
cu cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
10. Cancel adding n a new student, and then continue lon
debugging.
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
11. Delete the ed rowerfor
co ab George
arb
os
Li by pressing Delete. ze
d co
ve
r ab rbo
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
12. Step over the code we until you reach the removeStudent method we
d! d! call, and then
step into that method.
Th Th
Exercise
is
do 2: Validating Student Information
is
do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/50
10/25/2019 20483A - Programming in C# | Skillpipe
Scenario
In this exercise, you will write code that validates the information that a user enters
for a student.
Th Th
Up until
is this point, almost anything can be entered
d
is as student data, and fields can be
d
oc oc
um um
left blank.
m art This
e nt means, for example, that a student
b
m art could en be added to the student list
tb
a.b elo a.b elo
arb ng arb ng
with no
N o u last oname sa or
s to with an invalid date of birth.
N o un o sa st
oM
na @ M au @
uth pri art t h p r i art
ori ma aB ori ma aB
ze ve arb zed vera arb
dc rab o co bs os
op s s sa p s a.
You will write code ies to check
all
.co
m
that . when adding or editing a student,
ies
all
the
.co first
m
name and
ow ow
last name fields for theedstudent ! contain data. ed
!
You will also write code to check that the date of birth entered is a valid date and that
the student is at least five years old.
T
his his T
Finally, dyou
oc will run the application and test your validation
do
c
code.
um um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
st
The main
un tasks
au
sa for this
@ t o Ma exercise are as follows: u na s a @ oM
tho p rim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
1. Run the application s all and
o m observe that student details that s aare noto m valid can be
ow llo
ed we
! d!
entered
2. Add code to validate the first name and last name fields
5. Leave the First Name and Last Name boxes empty, and type 10/06/3012 in the
Date of Birth box.
6. Click OK and verify that a new row has been added to the student list,
Th Th
containing
is
do
a blank first name, blank last name, is
do
and a negative age.
cu cu
ma me ma me
rta nt r nt
.ba belo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au Note: @
pri If you M artenter a date in an invalid format,au the
@
pri application
Ma will crash.
tho m a t h o m rta
riz av B arb r iz a v B arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
7. Close the application.
Task 2: Add code to validate the first name and last name fields
Th Th
is is
do d oc
cum um
ma ent ma en
r rt t
1. N
Intathe r
be
.ba ok_Click
lon
g N
a.b
method in StudentForm.xaml.cs be
ar code,
lon add a statement to
g
ou bo st ou bo st
n sa oM n sa oM
check uth if the @ @
a pri First aNamer t
box is empty. a u t h p r i art
ori m av aB ori m av aB
ze era a rbo zed era arb
dc b c b os
op s s.c s a o pie s s.c a.
2. If it is empty,iesdisplay a .
message box with a caption of Error
s containing the text
all o m all o m
ow ow
ed ed
The student must ! have a first name, and then exit the method. !
4. If it is empty, display a message box with a caption of Error containing the text
Th Th
is is
Theocustudent must have a last name, and then
d do exit the click method.
cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss s a. op ss sa
pie .
Task 3: Add codes ato validate .c om the date of birth i e sa . com
llo llo
we we
d! d!
2. If the entered date is invalid, display a message box with a caption of Error
Th T
containing
is
do the text The date of birth must hbe
is a valid date, and then exit the
do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/50
10/25/2019 20483A - Programming in C# | Skillpipe
method.
4. If the age is less than five years, display a message box with a caption of Error
Thcontaining the text The student must at least
T 5 years old, and then exit the
his
is
do do
method. cu
me
cu
me
ma nt ma nt
rta be rta be
.ba lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ Ma au @ Ma
tho pri rta tho pri rta
Note:
riz
ed
To
m av work
era Bout
arb the age in years, use therizfollowing
ed
ma
ve formula: Ba
os rab rbo
co bs a. co s sa
pie s.c pie s.c .
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do do
Task 4: Run cu
m
the application and verify that student cu information is now
me
validated
ma en ma nt
correctly
rta
.ba
t belo r t a .ba be
lon
No rbo n gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
1. Build the csolution bsand resolve
os any compilation errors. d co r ab
op s.c a pie s s.c sa
ies . sa .
all om om
ow llo
ed we
d!
2. Run the application. !
4. Leave the First Name, Last Name, and Date of Birth boxes empty.
Th Th
5. Click
is
do OK, verify that an error message appears
is
do containing the text The student
cu cu
mmust me m me
art
a.b
have
n t b a first name, then close the error art message
a
nt
be
box.
elo . b lon
No ar bo n gs No a r bo gs
un sa to un sa to
a @ M a @ Ma
6. Type uth Darren
ori
pri intoarthe
ma ta First Name box, and then u t click
ho OK.
p r im rta
ze ve B a r iz a v Ba
dc rab rbo e dc e rab rbo
op ss sa op ss sa
ies .co . ies .co .
7. Verify that an error all message
m appears containing the text aThe llo student
m must
ow w
e e
have a last name,d! and then close the error message box. d!
8. Type Parker into the Last Name box, and then click OK.
9. Verify that an error message appears containing the text The date of birth
Th
must be a valid date, and then close the Terror message box.
is his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 44/50
10/25/2019 20483A - Programming in C# | Skillpipe
10. Type 10/06/3012 into the Date of Birth box, and then click OK.
11. Verify that an error message appears containing the text The student must be
at least 5 years old, and then close the error message box.
12. Amend the date to 10/06/2006, click OK, and then verify that Darren Parker is
Thadded to the student list with an age appropriate
T his
to the current date.
is
do do
cu cu
mClose me ma me
13. art
a.b
thent application.
be rta nt
be
a lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
@ Ma @ Ma
14. In aVisual
uth
ori Studio,
pri
ma close
rta the solution. au
tho pri
m rta
ze ve Ba riz av Ba
dc rab rbo ed era rbo
op ss sa co b s sa
ies .co . pie s.c .
all m sa om
ow llo
ed we
! d!
Results: After completing this exercise, student data will be validated before it is
saved.
Th Th
is is
Exercise
do
cu 3: Saving Changes to the Class oList
m
d
cu
m
ma en ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim tho rim
Scenario rize av
era
aB
arb riz
ed
av
era
aB
arb
dc b os co b os
op s s.c a. pie s s.c a.
ies o sa om
In this exercise, youllowill m
we write code that saves changes in the student list to the
a llo
we
d! d!
database.
Every time the user closes and opens the application, they are presented with the
original student list as it existed when they first ran the application, regardless of any
changes
Th they may have made. You will write code
Th to save changes back to the
is is
d d
databaseocuwhen
m
oc
the user clicks the Save Changes button.
um You will then add
ma en ma en
ta. r be t ta. be r t
exception
N
bahandling
r
lon code to catch concurrency, update,
g N
ba and
r
logeneral
ng exceptions, and
ou bo st ou bo st
a@ s
oM sa oM
handle nthe
au exceptions
th pri
m
agracefully.
rt
na
uthpri
ma
@
art
ori av aB ori aB
zed era arb ze ve arb
co bs os co d r ab os
pie s.c a. pie ss a.
sa om sa .co
m
Finally, you will run yourllo
we application and verify that changes youllowmake ed
to student data
d! !
are persisted between application sessions.
1. ThVerify that
is data changes are not persisted Tto
his the database
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 45/50
10/25/2019 20483A - Programming in C# | Skillpipe
3. Add exception handling to the code to catch concurrency, update, and general
exceptions
4. Run the application and verify that data changes are persisted to the database
Th Th
is is
do d oc
cum um
ma e
nt ma en
r
Task 1:aVerify rt tthe
t .ba bethat
lon data changes are not persisteda . ba to be database
lon
No rbo gs No rbo gs
un sa t o u n s a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
1. In Visual Studio, c from c
s.c the a. E:\Labfiles\Starter\Exercise pie 3 folder, s.c open the
opie b s s o b s sa
sa sa .
om om
llo llo
School.sln solution. we
d!
we
d!
4. ThChange Kevin Liu’s last name to Cook byThpressing Enter in the main
is is
do d oc
application
ma
cu
me window. ma
um
en
rta n t rt tb
.ba be a.b elo
lon arb ng
No rbo g No
5. Verify
un sa thes tupdated
that oM data is copied to the ustudent
na
o s a list st
ando M that the Save
au @ uth @
tho pri art pri art
m aB ori m aB
Changes riz
ed button
av
era is enabled.
arb ze
dc
av
era arb
co b s os op b s os
pie s.c a. ies s.c a.
sa om all o m
llo ow
6. Click Save Changes. we
d! ed
!
7. Delete the student George Li, and then click the Save Changes button.
2. Add code to perform the following tasks when a user clicks Save Changes:
Th Th
is is
do oc d
cum um
ma e
ntexception handling to the code toarcatch m en
Task 3:rtaAdd
.ba belo t a.b tconcurrency,
be
lon
update, and
N r b ng N arb g
general
o u exceptions
na
os
a@
st
oM ou
na
os
a@
st
oM
uth pri art uth pri art
ori ma aB ori ma aB
ze ve arb zed vera arb
dc rab o co bs os
op s s sa p s a.
ies .co . ies .co
1. Enclose the lines all of code
ow
m that call the SaveChanges methodall
ow of mthe
ed ed
! !
schoolContext object and disable the Save Changes button in a try block.
RefreshMode.StoreWins, schoolContext.Students);
this.schoolContext.SaveChanges();
this.schoolContext.Refresh(RefreshMode.StoreWins,
schoolContext.Students);
6. Add another catch block to catch any other type of exception that might occur,
storing the exception in a variable named ex.
Th Th
is is
do d oc
7. In the
ma
umcatch block, add the following code:
e
c
m
um
en
rta nt art tb
.ba belo a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim a B user
// If riz someav other
ed B exception
arb occurs, report r ized
it ato
v the arb
era era
co bs o sa co bs os
p s
MessageBox.Show(ex.Message,
ies .co . "Error saving p ies s
changes");
.co a.
all m all m
ow ow
ed
this.schoolContext.Refresh( ed
! !
RefreshMode.ClientWins, schoolContext.Students);
Th Th
is is
do do
um c cu
Taskm4: me
art Run enthe application and verify that data
t be
ma changes
rta nt
be
are persisted to the
a.b l . b l
database
No arb
os
on
gs No arb
os
on
gs
un a @ t o u na a @ to
au pri M art uth pri Ma
tho m aB ori m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s a . p s .
1. Build the solution sa and
.co resolve any compilation errors. es
m
i
a
. co
m
llo llo
we we
d! d!
2. Run the application.
3. Change Kevin Liu’s last name to Cook by pressing Enter in the main
application window.
8. Run the application and verify that the changes you made to the student data
have been saved to the database and are reflected in the student list.
Results: After completing this exercise, modified student data will be saved to the
database
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
Module Review and Takeawaysuna
No
un
au
rbo
sa
@
gs
to
Ma
No arb
os
a@
ng
st
oM
tho pri rta uth pri art
riz m av Ba ori ma aB
ed era rbo ze ve arb
co b dc rab os
pie s s.c sa op s s a.
sa . ies .co
om
Module Review llo
we
all
ow
ed
m
d! !
In this module, you learned how to create and use methods, and how to handle
exceptions. You also learned how to use logging and tracing to record the details of
any exceptions that occur.
T T
Verifyhithe his a mark in the column to the right.
s d correctness of the statement by placing
o do
cu cu
ma me ma me
rta nt rt nt
.ba belo a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
Statementa uth @
pri M art a uth @
pri Ma
rta
Answer
ori m a aB ori m a Ba
ze ve arb ze ve rbo
dc rab os d co r ab
op s sforms a pie s s.c sa
The return type of a method ies .co part . of a methods signature. sa .
all m om
ow llo
ed we
! d!
Question
You must assign a value to an output parameter before the method returns.
Th Th
Verify ithe
s d correctness of the statement by placing is a mark in the column to the right.
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 49/50
10/25/2019 20483A - Programming in C# | Skillpipe
Statement Answer
A finally block enables you to run code in the event of an error occurring?
Verify the correctness of the statement by placing a mark in the column to the right.
Th Th
is is
do do
Statement c um cu
me Answer
ma en ma nt
rta tb r t a.b be
.ba elo lon
N r b ng N a r b gs
Traceo ustatements os are sactive t o o u builds.
in both Debug and Release mode os to
na a @ M na a @ Ma
uth pri art uth pri rta
ori ma aB ori ma Ba
ze ve a r ze ve rbo
dc rab bo dc rab
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 50/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
Contents:
is
do
cu
is
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho Module pri tho p rim art
av Overview
m rta aB
riz Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
Lesson 1: Implementing llo
we
Structs and Enums llo
we
d! d!
d! d!
Objectives
After completing this module, you will be able to:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d
Lesson
ma
r
um 1 : Implementing Structs and
en
t
c
ma
r
oc
um
en Enums
t
ta.
be ta. be
ba
lon ba lon
No rbo
gs No rbo gs
un sa t o u n s a to
au @ M au @ Ma
tho pri art t h pri rta
m a o m
The .NET Framework
riz
ed
av
era includes Ba
rbo various built-in data types,
riz
ed such
av as Int32,
era Ba
rbo Decimal,
co b s s a. c o b s sa
pie s.c pie s.c .
String, and Boolean. s a However,
llo
om suppose you want to create an
s a object
llo
om that
we we
represented a coffee. Which d! type would you use? You might use built-in d! types to
represent the properties of a coffee, such as the country of origin (a string) or the
strength of the coffee (an integer). However, you need a way to represent coffee as a
discrete entity, so that you can perform actions such as add a coffee to a collection or
compare one coffee to another.
Th Th
is is
do oc d
c um um
ma e
nt you will learn how to use ma en
In this lesson,
rta
.b be
l
structs and rta enums
.ba
t b to create your own
elo simple
arb on rbo ng
No o g st No st
types.una sa
@ oM un
au
sa
@ oM
uth pri art tho p rim art
ori m av aB riz av aB
ze era arb ed era arb
dc b os co b os
op s s.c a. pie s s.c a.
ies
Lesson Objectives all
ow
o m sa
llo
we
om
ed d!
!
After completing this lesson, you will be able to:
• Create
Th and use structs. Th
is is
do oc d
c um um
ma n e ma en
• Define
r ta. constructors
ba
t be
lon
to instantiate structs. r ta.
ba
tb
elo
No r bo gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri at a uth pri art
• Createthproperties
ori ma to rget a B and set field values in a struct. ori ma aB
ze ve a rbo ze ve arb
dc rab dc rab os
op s s sa o p s s a.
ies .co . ies .co
• Create indexers ato llo expose
we
m struct members by using an integer a llo
we
index. m
d! d!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.brt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
An enumeration
au
tho p type,
rim
M or
a rta enum, is a structure that enables
au
tho you
p rim to create art
aB
a variable
riz av B arb r iz a v arb
ed era ed era
with a fixed set coof possible
pie bs
s.c
values.
os
a.
The most common example co
pie
isbsto
s.c
use os an enum to
a.
sa om sa om
define the day of the oweek. l l we There are only seven possible values l l ow for days of the
ed
d! !
week, and you can be reasonably certain that these values will never change.
Declaring
Th
i
an Enum Th
is
sd d
oc oc
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma Monday, Tuesday, na a @ oM
enum Dayau { p
Sunday, u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
Wednesday, Thursday, c op b s Friday,
s Saturday }; c o b s os
ies s.c a . pie s.c a.
all o m s all o m
ow ow
ed ed
! !
To use the enum, you create an instance of your enum variable and specify which
enum member you want to use.
Using enums has several advantages over using text or numerical types:
• Improved code readability. The enum syntax makes your code easier to read and
understand.
Th Th
is is
do oc d
cum um
ma e m en name is the string you define
Each member
rta nt of an enum has a name and a value.
belo
art The
a.b tb
elo
.ba arb
No rbo ng N ng
in the ubraces,
na sa such tas
@
s
o M Sunday or Monday. By default, o un the
o sa value
@
s t is an integer. If you
oM
uth pri art au p art
ori ma a t h r ima
oriare assigned a Bincremental
do not specify ze a value
dc
ve forBeach
rab arb member, the members zed vera arb
op s o sa co bs os
s . p s a.
values starting with ies 0. For
all
.co example, Day.Sunday is equal toie0
m sa and Day.Monday
. com is
ow l l ow
ed ed
equal to 1. ! !
The following example shows how you can use names and values interchangeably:
Reference Links: For more information about enums, see the Enumeration
Types (C# Programming Guide) page at http://go.microsoft.com/fwlink/?
ThLinkID=267792. Th
is is
do do
cum cu
ma e ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
Creating and Using Structs
au
tho
riz
pri
ma
Ma
rta
Ba
au
tho
riz
pri
ma
Ma
rta
Ba
ed ve rbo ed ve rbo
co rab co rab
pie ss sa pie ss sa
sa .c . sa . c .
om om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b rt
a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
In VisualautC#,
ho
a struct
prim
Mis
a a
rta programming construct that
au you can
tho p rim use artto define custom
riz av B r a aB
arb iz v arb
types. Structsedare co
pie
era
essentially
bs o lightweight
sa data structures ed
that
co
pie
era
representbs orelated
sa pieces
s.c . s.c .
s om sa om
of information as a asingle llo
we item. For example: llo
we
d! d!
Creating a Struct
Th Th
is is
You usedothe
cu struct keyword to declare a struct, as dshown
oc
u by the following example:
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
Declaringau a Struct
tho pri Ma
rta
au
tho pri Ma
rta
riz ma Ba riz ma Ba
ed ve rbo ed ve rbo
co rab co rab
pie ss sa pie ss sa
sa .c . sa . c .
om om
llo llo
we we
d! d!
public struct Coffee
{
public int Strength;
public string Bean;
public string CountryOfOrigin;
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/55
10/25/2019 20483A - Programming in C# | Skillpipe
internal The type is available to any code within the same assembly, but not available to code
in another assembly. This is the default value if you do not specify an access modifier.
private The type is only available to code within the struct that contains it. You can only use
the private access modifier with nested structs.
Th Th
is is
do d oc
cum u
me
Structs
ma can contain
rt nt
b
a variety of members, including
e ma fields,
rt nt properties, methods, and
b
a.b elo a.b elo
arb ng arb ng
events.
N ou os
a
st
oM
No
un os
a
st
oM
na @ au @
uth pri art tho p rim art
ori m av aB riz av aB
ze era arb ed era arb
dc b os co b os
op s a. s a.
Using a Struct ies
all
s.c
o m
pie
sa
s.c
om
ow llo
ed we
! d!
To create an instance of a struct, you use the new keyword, as shown by the
following example:
Instantiating a Struct
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
Coffee .bacoffee1 lon = new Coffee(); elo
No rbo gs No arb ng
un s to un os st
a@ M= a @ oM
au
coffee1.Strength pri art 3; au pri art
tho ma aB tho m aB
riz ve arb riz av arb
ed r ed era
coffee1.Bean co = "Arabica";
ab
ss os
a. co bs os
a.
pie .co pie s.c
sa m sa om
coffee1.CountryOfOrigin llo = "Kenya"; llo
we we
d! d!
Initializing Structs
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c um um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
You might au havepnoticed
tho
@
rim
M a that
rta
the syntax for instantiating
au
tho a struct,
@
p rim for
art example, new
riz av B r a aB
ed arb
era the syntax ized is becausevera arb
Coffee(), is similar co to bs o sa for calling a method. This co bs when
os
a.
you
pie s.c . pie s.c
s om sa om
instantiate a struct, ayou llo
we are actually calling a special type of method
llo
we called a
d! d!
constructor. A constructor is a method in the struct that has the same name as the
struct.
When you instantiate a struct with no arguments, such as new Coffee(), you are
calling
Th the default constructor which is created by
Th the Visual C# compiler. If you want
is is
d
oc to specify default field values when you instantiate
oc d
to be ableum um a struct, you can add
ma en ma en
ta. r be t t r tb
constructors
ba thatlonaccept parameters to your struct.a.ba elo
ng
N ou r bo g st N r ou bo st
na sa oM na s a oM
uth @ uth @
pri art pri art
ori m av aB ori m av aB
ze era arb ze era arb
The following dexampleco
pie b s shows
s.c
os how
a. to create a constructord cin op a struct:
b s s.c
os
a.
sa om ies o
llo all m
we ow
d! ed
!
Adding a Constructor
The Tfollowing
his
d
Th
example shows how to use this constructor
is
d
to instantiate a Coffee
oc oc
um um
item:mar e nt ma
rt
en
tb
ta. be a.b elo
ba lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
Calling a Constructor
riz
ed
m av Ba riz
ed
av aB
arb
era rbo era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do oc d
You can
m
add
um multiple constructors to your struct, with
e
c
m
each
um
e
constructor accepting a
ar nt ar nt
ta.
different
N
ba
rb
be
combination
lon
g
of parameters. However, Nyoutacannot
.ba
rb
be
ladd
on
g
a default constructor
ou os st ou os st
na @ a o na a@ oM
to a struct
uth because
pri
m
it Misartcreated
a
by the compiler. uth pri
m
art
aB
ori av Ba ori av
zed era rbo ze era arb
co b dc b os
pie s s.c sa op s s.c a.
sa . ies
om all o m
Creating Properties llo
we
d!
ow
ed
!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
In Visual C#, a property llo
we is a programming construct that enables llo client code
we to get or
d! d!
set the value of private fields within a struct or a class. To consumers of your struct or
class, the property behaves like a public field. Within your struct or class, the property
is implemented by using accessors, which are a special type of method. A property
can include one or both of the following:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/55
10/25/2019 20483A - Programming in C# | Skillpipe
• The get accessor uses the return keyword to return the value of the private field
to the caller.
• The set accessor uses a special local variable named value to set the value of the
Th Th
is is
privatedo field. The value variable contains the value
c
do provided by the client code
c
um um
ma en ma en
whenta.bit accessed
r tb
elo the property. rt a.b elo
tb
No ar bo ng No arb ng
un sa s to un os st
@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
The following example sa
llo
shows
c om how to use a property: sa
llo
om
we we
d! d!
Using a Property
coffee1.Strength = 3;
// The following code invokes the get accessor.
int coffeeStrength = coffee1.Strength;
The client code uses the property as if as it was a public field. However, using public
Th
properties Th
to expose private fields offers the following advantages over using public
is is
d oc d oc
me u um
fieldsmdirectly:
ar nt ma en
rt tb
ta. be a . elo
ba lon ba ng
No rbo gs No rbo st
un sa to un sa oM
au @ M au @
tho p rim a rta tho p rim art
• You can ruse ize properties
av
era B to
arb control external access to r izyour
ed
fields.
a vera
aAB property that
arb
dc bs o co bs os
op sa a. only a set
includes only aiesget accessor s .co
m
. is read-only, while a property p iesthat includes
s .co
m
all all
ow ow
accessor is write-only. ed
!
ed
!
• You can change the implementation of properties without affecting client code. For
T
his T
example,
do you can add validation logic, or call hais method
do instead of reading a field
cu cu
ma me ma me
value.
rta be
nt rt a.b
nt
be
.ba lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
au pri Ma au pri Ma
tho ma rta tho ma rta
riz ve Ba riz ve Ba
ed rab rbo ed rab rbo
public int co Strength ss sa co ss sa
pie .c . pie . c .
sa om sa om
{ llo llo
we we
d! d!
get { return strength; }
set
{
if(value < 1)
Th { strength = 1; } Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/55
10/25/2019 20483A - Programming in C# | Skillpipe
• To create a property that reads and writes to a private field, you can use the
This Th
following
do syntax: is
d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a ng
No rbo gs No rbo st
un sa t o u na s a oM
publicau int @ Strength Ma { get; set; } u @
tho p rim rta tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
• To create a property that reads from a private field, you can used!the following
d !
syntax:
In each case, the compiler will implicitly create a private field and map it to your
property. These are known as auto-implemented properties. You can change the
implementation of your property at any time.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/55
10/25/2019 20483A - Programming in C# | Skillpipe
protected) to your accessors. For example, you might create a property with a public
Th
get accessor and a protected set accessor. ForThmore information, see the Restricting
is is
do do
um c um c
Accessor
ma Accessibility
en
t
(C# Programming Guide)mpage
a at
en
t
rta be rta be
arb .b
on l .ba lon
http://go.microsoft.com/fwlink/?LinkID=267793.
No os gs
t
No rbo
sa
gs
to
un a@ oM un @ Ma
au pri art au pri
tho ma aB tho m rta
riz v arb riz av Ba
ed era ed era rbo
co bs os co b sa
Creating Indexers pie
sa
llo
s.c
om
a. pie
sa
llo
s s.c
om
.
we we
d! d!
Th Th
is is
do d oc
c um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s c b os
In some scenarios, pie yous.might
sa
s
co
awant
. to use a struct or a classpieas o
s
a container
s s.c
o
a. for an
llo m a llo m
array of values. For example, we
d! you might create a struct to represent we the beverages
d!
available at a coffee shop. The struct might use an array of strings to store the list of
beverages.
"Cappuccino", "Espresso" };
}
}
When you expose the array as a public field, you would use the following syntax to
Th beverages from the list:
retrieve Th
is is
d oc d oc
um um
ma nt e ma en
rta be rt a.b tb
.ba lon elo
r arb ng
Accessing
N ou boArray
s a
gsItems Directly
to
No
un os
a
st
oM
na @ Ma au @
uth pri rta tho p rim art
ori ma Ba riz av aB
ze ve rbo ed era arb
dc rab co bs os
op s s sa pie s.c a.
ies .co . sa
all m om
o llo
Menu myMenu = newweMenu(); d!
we
d!
A more intuitive approach would be if you could access the first item from the menu
by using
Th the syntax myMenu[0]. You can do this
Th by creating an indexer. An indexer
is is
oc d oc d
is similar
m
to
um a property, in that it uses get and set accessors
e m
um
e
to control access to a
ar nt ar nt
ta. be ta. be
field.N More ba importantly,
rb
lon
g
an indexer enables youNto access
ba
rb collection
lon
g
members directly
ou os st ou os st
na a o
@of the Mcontaining struct or class by nproviding
@ an integer a o
from the uname
th pri
m
art
a
au
th pri
m
Ma
rta index value.
ori av Ba ori av Ba
z z
To declare anedindexer,
co
p
era
s
rbo
bsyou use
ed
co
p
era
sa the this keyword, which indicates
rbo property
bsthat the
s sa
ies .co . ies .co .
m m
will be accessed byalusing
low
e
the name of the struct instance. all
ow
ed
d! !
Creating an Indexer
Th Th
is is
do d oc
c um um
ma e nt ma en
rta be rt a.b tb
.bastruct lon Menu elo
public
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
{ a uth pri au pri art
ori ma rta tho m aB
ze ve Ba riz av arb
rbo ed era
private d string[] co
pie
rab
ss beverages; sa co
pie bs
s.c
os
a.
sa .c . sa
om om
// This is theweindexer. l l o llo
we
d! d!
public string this[int index]
{
get { return this.beverages[index]; }
set { this.beverages[index] = value; }
T}h Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/55
10/25/2019 20483A - Programming in C# | Skillpipe
Reference Links: For more information about indexers, see the Using
Indexers (C# Programming Guide) page at http://go.microsoft.com/fwlink/?
ThLinkID=267794. Th
is is
do d oc
cum um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
No r bo gs No a r bo ng
st
Demonstration: Creating and Using a Struct
un
au
tho
s a @
pri
m
t o M art
u n a uth
s a @
pri
m
oM
art
riz av a Ba o riz av aB
ed era rbo e d e r arb
co bs sa co ab os
In this demonstration, you s
p ies s .co will .create a struct named Coffeeieand p
s adds.co several
a.
all m all m
ow ow
properties to the struct. edYou will then create an instance of the Coffee
!
ed
! struct, set
some property values, and display these property values in a console window.
Demonstration Steps
Th T
5. Start
is
do the MSL-TMG1 virtual machine if it is hnot
is already running.
do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/55
10/25/2019 20483A - Programming in C# | Skillpipe
11. In the New Project dialog box, in the Templates list, click Visual C#, and then
in the Project Type list, click Console Application.
16. Notice that you are able to use the Coffee struct in the same way that you
Th Th
would
is
do use a standard .NET Framework type. is
do
cu cu
ma me m me
rta n tb a r nt
elo menu, click Build Solution. t a.b be
17. On
No
.bthe
arbo Build ng N a r b
lon
gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho m a t h o m rta
18. On therizDebug ed
av menu,
era Ba click Start Without Debugging.
rbo
riz
ed
av
era Ba
rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
llo llo
19. Notice that the Coffee we
d! struct works just like a standard .NET we Framework
d! type at
runtime.
tho
sa
@
pri
gs
to
Ma
No
un
au
tho
a @
os
p
st
oM
art
m rta rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
When you create multiple l l o items of the same type, regardless ofllowhether they are
we we
d! d!
integers, strings, or a custom type such as Coffee, you need a way of managing the
items as a set. You need to be able to count the number of items in the set, add items
to or remove items from the set, and iterate through the set one item at a time. To do
this, you can use a collection.
Th Th
is is
do do
c cu
Collections
ma
um are
en an essential tool for managing multiple
ma meitems. They are also central to
nt
rta tb r t a be
.ba elo .ba lon
developing
No rbgraphical
o
ng
s
applications. Controls such
N o
as drop-down
r b o gs list boxes and menus
un s a t o u n s a to
au @ Ma au @ Ma
are typically tho data-bound
pri
ma r ta to collections. t ho p r im rta
riz ve B a r iz a v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
In this lesson, you willwelearn d! how to use a variety of collection classes we
d! in Visual C#.
Lesson Objectives
After completing this lesson, you will be able to:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 16/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d
Choosing
m
um
en
Collections
c
ma
oc
um
en
art tb rt tb
a.b elo a.b elo
No arb ng No arb ng
un o sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do
All collection do
classes share various common characteristics. To manage a collection
cu cu
ma me ma me
r nt rt nt
of items,.byou
t a
a
must
be
lon be able to: a.b
arb
be
lon
No rbo gs No os gs
un sa to un a@ to
au @ Ma au Ma
tho pri rta tho pri rta
riz m av Ba riz m av Ba
• e
Add items tocothe collection.
d e rab rbo ed era rbo
s sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
w we
• Remove items fromethe d! collection. d!
Th
• Iterate Th item at a time.
through the items in the collection, one
is is
do do
c um cu
ma e ma me
rta nt rt nt
.ba belo a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
Every collection
t ho
riz
rclass
im
av intaVisual
r
B C# provides methodshoandt
r ize
properties
r im
a ve
rta that support
Ba
ed era arb dc rab rbo
co b o sa these operations, however,oyou sato manage
these core operations. pie
sa
sBeyond
s.c
om
. pie will
sa
ss want
. com
.
llo llo
collections in differentwways ed
!
depending on the specific requirements we of your
d!
application. Collection classes in Visual C# fall into the following broad categories:
• List classes store linear collections of items. You can think of a list class as a one-
dimensional array that dynamically expands as you add items. For example, you
Th Th
might
is use a list class to maintain a list of available
d
is
d
beverages at your coffee shop.
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/55
10/25/2019 20483A - Programming in C# | Skillpipe
• Dictionary classes store a collection of key/value pairs. Each item in the collection
consists of two objects—the key and the value. The value is the object you want to
store and retrieve, and the key is the object that you use to index and look up the
value. In most dictionary classes, the key must be unique, whereas duplicate
values are perfectly acceptable. For example, you might use a dictionary class to
maintain a list of coffee recipes. The key would contain the unique name of the
Th Th
i
sd sd i
coffee,
oc and the value would contain the ingredients
u
oc and the instructions for making
u
m me ma me
nt nt
theacoffee.
rta
.b be
lo
rt a.b lon
be
No arb ng No arb gs
un o sa st u os to
@ o M n a @ Ma
au pri art au pri
• t
Queue classes
h ori marepresent aB a first in, first out collection t h ori of objects.
ma rtaItems are
ze ve a ze ve Ba
dc rab rbo dc rab rbo
retrieved frompiethe o collection
s s.c s a. in the same order they werepiadded. o s s For sa
example, you
sa es .co .
om a m
llo llo
might use a queuewclass ed
!
to process orders in a coffee shop towensure ed
!
that
customers receive their drinks in turn.
• Stack classes represent a last in, first out collection of objects. The item that you
added to the collection last is the first item you retrieve. For example, you might
use
T a stack class to determine the 10 most recent
T visitors to your coffee shop.
his his
do do
cum cu
ma e ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
sa to to
When uyou
na choose
uth @
pri a built-in
Ma
rta
collection un
class for a specific
au
th
a@
scenario,
pr Ma ask yourself the
r
ori m ori im ta
ze ave Ba ze av Ba
following questions: dc rab rbo d era rbo
op s sa co b s sa
ies s.c . pie s.c .
all om sa om
ow llo
ed we
! d!
• Do you need a list, a dictionary, a stack, or a queue?
If you can answer all of these questions, you will be able to select the Visual C#
collection class that best meets your needs.
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
The System.Collections
au
tho prim
M a rta namespace provides a range
au
tho of general-purpose
p rim art
riz av B r a aB
ed era arb ized vera arb
collections that includes
co
pie bs lists, o dictionaries,
sa queues, and stacks.
co
pie
Thebs following
os
a.
table
s.c . s.c
sa om sa om
shows the most important llo
we collection classes in the System.Collections llo
we namespace:
d! d!
Class Description
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/55
10/25/2019 20483A - Programming in C# | Skillpipe
Class Description
Stack The Stack class is a first in, first out collection of objects.
The Stack includes methods to view the top item in the
collection without removing it (Peek), add an item to the top
of the stack (Push), and remove and return the item at the
top of the stack (Pop).
Th Th
is is
do d oc
cum um
ma e nt ma en
rta b a rt tb
Reference
. ba
rbo
e lonLinks: For more information aboutbathe classes .
rbo
elo
ng listed in the
No gs No st
previous s t s
una
uth
a @table, M o see the System.Collections Namespace
u na
uth
a @ page
o Ma at
pri art pri rta
ori ma aB ori ma
http://go.microsoft.com/fwlink/?LinkID=267795.
ze
dc
ve
rab a rbo
ze
dc
ve
rab
Ba
rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
Specialized Collection Classes
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The System.Collections.Specialized namespace provides collection classes that
are suitable for more specialized requirements, such as specialized dictionary
collections and strongly typed string collections. The following table shows the most
important collection classes in the System.Collections.Specialized namespace:
Th Th
is is
do d
oc
cum um
ma e nt ma en
Classrta.b be
lon
Description
r ta.
ba
tb
elo
No arb gs No r bo ng
un so to un s st
a@ Ma a @ oM
au p au priis a dictionary
art
t
ListDictionary
ho r im rta tho
The ListDictionary m a B class that is
riz av Ba riz av ar
ed era rbo ed era
co
pie b ss sa optimized for small
pie bs Asboasgeneral
co collections. a.
rule, if
.c . s.c
sa om your collection includesa10 s o
llo llo itemsmor fewer, use a
we we
d! ListDictionary. If your collection d! is larger, use a
Hashtable.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/55
10/25/2019 20483A - Programming in C# | Skillpipe
Class Description
Using
Th
is List Collections
d
Th
is
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.brt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
The most au commonly
tho prim used
M a rta list collection is the ArrayList
au
tho class.
p rim The art ArrayList stores
riz av B r a aB
ed era arb ized vera arb
items as a linear co collection
pie bs ofo objects.
sa You can add objects co of
pie
any bstype to
os an
a.
s.c . s.c
sa om sa om
ArrayList collection,obut l l we the ArrayList represents each item in othe
l l we collection as a
d! d!
System.Object instance. When you add an item to an ArrayList collection, the
ArrayList implicitly casts, or converts, your item to the Object type. When you
retrieve items from the collection, you must explicitly cast the object back to its
original type.
Th Th
is is
do oc d
The following
m
um example shows how to add and retrieve
e
c
m
umitems from an ArrayList
e
ar nt art nt
ta. be a.b be
collection:
N
ba
rb
lon
gs No arb lon
gs
ou os to un os to
na a@ Ma au a@ Ma
uth pri rta tho pri rta
ori m a Ba riz m av Ba
ze ve rbo ed era rbo
d
Adding and Retrievingco rab Items from an ArrayList co b
pie s s.c sa pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
When you work with collections, one of your most common programming tasks will
be to iterate over the collection. Essentially, this means that you retrieve each item
fromTthed
Th of items, to evaluate each item
his collection in turn, usually to render a list is
d
oc oc
u
me criteria, or to extract specific member me u
against
ma some
r nt ma values
r nt from each item. To iterate
ta. be ta. be
ba lon ba lon
over oaucollection,
N r bos you
g s t use a foreach loop. The foreach N ou r b osloop gexposes
st each item from
na a @ o Ma na a @ oM
uth pri u tho p ri a
the collectionori in turn,
ze
ma
ve
using
rta
Ba the variable name you specify riz inmthe av loop
rta declaration.
Ba
dc rab rbo e dc e rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
The following example eshows
d! how to iterate over an ArrayList collection: ed
!
Th Th
foreach(Coffee
is
d coffee in beverages) is
d
oc oc
um um
{ ma ent ma en
rta be a.b rt tb
.ba lon elo
rbo
NConsole.WriteLine("Bean gs a rbo
No coffee.Bean); ng
ou s a t o
type: {0}", u s a
st
oM
na @ Ma na @
uth pri r t u t h p r i art
ori m
Console.WriteLine("Country av aB of origin: {0}", ori m av aB
ze era a rbo zed era arb
dc b c b os
op s s.c s a o pie s s.c a.
coffee.CountryOfOrigin); ies o
. s o
all m all m
ow ow
Console.WriteLine("Strength ed (1-5): {0}", coffee.Strength); ed
! !
}
Reference Links: For more information on the ArrayList class, see the
ThArrayList Class page at http://go.microsoft.com/fwlink/?LinkID=267797.
Th
is is
do do
c um cu
ma e ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
Using Dictionary Collections
au
tho pri
ma
Ma
rta
au
tho pri
ma
Ma
rta
riz ve Ba riz ve Ba
ed rab rbo ed rab rbo
co ss sa co ss sa
pie .c . pie . c .
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
Dictionary au classes
tho prim store M a rta collections of key/value pairs.
au
tho The p most
rim commonly
art used
riz av B r a aB
ed era arb ized vera arb
dictionary class cois the
pie bHashtable.
ss os
a
When you add an item to
co a Hashtable
p bs os collection,
a.
.c . i e s . c
sa om sa om
you must specify a key l l ow and a value. Both the key and the value ocan l l we be instances of
ed d!
!
any type, but the Hashtable implicitly casts both the key and the value to the Object
type. When you retrieve values from the collection, you must explicitly cast the object
back to its original type.
The Tfollowing
h
example shows how to add and retrieve
Th items from a Hashtable
is is
oc d oc d
collection.
m
Ine this case both the key and the value
um
m
are umstrings:
e
art nt art nt
a.b be a.b be
a lon arb lon
No rbo gs No os gs
un sa to un a@ to
a @ Ma Items au Ma
Adding anduth
ori
Retrieving
pri
m rta from a Hashtable tho pri
m rta
ze a ve Ba riz av Ba
dc rab rbo ed era rbo
op s sa co b s sa
ies s.c . pie s.c .
all om sa om
ow llo
ed we
! d!
// Create a new Hashtable collection.
Hashtable ingredients = new Hashtable();
// Add some key/value pairs to the collection.
ingredients.Add("Café au Lait", "Coffee, Milk");
ingredients.Add("Café
Th Mocha", "Coffee,ThMilk, Chocolate");
is is
do do
cu
ingredients.Add("Cappuccino", "Coffee, Milk, cu
ma m en ma me Foam");
rta tb r nt
.ba elo ta. be
ingredients.Add("Irish ng Coffee", "Coffee, b
Whiskey,
arb lon Cream, Sugar");
Nou rb
os st N ou g os st
na a@ oM na a@ oM
ingredients.Add("Macchiato",
uth pri
ma
art "Coffee, Milk, uth Foam"); pri
ma
art
ori aB ori aB
ze ve a r ze ve arb
// Check whether d co r b
aba keyosexists. d co r ab os
pie ss a . p ies s s a.
sa .co .co
llo m a llo m
if(ingredients.ContainsKey("Café we Mocha")) we
d! d!
{
// Retrieve the value associated with a key.
Console.WriteLine("The ingredients of a Café Mocha are: {0}",
ingredients["Café
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/55
10/25/2019 20483A - Programming in C# | Skillpipe
Mocha"]);
}
Reference Links: For more information on the Hashtable class, see the
Hashtable Class page at http://go.microsoft.com/fwlink/?LinkID=267798.
Th Th
is is
do d oc
c um um
ma ent ma en
rta rt tb
Querying a Collection
No
.ba
rbo
be
lon
gs No
a.b
arb
os
elo
ng
st
un s a@ to un a oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
om om
llo llo
we we
d! d!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/55
10/25/2019 20483A - Programming in C# | Skillpipe
LINQ is a query technology that is built in to .NET languages such as Visual C#.
LINQ enables you to use a standardized, declarative query syntax to query data from
a wide range of data sources, such as .NET collections, SQL Server databases,
ADO.NET datasets, and XML documents. A basic LINQ query uses the following
syntax:
Th Th
sd i is
from <variable
oc
u
names> in <data source> d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
u s to un oM
where n<selection
au a @
pri criteria>
Ma au a @
p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
orderby <result ordering llo
we
criteria> llo
we
d! d!
For example, suppose you use a Hashtable to maintain a price list for beverages at
Fourth
Th Coffee. You might use a LINQ expression
Th to retrieve all the drinks that meet
is is
oc d oc d
certain
m
price
um criteria, such as drinks that cost less than
e m
um $2.00.
e
art nt art nt
a.b be a.b be
a lon arb lon
No rbo gs No os gs
un sa to un a@ to
a @ Ma shows how to a Ma
The following
uth
ori
example
pri
m rta use a LINQ expression
uth
ori
pri to query
m rta a Hashtable:
ze a ve Ba ze a ve Ba
dc rab rbo dc rab rbo
op s s.c sa op s s.c sa
ies . ies .
all om all om
Using LINQ to Querywead Collection o ow
ed
! !
In addition
Th
is
to this basic query syntax, you can call
Th a variety of methods on your query
is
do do
cu cu
results.
m Formeexample:
n ma me
nt
art t be rta be
a.b lon .ba lon
No arbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
• Call the pri
thoFirstOrDefault art method to get the first item from prithe results rta collection, or a
riz m av aB ori m a Ba
ed era arb ze ve r
os d r ab b os
default valuecopifiethe bcollection ss
.co a. contains no results. This method co
pie is
ss useful
.co a. if you have
sa m s a m
llo llo
ordered the results wof
ed your query.
!
we
d!
• Call the Last method to get the last item from the results collection. This method is
useful if you have ordered the results of your query.
• Call the Max method to find the largest item in the results collection.
Th Th
is is
do oc d
• Call
m
theumMin
e
method to find the smallest item min the
c umresults collection.
e
art nt art nt
a.b be a.b be
arb l ong arb lon
No o s N o o gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
Note:r i ze Most
dc
ve built-in
rab a types
rbo provide methods that zenable
e dc
ve you
rab
toBa compare one
rb
instance op
ieto ss
another sa
to . determine which is considered op
i larger ss or osmaller.
sa
. The
sa .c om e sa . com
llo llo
Max and Minwemethods d! rely on these methods to find thewelargest d! or smallest
items. If your collection contains numerical types, these methods will return
the highest and lowest values, respectively. If your collection contains
strings, members are compared alphabetically—for example, "Z" is
considered greater than "A". If your collection contains custom types, the
Max and Min methods will use the comparison logic created by the type
Th
is
developer. Th
i
do sd
c oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/55
10/25/2019 20483A - Programming in C# | Skillpipe
For example, if you have ordered your results by ascending cost, the first item in the
results collection will be the cheapest and the last item in the results collection will be
the most expensive. As such, you can use the FirstOrDefault and Last methods to
find the
Th cheapest and most expensive drinks, respectively.
i
Th
i
sd sd
oc oc
um um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
TheNfollowing
ou r bos
example
ng
st
shows how to retrieve the
N o
smallest
arb
o
and ng largest items
st
from a
na a@ oM un sa oM
au @
collectionthbased
u
ori
pr ion
ma the a r tsort
aB criteria in the LINQ expression:
t h ori
p r ima
art
aB
ze ve arb zed vera arb
dc rab o co bs os
op s s sa p s a.
ies .co . ies .co
all m all m
Using the FirstOrDefault ow and Last Methods ow
ed ed
! !
Last, Max, and Min, are extension methods. Generic types and extension
methods are covered later in this course.
Lesson Objectives
AfterThcompleting
is
d
this lesson, you will be able to:This d
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
N r No arb ng
• Create
ou events
bos
a@
and
gs
to delegates. un a
os st
oM
na Ma au @
uth pri rta tho pri art
ori ma Ba riz m av aB
ze ve rbo ed era arb
• Raise events. dc rab co bs os
op ss sa pie s.c a.
ies .co . sa
all m om
ow llo
e we
• Subscribe to events dand ! unsubscribe from events. d!
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.brt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ o
When you au create
tho prim an event
M a rta in a struct or a class, you au need pa wayMof
tho rim art enabling other
riz av B r a aB
ed era arb ized vera arb
code to subscribe co
pie
to your
bs event.
o sa In Visual C#, you accomplish co
pie
this bs by creating
os
a.
a
s.c . s.c
sa om sa om
delegate. A delegate llois a special
we type that defines a method signature; llo
we in other
d! d!
words, the return type and the parameters of a method. As the name suggests, a
delegate behaves like a representative for methods with matching signatures.
When you define an event, you associate a delegate with your event. To subscribe to
the event
Th from client code, you need to: Th
is is
do d oc
cum um
ma ent ma en
rta be rt
a.b tb
. elo
• Create
No
b aa
rbo method l on gs with a signature that matches
No the a event
rbo ndelegate.
gs This method is
un sa t o u na s a t o
au as the @ Ma @ Ma
known tho prievent
ma handler.
rta uth
o
pri
m rta
riz ve Ba r ize a ve Ba
ed rab rb d r ab rbo
co s os co s sa
pie s.c a . pie s.c .
• Subscribe to thes aevent llo by
om giving the name of your event handler
sa
llo method
om to the
we we
d! d!
event publisher, in other words, the object that will raise the event.
When the event is raised, the delegate invokes all the event handler methods that
have subscribed to the event.
Th Th
is is
do d oc
cum um
ma ent ma e
Suppose r ta. you create
ba
be
lon a struct named Coffee. One ofa.bthe nresponsibilities
rt tb
elo of this struct
No r bo gs No a r bo ng
sa of the to stock level for each Coffeeuninstance. sa s to
is to keep
un
au track @
pri Ma au @ When
p Ma the stock level
tho m r ta t ho r im rta
riz av Ba riz av Ba
drops below ad ccertain e e rabpoint, rboyou might want to raise an event e dc torawarn
e
b
an
rbo ordering
op ss sa op ss sa
ies .co . ies .co .
system that you areallrunning ow
m out of beans. all
ow
m
ed ed
! !
The first thing you need to do is to define a delegate. To define a delegate, you use
the delegate keyword. A delegate includes two parameters:
• The
T first parameter is the object that raised the
T event—in this case, a Coffee
his his
do do
instance.
cu
m
cu
me
m e m
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/55
10/25/2019 20483A - Programming in C# | Skillpipe
• The second parameter is the event arguments—in other words, any other
information that you want to provide to consumers. This must be an instance of
the EventArgs class, or an instance of a class that derives from EventArgs.
Next,Thyou
is need to define the event. To define anThevent,
is you use the event keyword.
do do
um c u c
You precede
ma enthe name of your event with the name
ma ofmthe
en delegate you want to
rta tb rta tb
ba .
lon e .ba elo
associate
No with
rbo your
s
gs event. No
sa
ng
rbo st
un a@ to un @ oM
au pri Ma au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co os
The following example pie
sa
b s sshows
.co
sahow
. to define delegates andcopevents: ies
bs
s .co a.
llo m all m
we ow
d! ed
!
Defining a Delegate and an Event
In this example, you define an event named OutOfBeans. You associate a delegate
named OutOfBeansHandler with your event. The OutOfBeansHandler delegate
takesThtwo parameters, an instance of Coffee that
Th will represent the object that raised
is is
d d
the eventocuand
m an instance of EventArgs that could obe
cu used to provide more
m
ma en ma en
ta. r be t rt a.b tb
information
N
ba about
r
lon the event.
g No arb
elo
ng
ou bo st os st
na sa oM un a oM
uth @ au @
pri art tho pri art
ori ma aB riz m av aB
ze ve arb ed era arb
Raising Events dc
op
ies
rab
s s .co
os
a. co
pie
sa
bs
s.c
om
os
a.
all m llo
ow we
ed d!
!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
After you au have defined
tho prim
M a an
rta event and a delegate, youau can write
tho p rim code art that raises the
riz av B r a aB
ed era arb ized vera arb
event when certain co
pie
conditions
bs o sa are met. When you raise theco event,
pie bs the delegate
os
a.
s.c . s.c
sa om sa om
associated with your lloevent
we will invoke any event handler methods llo that
we have
d! d!
subscribed to your event.
1. ThCheck whether the event is null. The eventThwill be null if no code is currently
is is
do do
c
subscribing
u to it. cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
2. Invoke
un sthe
a@ event to and provide arguments to the
un delegate. sa to
au M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
For example, suppose ad! Coffee struct includes a method named MakeCoffee. d!
Every
time you call the MakeCoffee method, the method reduces the stock level of the
Coffee instance. If the stock level drops below a certain point, the MakeCoffee
method will raise an OutOfBeans event.
Th Th
is sd i
The following
do
cu example shows how to raise an event:oc
u
ma me ma me
rta n tb rt nt
.ba elo a.b be
ng arb lon
No r bo st No os gs
u s oM un to
Raisingauan Event
n a @
pri art au a@
pri Ma
tho m aB tho ma rta
riz av arb riz ve Ba
ed era ed rab rbo
co bs os co ss sa
pie s.c a. pie . .
sa om sa com
llo llo
we we
d! d!
public struct Coffee
{
// Declare the event and the delegate.
public EventArgs e = null;
public delegate void OutOfBeansHandler(Coffee coffee, EventArgs
Th Th
is is
args);docu d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/55
10/25/2019 20483A - Programming in C# | Skillpipe
if (OutOfBeans != null)
{
// Raise the event.
OutOfBeans(this, e);
Th Th
is } is
do d oc
cum um
ma e nt ma en
rta} be rt a.b tb
elo
.ba lon arb
No rbo gs No ng
} una sa to un os st
@ Ma a @ oM
uth pri au p art
ori m rta tho rim aB
} ze a ve Ba riz av arb
dc rab rbo ed era
op s sa co b s os
ies s.c . pie s.c a.
all om sa om
ow llo
ed we
! d!
To raise the event, you use a similar syntax to calling a method. You provide
arguments to match the parameters required by the delegate. The first argument is
the object that raised the event. Note how the this keyword is used to indicate the
current Coffee instance. The second parameter is the EventArgs instance, which
can be
Th null if you do not need to provide any other
is
Th information to subscribers.
is
do do
cum cu
ma e ma me
rta nt rt nt
.ba be a.b be
lon arb lon
Subscribing to Events
No
un
au
rbo
s a@
gs
to
Ma
No
un
au
os
a@
gs
to
Ma
tho pri rta tho pri rta
riz ma Ba riz ma Ba
ed ve rbo ed ve rbo
co rab co rab
pie ss sa pie ss sa
sa .c . sa . c .
om om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/55
10/25/2019 20483A - Programming in C# | Skillpipe
If you want to handle an event in client code, you need to do two things:
• Create a method with a signature that matches the delegate for the event.
• Use the addition assignment operator (+=) to attach your event handler method to
the event.
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
r ng arb ng
For example,
N ou bos suppose
a@
st
oM
you have created an instance
N o un
of o the
sa Coffee
st
oM
struct named
na au @
uth pri art tho p rim a rta
coffee1. Inoriyour ze Inventory
ma
ve
a B class, you want to subscribe
a riz to the
e
av OutOfBeans Ba that may
dc rab rbo dc e rab rbo
op ss sa op ss sa
be raised by coffee1. ies .co . ies .co .
all m all m
ow ow
ed ed
! !
Note: The previous topic shows how the Coffee struct, the OutOfBeans
event, and the OutOfBeansHandler delegate are defined.
The Tfollowing
his example shows how to subscribe Tto
his an event:
do do
cum cu
ma e ma me
rta nt rt nt
.ba be a.b be
lon arb lon
Subscribing
N ou r bos to an
a@
gs Event
to
No
un os
a@
gs
to
na Ma au Ma
uth pri rta tho pri rta
ori m a Ba riz m av Ba
ze ve rbo ed era rbo
dc rab co b
op s s.c sa pie s s.c sa
ies . sa .
all om om
ow llo
public class Inventory ed we
! d!
{
public void HandleOutOfBeans(Coffee sender, EventArgs args)
{
string coffeeBean = sender.Bean;
Th // Reorder the coffee bean. Th
is is
do d oc
cum um
}
ma ent ma en
rta be a.b rt tb
.ba lon elo
Npublic r bo voidgs SubscribeToEvent() No a r bo ng
ou s t un s st
na a@ oM a @ oM
a
{ uthori pri
ma
art
aB
uth
ori
pri
ma
art
aB
ze ve a rbo ze ve arb
dc rab dc rab os
op
coffee1.OutOfBeans s s sa += HandleOutOfBeans; op s s a.
ies .co . ies .co
all m all m
ow ow
} ed
!
ed
!
}
To unsubscribe from an event, you use the subtraction assignment operator (-=) to
remove your event handler method from the event.
Th Th
is is
do
The following example shows how do
to unsubscribe from
cu cu an event:
ma me m ma en
rta n tb rt tb
.ba elo a.b elo
No rbo ng No arb ng
un sa st un os st
oM a oM
Unsubscribing
au
tho
@
p from
rim
an
art Event au
tho
@
p rim art
riz av aB riz av aB
ed era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
public void UnsubscribeFromEvent()
{
coffee1.OutOfBeans -= HandleOutOfBeans;
}
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
Demonstration: Working with Events in XAML
No
un
rbo
sa
gs
t o
No
u na
a rbo
s a
ng
st
oM
au @ Ma u @
tho p rim rta tho p rim art
riz av B riz av a
Visual Studioedprovides era tools a rbothat make it easy to work with ed events era in BWPF arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
applications. In this demonstration,
llo
we
you will learn how to subscribe llo
we
to events raised
d! d!
by WPF controls.
Demonstration Steps
5. ThClick Visual
is
Studio 2012. Th
is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 35/55
10/25/2019 20483A - Programming in C# | Skillpipe
6. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.
11. In the Properties window, ensure that btnGetTime is selected, and then click
Events.
Th
is Note: The Events button is marked Twith
his a lightning icon.
do do
cum cu
ma e mame
rta nt rt nt
.ba belo a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
a @ M a @ Maevents to
12. Notice uth thatprithe Properties
ori m
art
aB
window now displays uth a listprof
ori im the rta which
ze ave arb ze a ve Ba
d r d r rbo
you can subscribe. co
pie
ab
s s.c
os
a .
co
pie
ab
s s.c sa
.
sa om sa om
llo llo
we we
13. In the Properties dwindow, ! double-click inside the Click text box. d!
14. Notice that Visual Studio creates an event handler method for you and switches
to the code behind page.
18. In the Button element, note that the designer has added the following attribute:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/55
10/25/2019 20483A - Programming in C# | Skillpipe
Click="btnGetTime_Click"
19. In Solution Explorer, expand obj, expand Debug, and then double-click
ThMainWindow.g.i.cs. Th
is is
do d oc
cu um
ma me ma en
n
20. r
Near t a.b thet bbottom
elo of the file, notice that Visual Studio
a.b tb
rt
has
elo added the following line
No arbo ng Noa rbo ng
sa s to sa st
ofunacode:
uth @
pri Ma un
au @
p
oM
art
ori ma rta tho rim aB
ze ve Ba riz av arb
dc rab rbo ed era
op s sa co bs os
ies s .co . pie s.c a.
all m sa om
ow llo
this.btnGetTime.Click ed += new we
! d!
System.Windows.RoutedEventHandler(this.btnGetTime_Click);
This demonstrates that Visual Studio parses the XAML to create the code that
Thsubscribes your event handler method to the Th Click event of the button.
is is
do do
cu cu
mOn m ma me
21. art theenFile t be menu, click Close. rta nt
be
a.b lon .ba lon
No arbo gs No rbo gs
un sa to un sa to
a @ M a @ Ma
22. On uthetho Debug pri
m menu,
art
aB click Start Without Debugging.
uth
ori
pri
m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
23. Click What'ssthe all time?
ow
om button several times. sa
llo
om
ed we
! d!
24. Notice that the label displays the current time.
25. Close the application, close the solution, and then close Visual Studio.
Th Th
is is
do do
Demonstration:
ma
um
en
c Writing Code for the
ma
cuGrades Prototype
me
nt
rta tb r t a be
Application
No
.ba
rbo
s
elo
nLab
gs No
.ba
rbo
s
lon
gs
un a@ to un a@ to
au pri Ma au pri Ma
tho ma rta tho ma rta
r
In this demonstration, ve you Bawill learn about the tasks r
thatzeyou will
ve perform rbo in the lab for
i ze i Ba
dc rab rbo dc rab
op ss sa op s s sa
ies . . ies .co .
this module. all
c om all m
ow ow
ed ed
! !
The School of Fine Arts has decided that they want to extend their basic class
enrollment application to enable teachers to record the grades that students in their
class have achieved for each subject, and to allow students to view their own grades.
This functionality necessitates implementing application log on functionality to
authenticate the user and to determine whether the user is a teacher or a student.
Th Th
sd i sd i
You decide
oc to start by developing parts of a prototype
u
oc application to test proof of
u
ma me ma me
nt nt
concepta.and
r t
ba toeobtain
b
lon client feedback before embarking r t a.b onbe the final application. The
lon
No rbo gs No a rbo gs
prototype
u s
na application a t o will use basic WPF views rather
u na s
than a separateto forms for the
uth @ M uth @ Ma
pri art pri rta
ori ma aB ori ma Ba
user interface. ze These
dc
ve views
rab arb have already been designed
os
ze and you
dc
ve
rab must rboadd the code
op s s a o p s s sa
ies .co . ies .co .
to navigate among athem.
llo m a llo m
we we
d! d!
You also decide to begin by storing the user and grade information in basic structs,
and to use a dummy data source in the application to test your log on functionality.
Objectives
Th Th
is is
do d oc
c um um
Aftermcompleting
ar nt this lab, you will be able to:
e ma
rt
en
tb
ta. be a.b elo
ba
lon arb ng
No rbogs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
• Navigaterizamong m av views. Ba riz av aB
ed era rbo ed era arb
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
• Create and use collections l l o of structs. llo
we we
d! d!
• Handle events.
Scenario
In this exercise, you will add navigation logic to the Grades Prototype application.
First, you will examine the window and views in the application so that you are
familiar with the existing structure of the application.
Th Th
is is
do d o
um c cu
You will
ma define
en a public event handler named LogonSuccess
ma me
n
that will be raised when
rta tb rta tb
.ba e .ba
lon logs on to the application. You will ldummy
on e
a user
No successfully
rbo gs No rbadd
o gs code to the
un sa to un sa to
au @ M @ M
Logon_Click
tho
r
event
pri
ma handler
art
aB to store the usernameaand
uth role
or
pri of thearlogged
ma ta
B
on user
ize ve arb ize ve arb
ab d r
os event. Then you will add markup ab os d r
and raise the LogonSuccess
co
pie ss
.c a. co
pie to ssthe LogonPage
.c a.
sa om sa om
llo llo
XAML code to connect we the Logon button to the Logon_Click event
d
we handler.
d
! !
Next, you will add code to the GotoLogon method to display the logon view and to
hide the other views. You will implement the Logon_Success method to handle a
successful log on by displaying the logged on views, and then you will add markup to
the MainWindow
Th
is XAML code to connect the LogonSuccess
Th
is event to the
do do
u c cu
Logon_Success
ma m en method. ma me
nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
pri art pri
You will add tho code
riz m to
av the aBMainWindow to determine whether
ori
ze
m the
a ve
user
rta is a teacher or
Ba
ed era arb d r rbo
co b os co ab sa
a student, display pie their sname
sa
s
.co in
a . the application, and display p either
i es
s the
s. co StudentsPage
.
llo m a llo m
view for teachers or the we StudentProfile view for students.
d!
we
d!
You will then add code to the StudentsPage view that catches a student name being
clicked and raises the StudentSelected event for that student and displays their
student profile.
Th Th
is is
do d oc
c um u
Finally,
ma you will e mathe m
nt run the application and verify that appropriate
en views are displayed
rt b
a.b rt tb a.b
elo elo
arb ng arb ng
for students
No
u osand teachers
a
st
o
upon a successful log
Noon.
u a@
os st
oM
na @ Ma na
uth pri rta uth pri art
ori ma Ba ori ma aB
ze ve rbo ze ve arb
dc rab dc rab os
sa
The main tasksofor pie thisssexercise
sa .c om
. are as follows: op
ies
all
s s.co
m
a.
llo ow
we ed
d! !
2. Define the LogonSuccess event and add dummy code for the Logon_Click
event
Th Th
is is
3. Add
do code
cu to display the Log On view d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
um c um
Taskm1:
a
Examine
en the window and views in themaapplication
en
rta tb rta tb
.ba elo .ba elo
No rbo ng N r b ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
1. r
Start theed MSL-TMG1
i z av B arvirtual machine if it is not already r iz running.
a v arb
era b ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
2. Start the 20483A- we SEA-DEV11-03 virtual machine and log on
d!
we as Student
d! with
the password Pa$$w0rd.
3. Start Visual Studio and open the GradesPrototype.sln solution from the
E:\Labfiles\Starter\Exercise 1 folder.
Th Th
4. Build
is
do the solution.
is
d
cu oc
me um
ma nt ma en
rta be rt a.b tb
5. Review elo for the application and
rbo MainWindow.xaml, which is the main window
.ba lon arb
No gs N ng
un sa to ou os st
@ Ma na a@ oM
willuhost
a
tho the
pri following
m rta views: uth
ori
pri
m
art
aB
riz av B a ze av arb
ed era rbo dc era
co bs sa op b s os
pie s.c . ies s.c a.
sa om all o m
llo ow
we ed
d! !
• LogonPage.xaml
• StudentProfile.xaml
• StudentsPage.xaml
Th Th
is is
do d oc
cum um
ma ent maen
rta be a.b rt tb
.ba lon elo
6. NoIn thebViews
r gsfolder, review the LogonPage.xaml. No a r bo Notice ng that this view contains
un o s t u s st
a @ o M n a @ oM
au pri art a uth pri art
text tboxes
ho
riz for
m avthe username
a Ba and password, a checko riz box mav identify
to aB the user as a
ed era rbo e d e r arb
a
teacher, and co
pie a button
sa
bs
s.c tosalog
om
. on to the application. copies bss.co osa.
llo all m
we ow
d! ed
!
7. In the Views folder, review the StudentProfile.xaml. Notice that this view
contains a Report Card that currently displays a list of dummy grades. The view
also contains a Back button and a blank space that will display the student’s
name. This view is displayed when a student logs on or when a teacher views a
Th
student’s profile. Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/55
10/25/2019 20483A - Programming in C# | Skillpipe
8. In the View folder, review the StudentsPage.xaml. Notice that this view
contains the list of students in a particular class. This view is displayed when a
teacher logs on. A teacher can click a student and the Students Profile view will
be displayed, containing the selected student’s data.
Th Th
is is
do oc d
um c um
m
Task 2:
art Define e nt the LogonSuccess event and add m art dummy en code for the
a.b b a.b tb
elo elo
Logon_Click
No arbo event ng No a rbo ng
un sa st un sa st
@ oM @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
1. In the LogonPage.xaml.cs sa
llo
om class, in the Event Members s a region,
llo
om define a
we we
d! d!
public event handler named LogonSuccess.
2. In the Logon Validation region, add an event handler for the Logon_Click
event, which takes an object parameter named sender and a
RoutedEventArgs parameter named e.
Th Th
is is
do do
3. In the cu Logon_Click event handler, add code to
m
cudo the following:
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
NoSaverbthe n g N r b gs form in the
4. un o sa usernames to and role that the user specified
o un o sa on the to relevant
au @ M a uth @ Ma
tho pri art pri rta
propertiesriz of m athe SessionContext
aB object. ori m a Ba
ed ve arb ze ve rbo
co r ab os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
5. If the user is a student, l l o set the CurrentStudent property ofwthe l l o
we ed
d! !
SessionContext object to the string Eric Gruber.
7. In the LogonPage.xaml XAML editor, locate the definition of the Log on button.
Th Th
is is
do do
8. Modify cu the definition to call the Logon_Click method
m
cu
me
when the button is clicked.
ma en ma n
rta tb rta tb
.ba elo .ba elo
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa co s os
pie s.c . p ies s.co a.
Task 3: Add codes ato llo
display
om the Log On view a llo m
we we
d! d!
handle a successful log on. This method should take an object parameter
named sender and an EventArgs parameter named e. The method should
update the display and show the data for the logged on user.
a. Parse the student name into the first name and last name by using a
Th Th
is
do regular expression. is
d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ Note: o n a @ oM
au
tho pri
m
M You
art can use the following codea uth to parse
pri
m
the art name:
riz av a B o r a aB
ed era arb ize ve arb
co bs os d co r ab os
pie s.c a. pie ss a.
sa om sa .co
llo llo m
we we
d! d!
Match matchNames = Regex.Match(SessionContext.CurrentStudent, @"([^ ]+)
([^ ]+)");
b. If a name is successfully parsed, display the first name and last name of
the student in the appropriate boxes.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/55
10/25/2019 20483A - Programming in C# | Skillpipe
5. If the user is a student, hide the btnBack button, or if the user is a teacher,
display the btnBack button.
Th Th
is is
do oc d
cum um
ma ne ma en
Task 6:rtaBuild
.ba
t band test the application
elo r ta. tb
elo
n b a ng
No r bo gs No r bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
1. Build the csolution op bsand resolve
s sa any compilation errors.cop ab
s s
os
a.
ies .co . ies .co
all m all m
ow ow
ed ed
2. Run the application. ! !
Th Th
The
is
do
Students page should look like this: is
d
cu oc
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
FIGURE 3.1: THE l l ow STUDENTS PAGE llo
we
ed d!
!
5. Click Kevin Liu and verify that the application displays the StudentProfile view.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Results:
Th
After completing this exercise, you should
Th
have updated the Grades
is is
Prototype
do
cu application to respond to user events and
do move among the application
cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 44/55
10/25/2019 20483A - Programming in C# | Skillpipe
views appropriately.
• AssessmentDate as a string
• Assessment as a string
Th Th
is is
• dComments
oc
um
as a string d oc
um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 45/55
10/25/2019 20483A - Programming in C# | Skillpipe
• StudentID as an integer
• UserName as a string
Th Th
is is
• dPassword
oc
um as a string d oc
um
ma en ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
•un TeacherID sa
@
s tas an integer
oM un os
a @
st
oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
• FirstName co
pie asbsa s.cstring
os
a. co
pie bs
s.c
os
a.
sa om sa om
llo llo
we we
d d!
• LastName as a !string
• LastName as a string
• Class as a string
Th Th
is is
do d oc
cum um
ma ent ma en
Task 2:taAdd
r unit
be tests to create and use the collections a.b rt t b of structs
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
1. Add a Unit co Test bProjectss sacalled GradesTest to the solution co and
s os
reference the
pie .co . p ies s.co a.
sa m a m
llo llo
GradesPrototype we project from it.
d!
we
d!
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta be rt a.b tb
.ba elo
Field
No rbo
lon
gs Value
N arb ng
os st
un sa to ou a@ oM
au @ Ma na
tho pri rta uth pri art
m ori ma aB
FirstName rized av
era Ba
rbo Eric ze
dc
ve arb
co b rab os
pie s s.c sa op s s a.
sa . ies .co
om all m
LastName llo
we Gruber ow
d! ed
!
UserName grubere
Password password
• TeacherTest
T
test method: To create a new teacher
T
by using the following
his his
do
information, do
and then verify that it is created correctly.
cu cu
ma m en m ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
c b os c b os
Field op
ies s s.c a. Value op
ies s s.c a.
all o m all o m
ow ow
ed ed
FirstName ! Esther !
LastName Valle
UserName vallee
Password password
Th Th
is is
do d oc
Class cum 3A um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
• tho
createGrade method: Takes an assessment, a subject, and
riz m av a Ba o riz m av a commentsaB
arb
ed era rbo e d e r ab
co bs s co os
arguments, creates p ies a.cnew
s
o
Grade
a . object from them and the p ies current s s.co date,a. and
all m all m
returns the Grade oobject. we
d!
ow
ed
!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 47/55
10/25/2019 20483A - Programming in C# | Skillpipe
Argument Value
assessment B+
subject Math
comments Good
Th Th
is is
do oc d
cum um
ma e m en
• GradeCollectionTest
rta
.ba
nt
belo
test method: To create aartcollection
a.b tb
elo
of new grades by
No rbo ng N arb ng
passing the st
sa following st
un @ o M sets of grade information o u to the
na
os createGrade
a@ oM method, and
au p a u p art
tho rim rta tho rim aB
then verify riz that aone
ed ve of Bthe
r arb collection items is createdrizcorrectly.
ed
av
era arb
co a bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
B+ Math Good
Th Th
is is
do d o
umc cu
Results:
ma After
en completing this exercise, the application
ma me will contain structs for the
n
rta tb rta tb
teacher, .bastudent, elo and grade types. .ba elo
No rbo ng No rbo ng
un s st un sa st
a @ oM @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
Exercise 3: Displaying User and Grade Information
d! d!
Scenario
In this exercise, you will first examine the dummy data source that the application
Th Th
i is
uses tos dpopulate
oc
u
the collections in this exercise. d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 48/55
10/25/2019 20483A - Programming in C# | Skillpipe
You will define a public event handler named LogonFailed that will be raised when a
user fails to log on successfully. You will add code to the Logon_Click event handler
to validate the username and password entered by the user against the Users
collection in the MainWindow window. If the user is a teacher or a student, you will
store their details in the global context and then raise the LogonSuccess event, but
if the user is not validated, you will raise the LogonFailed event.
Th Th
is is
do d oc
cum um
ma ent enma
You willahandle t b to display a message to
r t .ba bellog
on
on failure in the Logon_Failed amethod
. ba
rt
elo
No rbo gs No rbo ng
un andsathen to will add markup to the MainWindow sa st
the user au @
p
you M a
un
au @
p
XAML o M code to connect
art
tho rim rta tho rim aB
riz av B r i a
the LogonFailed ed
co
event
era toathe
bs
rbo Logon_Failed method. ed z
co
vera
bs
arb
os
pie s.c sa pie s.c a.
sa . sa
om om
llo llo
we we
d! d!
You will add code to the StudentsPage view to display students for the current
teacher, and to display the details for a student when the user clicks their name.
You will then use data binding to display the details and grades for the current
student
T
in the StudentProfile view, and to display
T
only the Back button if the user is
his his
do do
a teacher.cu
m
cu
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
un sa to un sa to
Finally, you
a uth will prun
@
r i
thearapplication
M
t
and verify that only a uth valid @
priusers Macan log on
rta
and that
ori m a aB ori m a Ba
ze ve arb ze ve
valid users cancosee only
d rab data
s os appropriate to their role.
a
d co r ab
s
rbo
sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!
The main tasks for this exercise are as follows:
Task 1: Examine the dummy data source used to populate the collections
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 49/55
10/25/2019 20483A - Programming in C# | Skillpipe
2. In the Data folder, in the DataSource.cs file, expand the Sample Data region.
3. Note how the Teachers ArrayList is populated with Teacher data, each
Thcontaining TeacherID, UserName, Password, Th FirstName, LastName, and
is is
do do
Class cu fields.
me
cu
me
ma n m a nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r b gs
4. Note
un how sa thes Students
@ t o ArrayList is populated
ou
n
withos Student
a @ to data, each
au pri M art au pri Ma
tho ma aB t h oi ma r taB
containing riz
ed a StudentID,
ve arb UserName, Password, rTeacherID, ze ve FirstName,
arb and
co ra b o d c r a b os
s s a. o s a.
LastName pfields. ies
all
s.c
om
pie
sa
s.c
om
ow l l ow
ed ed
! !
5. Note how the Grades ArrayList is populated with Grade data, each containing
a StudentID, AssessmentDate, SubjectName, Assessment, and Comments
fields.
Th Th
is is
do d oc
cum um
ma e nt ma en
tb
Task 2:rtaAdd
.ba the
be LogonFailed event
lon
rt a.b
arb
elo
ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b sa co b os
1. In the LogonPage.xaml.cs
pie
sa
s s.c
om
. file, in the Event Members pie region,
sa
s s.c define
om
a. a public
llo llo
event handler named we
d! LogonFailed. we
d!
fields from the data source, and then raise the LogonSuccess event.
6. If the credentials do not match any teachers or students, raise the LogonFailed
event.
Th Th
is is
do d oc
Taskm3: Add c
um the Logon_Failed event handler um
eart nt m art en
a.b b a.b tb
elo elo
No arb ng N arb ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
1. In the rMainWindow.xaml.cs
ize av
era B arb class, in the Event Handlers
r ized
a vera region, arb add an event
dc bs o c b os
op s.c s a. o pie parameter s s.c a.
handler for the ies Logon_Failed
all om event that takes an object sa om named
ow l l ow
sender and an EventArgs ed parameter named e. ed
! !
6. In the case statement for a student, add code to display the student name in
txtName text box at the top of the page.
7. In the case statement for a teacher, add code to display the teacher name in
Ththe banner at the top of the page. Th
is is
do do
cu cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
Task 4: Display e d c therastudents
op b
rbo for the current teacher d
sa
e
c op
e rab rbo
sa
ies ss . ies ss .
.co .co
all m all m
ow ow
ed ed
! !
1. In StudentsPage.xaml XAML editor, locate the ItemsControl named list and
note how data binding is used to display the name of each student.
Page list to identify which student’s data to display in the Student Profile
page.
2. In the StudentsPage.xaml.cs code, locate the Refresh method, and then add
code to do the following:
Th Th
is is
d
a. cuFind all the students for the current teacher
o do and store them in a new
cu
ma me m me
rta ArrayListn tb a r nt
.ba elo object. t a.b
a
be
lon
No rbo ng N r b gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho t h rta control.
b. Bind riz
ed
the m avcollection a Ba to the ItemsSource property o riz
ed
ofm the
av list Ba
era rbo era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
c. Display the l l owclass name.
ed
l l ow
ed
! !
d. Locate the Student_Click event and then add code to do the following:
e. Identify which student was clicked by using the Tag property of the button.
Th Th
is is
d
Task 5: oSet do
cu the DataContext for the page cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
1. In the t ho StudentProfile.xaml.cs
riz
r im
av
r ta
B
file, in the Refresh t ho method,
r
r im
a
add
rta code to display
Ba
ed era arb ize ve
o dc rab rbo
the detailsopof c
iesthe scurrent
b
s.c sastudent in the studentNameopStackPanel ss sobject
a. and to
. i e sa . c
all om om
ow button only if the user is a teacher. llo
display the Back ed we
d!
!
3. Modify the definition to bind the Text property to the FirstName field.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 52/55
10/25/2019 20483A - Programming in C# | Skillpipe
5. Modify the definition to bind the Text property to the LastName field.
6. In the StudentProfile.xaml.cs file, at the end of the Refresh method, add code
to iterate the grades for the current student in DataSource.Grades list and then
Thdisplay them in the studentGrades controlT by using data binding.
his
is
do do
cu cu
ma me ma me
rta nt rta nt
.ba be .ba be
lon lon
No rbo gs No rbo gs
un sa to un sa to
au @ Ma au @ Ma
tho pri r tho pri rta
Task 6: Build riz andavtest tathe
m Ba application riz m av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!
1. Build the solution and resolve any compilation errors.
3. Log on as parkerd with a password of password and verify that the Logon
ThFailed message box appears. Th
is is
do do
cu cu
ma m en ma me
rta t r nt
4. Log.baon as belvallee with a password of password t a .ba andbeverify that the Students
on lon
No rbo gs No rbo gs
un sa to un sa to
page au appears.
tho
@
pri Ma
rta
au
tho
@
pri Ma
rta
riz m av Ba r m a Ba
ed era ize ve
rbo d r ab rbo
co b s s a co s sa
5. Click Kevin eLiu, p s p s
i s a verify .co
m that the Student Profile page appears,
. i es
a
.and
co
m then. log off.
llo llo
we we
d! d!
6. Log on as grubere with a password of password and verify that the Student
Profile page appears.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be completing this exercise, only valida.users rt tb
Results: .ba After
r
lon ba
r
ewill
lon be able to log on to
No bo gs No bo gs
the application
un s a@ ando M t they will see only data appropriate
un s a@ theirtorole.
to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
we we
d! d!
Module Review
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 53/55
10/25/2019 20483A - Programming in C# | Skillpipe
In this module, you have learned how to implement structs and enums, organize data
into collections, and work with events and delegates.
Question
Th
is
Th
is
do oc d
cum um
ma e
nt m art You en
rta to create
You want b a string property named CountryOfOrigin.a.b twant
be to be able to read the
.ba elo lon
No rbo ng N arb gs
property
un value safrom any s t code, but you should only be able o u to write os to the to
@ o M n a @ Ma
au pri art au pri
tho m a t h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
property from within co the containing
b s s a. struct. How should you declare c
the
o property?
b s sa
pie s.c pie s.c .
sa om sa om
llo llo
we we
d! d!
Select the correct answer.
Question
You want to create a collection to store coffee recipes. You must be able to retrieve
eachThcoffee
i recipe by providing the name of the coffee. TBoth
hi the name of the coffee
sd sd
oc oc
um um
ma ent ma en
r
and thetacoffee
.ba be
recipe
lon will be stored as strings. You also need a.b to bet bable
rt elo to retrieve
No rbo gs No arb ng
un sa t u os st
@ o M n a @ oM
au a uth
tho bypproviding
coffee recipes rim art
an integer index. Which collection class
pri
m
should
art
riz av a Ba o riz av you a Buse?
arb
ed era rbo e d e r ab
co bs sa co s os
pie s.c . p ies s.co a.
sa om a m
llo llo
w we
Select the correct answer. ed! d!
ArrayList
Hashtable
SortedList
Th Th
is is
do
NameValueCollection d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 54/55
10/25/2019 20483A - Programming in C# | Skillpipe
Question
StringDictionary
Th Th
is is
do d oc
Question
m
um c
ma
um
art en en
a.b t b a.b rt tb
elo elo
No arb ng N arb ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
You are riz creating
ed
av
era a method
B arb to handle an event rnamed
ized
a vOutOfBeans.
era arb The
o os
delegate cfor op thebsevent
ies s .co
sa
is . as follows: public delegate co
p void
ies
bs
s .co a.
all m all m
OutOfBeansHandler(Coffee ow coffee, EventArgs args); Which ow
ed ed of the
! !
following methods should you use to subscribe to the event?
Question
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 55/55
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
Contents:
is
do
cu
is
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho Module pri tho p rim art
av Overview
m rta aB
riz Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
Lesson 1: Creating llo Classes
we
llo
we
d! d!
d! d!
Classes enable you to create your own custom, self-contained, and reusable types.
Interfaces enable you to define a set of inputs and outputs that classes must
implement in order to ensure compatibility with consumers of the classes. In this
module,
Th
i
you will learn how to use interfaces andThclasses
i
to define and create your
sd sd
oc o
own mcustom, u me reusable types. You will also learn m howcuto mecreate and use enumerable,
art n tb art nt
a.b elo a . be
type-safe
No acollections
rbo ng of any type. No
b arb lon
gs
un s s t un o s to
a@ oM a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
Objectives co
pie ss
.c
sa
. op
i e
ss
. c
sa
.
sa om sa om
llo llo
we we
After completing this module, d! you will be able to: d!
In Visual C#, you can define your own custom types by creating classes. As a
Th Th
programming
is
d construct, the class is central to object-oriented
is
d programming in Visual
oc oc
um um
C#. It aenables
m
rta
e nt you to encapsulate the behaviors and
b
mart characteristics
en
tb of any logical
.ba elo a.b elo
rbo ng a rbo ng
entity
No in a reusable
un sa s tand extensible way.
oM
No
un sa st
oM
au @ au @
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
co bs o sa co bs os
In this lesson, you p s
ieswill learn how to create, use, and test p
classes ins .cyour a.
om own
.co . ies
all m all
ow ow
applications. ed ed
! !
Lesson Objectives
After completing this lesson, you will be able to:
Th Th
is is
do d oc
c
um um
• Create
ma classes.
en ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
u s st un os st
• Create
na objects a o instantiating a oM
pri by M classes.
uth @ au @
art tho p rim art
ori m av aB riz av aB
ze era arb ed era arb
dc b os co b os
op s a. s
pie are sinstantiated. a.
• Use constructors ies to set
all
s.c values
o m
or to run logic when classes sa .co
m
ow llo
ed we
! d!
• Explain the difference between reference types and value types.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/71
10/25/2019 20483A - Programming in C# | Skillpipe
In Visual C#, a class is a programming construct that you can use to define your own
custom types. When you create a class, you are effectively creating a blueprint for
the type. The class defines the behaviors and characteristics, or class members,
which are shared by all instances of the class. You represent these behaviors and
characteristics by defining methods, fields, properties, and events within your class.
Th Th
sd i i
For example,
oc
u
suppose you create a class named sDrinksMachine.
do
cu You would use
ma me ma me
nt nt
fields and
r t a.b propertiesbelo to define the characteristics ofa.ba drinks
r t be machine, such as the
lon
No arbo ng N a r b gs
s st ou os to
make, model,
una
uth
a age,
@
pri
and
o M art
service interval of the machine.
na
uth
You
a @
pri
would Ma create methods to
ori ma aB ori ma rta
represent the ze things ve that aardrinks machine can do, suchzeas make ve anBespressoarb or
dc rab bo dc rab os
op s s sa op s s a
ies .co . ies .co .
make a cappuccino. all Finally,
ow
m you would define events to represent all
ow
actions
m that might
ed ed
require your attention, such ! as replacing coffee beans when the machine ! has run out
of coffee beans.
You use the class keyword to declare a class, as shown in the following example:
Th Th
is is
do d
Declaring
um a Class
c oc
um
ma en ma en
rta tb rt a.b tb
.ba elo elo
ng arb ng
Declaring
No
un
rbao Class
sa st
oM
No
un os
a
st
oM
au @ au @
tho prim art tho p rim art
riz av aB riz av aB
ed era arb ed era arb
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
public class DrinksMachine we we
d! d!
{
// Methods, fields, properties, and events go here.
}
Th Th
is is
do do
The class cu keyword is preceded by an access modifier,
m
cu such as public in the above
me
ma en ma nt
rta tb r t a be
example,
No
.bawhichelospecifies from where you can use the
rbo ng No
.ba type.
rbo
lonYou can use the following
gs
u s s t un s to
a@ oM a@
accessnmodifiers
au
tho pri in
ma
yourart class declarations: a uth pri
ma
Ma
rta
riz aB ori Ba
ed ve a rbo ze ve rbo
co rab dc rab
pie ss sa op ss sa
sa .c . i e sa . c .
om om
llo llo
Access modifier wedDescription !
we
d!
public The type is available to code running in any assembly that references the
assembly in which the class is contained.
internal The type is available to any code within the same assembly, but not available
to code in another assembly. This is the default value if you do not specify an
Th Th
is access modifier. is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/71
10/25/2019 20483A - Programming in C# | Skillpipe
private The type is only available to code within the class that contains it. You can
only use the private access modifier with nested classes.
Within your class, you can add methods, fields, properties, and events
Th Th
is is
do d oc
cum um
Adding
rta Members
mant
b
to a Class
e ma
rt a.b
en
tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
oM a oM
to defineautthe
ho
behaviors
@
prim artand characteristics of your atype,
uth asprshown
@
arin the following
aB ori ima ta
riz av arb ze ve Ba
example: ed era dc rab rbo
co bs os op s sa
pie s.c a. ies s.co .
sa om all m
llo ow
we ed
d! !
Defining Class Members
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/71
10/25/2019 20483A - Programming in C# | Skillpipe
Instantiating Classes
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b rt
a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
A class is just a blueprint sa for
om a type. To use the behaviors and sa characteristics
om that you
llo llo
we we
define within a class, you d! need to create instances of the class. And!instance of a
To create a new instance of a class, you use the new keyword, as shown in the
following example:
Th Th
is is
do d oc
cum um
ma e nt ma en
Instantiating
rta
.b bae Class
l
rt a.b
elo
tb
arb on ng arb
No o gst No st os
un sa o u na a oM
au @ Ma u @
tho prim rta tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
DrinksMachine dm s all = new o m DrinksMachine(); s all o m
ow ow
ed ed
! !
When you instantiate a class in this way, you are actually doing two things:
• You are creating a new object in memory based on the DrinksMachine type.
Th Th
is is
do oc d
• You
m
areumcreating
e
an object reference named dm
c
m
that
um refers to the new
e
ar nt art nt
ta. be a.b be
DrinksMachine
N
ba
rb
lon object.
g No arb lon
gs
ou os st un os to
na a@ oM a@ Ma
uth pri art au pri
ori ma aB tho ma rta
ze ve arb riz ve Ba
dc rab ed rab rbo
op s os co ss sa
ies s .co a. pie . .
sa com
a m
When you create your llo object reference,
we instead of explicitly specifying
llo
we the
d! d!
DrinksMachine type, you can allow the compiler to deduce the type of the object at
compile time. This is known as type inference. To use type inference, you create your
object reference by using the var keyword, as shown in the following example:
Instantiating
Th a Class by Using Type Inference
Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/71
10/25/2019 20483A - Programming in C# | Skillpipe
In this case, the compiler does not know in advance the type of the dm variable.
When the dm variable is initialized as a reference to a DrinksMachine object, the
compiler deduces that the type of dm is DrinksMachine. Using type inference in this
Th Th
is
way causes is
no change in how your application runs;
do do it is simply a shortcut for you to
c um c um
avoidmatyping
rta
.
en
the e
ma
rta
.
en
t b class name twice. In some circumstances, t b type inference can make
e
ba lon ba lon
N bo r g
s t read, while in other circumstances bo smake N r g
your ocode
un
a
easier
sa
@ to oM ou
n a
itsamay
@ to
M
your code more
uth pri art uth pri art
aB m a m
confusing. oAs
riz a general
ed
av
era rule, ori
arb consider using type inference
ze
d when
av
era theBatype
rb of variable
co bs os co bs os
pie s.c a. pie s.c a.
is absolutely clear. sa
llo
om sa
llo
o m
we we
d! d !
After you have instantiated your object, you can use any of the members—methods,
fields, properties, and events—that you defined within the class, as shown in the
following example:
Th Th
i is
UsingsObject
do
cu Members d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
r m a Ba riz av aB
var dm = iznew ed ve
DrinksMachine();
rab rbo ed era arb
co s sa co b s os
pie s.c . pie s.c a.
dm.Make = "Fourth sa om
Coffee"; sa om
llo llo
we we
d! d!
dm.Model = "Beancrusher 3000";
dm.Age = 2;
dm.MakeEspresso();
This Tapproach
his
d
Th variable is known as dot notation.
to calling members on an instanceis
d
oc oc
u
me variable name, followed by a period, me u
You type
ma
r
thent ma followed
r nt by the member name. The
ta. be ta. be
arb onb l arb on b l
IntelliSense
No
u ofeature
s
gs in Visual Studio will promptNyou
t o u
witho s member
gs
t
names when you
na a@ oM na a@ oM
uth pri art uth pri art
type a period
ori after
z
maa variable.
v
aB ori
ze
ma
ve
aB
ed era arb dc rab arb
co bs os op s os
pie s.c a. ies s.co a.
sa om all m
llo ow
we
Using Constructors d! ed
!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.brt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
In the previous
au
tho topics,
prim
M ayou
rta might have noticed that athe
u tho syntax p rim for ainstantiating
rta a class
riz av B arb r iz a v B arb
ed
—for example, cnew
op
era
DrinksMachine()—looks
bs os
a
similar to ethe d c syntax
op
era
bs for calling
os
a.
a
ies s .co . ies s .co
all m m
method. This is because ow when you instantiate a class, you arealactually low calling a
ed ed
! !
special method called a constructor. A constructor is a method in the class that has
the same name as the class.
Constructors are often used to specify initial or default values for data members
within
Th the new object, as shown by the followingThexample:
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.a elo
Adding
No
baConstructor
rbo
lon
gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
public class DrinksMachine l l o llo
we we
d! d!
{
public int Age { get; set; }
public DrinksMachine()
{
Th Age = 0; Th
is is
do d oc
} cum um
ma e nt ma en
rta be a.b rt tb
} N .ba lon elo
r bo gs No a r bo ng
ou s t un s st
na a@ oM a @ oM
uth pri art a uth pri art
ori ma aB ori ma aB
ze ve a rbo ze ve arb
dc rab dc rab os
op s s sa o p s s a.
.
A constructor thatiestakes all
.co
nom parameters is known as the default ies
all
.co
constructor.
m This
ow ow
ed ed
constructor is called whenever ! someone instantiates your class without ! providing any
arguments. If you do not include a constructor in your class, the Visual C# compiler
will automatically add an empty public default constructor to your compiled class.
In many cases, it is useful for consumers of your class to be able to specify initial
Th Th
i i
valuess for
cu
sd
do data members when the class is instantiated.
oc
u
For example, when someone
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/71
10/25/2019 20483A - Programming in C# | Skillpipe
creates a new instance of DrinksMachine, it might be useful if they can specify the
make and model of the machine at the same time. Your class can include multiple
constructors with different signatures that enable consumers to provide different
combinations of information when they instantiate your class.
Consumers can use any of the constructors to create instances of your class,
depending on the information that is available to them at the time. For example:
Th Th
Calling
is Constructors
do
is
d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c um um
Reference
rta
.
nt Types and Value Types
ma
be
e ma
rt a.b
en
tb
elo
ba lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do do
uc cu
Now mthat
art
you
m en know how to create and instantiate maclasses, me
nt you will learn about the
a.b t be rta be
l on . b lon
differences
No arbbetween
o g s classes and structs. N o
arb
o gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
A struct is a value pie type.s.This
s definition
a applies to built-in structp types, s s such sa as int and
sa co . i es . co .
llo m a llo m
bool, as well as to structs we
d! that you define yourself. A value type contains
we
d! its data
directly. In other words, when you interact with a value type, you are interacting
directly with the data it contains in memory. By contrast, a class defines a reference
type. When you create an object by instantiating a class, you are creating a reference
type. The object itself is stored in memory, but you interact with the object through an
object
Th reference. All the object reference does is
is
Th point to the object in memory.
is
do do
c um cu
ma e me
ma
rta nt nt
rt
.ba belo a .ba be
ng lon
No rbo s No rbo gs
Note:
un
au
Most
s a@ of othe t
M
built-in types in Visual C#,unasuch aas s
@ int, tobool, byte, and
Ma
tho pri art uth pri rta
char,riare ze value
ma
ve types.
aB
a For more information about ori built-in
ze
ma types,
ve Ba see the Built-
dc rab rbo dc rab rbo
In Types Table op
ies (C# ss Reference)
.co
sa
. page at http://go.microsoft.com/fwlink/?
op
ies ss
.co
sa
.
all m all m
LinkID=267800.we o o we
d! d!
Value types and reference types behave differently. If you copy a value type from one
variable to another, you are copying the data that your variable contains and creating
a new instance of that data in memory. If you copy an object reference from one
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/71
10/25/2019 20483A - Programming in C# | Skillpipe
variable to another, all you are doing is copying the object reference. You are not
creating a second object in memory. Both variables will point to the same object.
Boxing
Th Th
is is
do d oc
um c um
int mi
art = 100; en
tb
ma en
tb
a.b elo rt a.b elo
a arb
No
object orbo=s i;ngs t No os
ng
st
un a@ oM un a @ oM
au pri art au p art
tho m aB tho rim aB
riz av arb riz av arb
ed era ed era
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
The boxing process llis ow implicit. When
ed
you assign an object reference llo
we to a value type,
! d!
the Visual C# compiler automatically creates an object to wrap the value and stores it
in memory. If you copy the object reference, the copy will point to the same object
wrapper in memory.
The Tprocess
h of converting a reference type to aTvalue
h type is called unboxing. Unlike
is is
oc d o d
the boxing
m
umprocess, to unbox a value type you must cexplicitly
e m
um
e
cast the variable back
art nt art nt
a.b be a.b be
to itsN original
arb type: lon
gs No arb lon
gs
ou os to un os to
na a@ Ma au a@ Ma
uth pri rta tho pri rta
ori ma Ba riz ma Ba
ze ve r ed ve rbo
Unboxing d copi rabss. bosa. co
pie
rab
ss
.
sa
.
es co sa com
all m llo
ow we
ed d!
!
int j;
j = (int)o;
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/71
10/25/2019 20483A - Programming in C# | Skillpipe
7. In the New Project dialog box, in the Templates list, click Visual C#, and then
in the Project Type list, click Console Application.
Th Th
is is
do do
11. Immediately
cu
me below the code you just added, addcu the following code:
m
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/71
10/25/2019 20483A - Programming in C# | Skillpipe
class MyClass
{
public int Contents = 0;
}
Th Th
is is
do d oc
cum um
ma e nt ma en
r rt tb
12. Within
t a.b
arb
the beloProgram class, within the Main method, a.b
arb
add
elo the following code:
No ng N ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co struct1 bs o co bs os
MyStruct pie s.c = sanew . MyStruct(); pie s.c a.
sa om sa om
llo llo
MyStruct struct2 we = struct1; we
d! d!
struct2.Contents = 100;
MyClass class1 = new MyClass();
MyClass class2 = class1;
class2.Contents = 100;
Th Console.WriteLine("Value types: {0}, Th
is is {1}", struct1.Contents,
do do
cu cu
m
mastruct2.Contents);
en ma me
rta t r nt
.ba belo t a .ba be
n lon
No Console.WriteLine("Reference
rbo gs types:
No {0}, rbo {1}", gs class1.Contents,
un sa to un sa to
au @ M a uth @ Ma
tho
class2.Contents); pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
13. On the Debug menu, click Start without Debugging. The console window
shows the following output:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e en ma
rta b a.b tb rt
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
In someaucases,
tho pyou
rim may
M a rta want to create a class purelyau to encapsulate
tho p rim art some useful
riz av B r a aB
arb iz v arb
functionality, eratherdc
op
era
thanbs to represent
os
a
an instance of anything. ed
co
p
era
For bsexample, os
a.
suppose
ies s .co . ies s .co
all a set m all m
you wanted to create ow of methods that convert imperial weights ow and measures to
ed ed
! !
metric weights and measures, and vice versa. It would not make sense if you had to
instantiate a class in order to use these methods, because you do not need to store
or retrieve any instance-specific data. In fact, the concept of an instance is
meaningless in this case.
Th Th
is is
do oc d
In scenarios
m
um like this, you can create a static class. A
e
c
m
static
um
e
class is a class that
ar nt ar nt
ta.
cannot
N
be rb
be
ba instantiated.
lon
g
To create a static class,Nyouta.buse be
arb thelonstatic
g
keyword. Any
ou os st ou os st
na @ the class a o na @ as shown a o
members
uthwithinpri
m
Ma
rta must also use the static keyword,
uth pri
m
Ma
rta in the
ori av Ba ori av Ba
ed z e rbo ze era rbo
following example:
co
p
rab
ss sa
d co
pie bs
s.c sa
ies .co . sa .
all m o m
ow llo
ed we
! d !
Static Classes
return pounds;
}
}
To call a method on a static class, you call the method on the class name itself
Th of on an instance name, as shown by the
instead Th following example:
is is
d oc d oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
r arb ng
Calling
N o u Methods bos
a
gon
s t a Static Class
oM
No
un os
a
st
oM
na @ au @
uth pri art tho p rim art
ori ma aB riz av aB
ze ve arb ed era arb
dc rab os co bs os
op s s a. pie s.c a.
ies .co sa om
all m llo
ow we
double weightInKilos ed
! = 80; d!
Static
T
Members Th
his is
do do
um c cu
Non-static
ma classes
en can include static members. m This
a
ismeuseful
nt when some behaviors
rta t b r t a be
.ba elo .ba l on
and Ncharacteristics
ou rbo
s
ng relate to the instance (instance
st No members), rbo
s
gs while some behaviors
na a @ o u na a @ to
uth pri M art to the type itself (static members). uth pri Methods, Ma
and characteristics
ori m a relate aB ori m a
rta
Ba
fields,
ze ve arb ze ve r
dc rab o d co r ab b os
properties, and oevents pie scan
s.c allsabe. declared static. Static properties pie ssare often
.co a. used to
sa om sa m
llo llo
return data that is common we
d! to all instances, or to keep track of how we many instances of
d!
a class have been created. Static methods are often used to provide utilities that
relate to the type in some way, such as comparison functions.
To declare a static member you use the static keyword before the return type of the
Th
member, Th
is as shown by the following example: is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
arb ng
Static
No Members
un
rbo
s a@
in
gs Non-static Classes
to
No
un os
a
st
oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
om om
llo llo
public class DrinksMachine we we
d! d!
{
public int Age { get; set; }
public string Make { get; set; }
public string Model { get; set; }
Tpublic
his Th
static int CountDrinksMachines()
is
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/71
10/25/2019 20483A - Programming in C# | Skillpipe
{
// Add method logic here.
}
}
Th
Regardless Th exist, there is only ever one
of how many instances of your class
is is
d oc d oc
u u
ma ofma
instance me
en static member. You do not need tominstantiate
ar nt the class in order to use
r tta. be ta. be
ba lon ba lon
statico members.
N
un
r bos You
g s t access static members through N ou the
r b os class gs name rather
to
than the
a @ o M n a @ Ma
au pri art au pri
t
instance name, h ori asma shown a B by the following example: or t h ma rta
ze ve a ize ve Ba
dc rab rbo dc rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
Access Static Members ed
!
ed
!
Th Th
is is
do d oc
c um um
ma ent ma en
Testing
N
rta
.ba Classes
r
be
lon
g No
rt a.b
arb
tb
elo
ng
ou bo st os st
na sa oM un a oM
uth @ au @
pri art tho p rim art
ori m av aB riz av aB
ze era arb ed era arb
dc b os co b os
op s s.c a. pie s s.c a.
ies o sa om
all m llo
ow we
ed d!
!
Th Th
is is
do ocd
c um um
ma e ma en
Classes rta oftent brepresent
.ba
n
elo self-contained units of functionality.
r ta. tb
elo In many cases, you will
n b a ng
N r b gs No r bo s tyou integrate them
un testothe
want oto sa functionality
@ t o M
of your classes in isolation
u n sbefore
a @ oM
au pri art a uth pri art
tho m a o m aB
with other classesriz
ed
ain
ve yourBaapplications.
rab rb
riz
e d
av
e r ab
arb
co ss os co s os
pie .co a . p ies s.co a.
sa m a m
llo llo
we we
d! d!
To test functionality in isolation, you create a unit test. A unit test presents the code
under test with known inputs, performs an action on the code under test (for example
by calling a method), and then verifies that the outputs of the operation are as
expected. In this way, the unit test represents a contract that your code must fulfill.
However, when you change the implementation of a class or method, the unit test
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/71
10/25/2019 20483A - Programming in C# | Skillpipe
ensures that your code always returns particular outputs in response to particular
inputs.
For example, consider the case where you create a simple class to represent a
customer. To help you target your marketing efforts, the Customer class includes a
GetAge method that returns the current age of the customer in years:
Th Th
is is
do d oc
c um um
ma nt e ma en
rta rt tb
Class Under
.ba Test
be
lon a.b
arb
elo
No rbo gs No ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
public class Customer s a o m sa om
llo llo
we we
d! d!
{
public DateTime DateOfBirth { get; set; }
public int GetAge()
{
TimeSpan difference = DateTime.Now.Subtract(DateOfBirth);
Th Th
is is
doint ageInYears = (int)(difference.Days do / 365.25);
cu cu
ma m en ma me
rta// Note: tb nt
.ba elo converting a double to anrta.int ba
be
rounds
lon down to the
No rbo n gs No rbo gs
un
nearest sa to un sa to
au whole @
pri
number.
Ma au @
pri Ma
tho m rta tho m rta
riz av Ba r ize a ve Ba
return ed ageInYears;
era rbo d r ab rbo
co b s s a co s sa
pie s.c . pie s.c .
} sa om sa om
llo llo
we we
d! d!
}
In this case, you might want to create a unit test that ensures the GetAge method
behaves as expected. As such, your test method needs to instantiate the Customer
Th T
class, isspecify a date of birth, and then verify thathithe
d s d GetAge method returns the
oc oc
u u
ma agemein
correct me
nt years. Depending on the unit test mframework
art nt you use, your test method
rt b
a.b elo b a.b elo
No lookarbsomething
might os
ng
s t like the following: No arb
os
ng
st
u
na a@ o Ma un a @ oM
uth pri au pri art
ori ma rta tho m aB
ze ve Ba riz av arb
dc rab rbo ed era
op ss sa co bs os
Example Test Method ies .co . pie s.c a.
all m sa om
ow llo
ed we
! d!
[TestMethod]
public void TestGetAge()
{
Th Th
//doArrange.
is is
d
cu oc
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 16/71
10/25/2019 20483A - Programming in C# | Skillpipe
• Act. In this phase, you perform the action that you want to test.
• Assert. In this phase, you verify the results of the action. If the results were not as
expected, the test fails.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.brt tb
.ba lon elo
r a r ng
TheNAssert.IsTrue
ou
na
bo
s a@
gs
method
t oM is part of the No
Microsoftun Unit
a
bo
Test
s a @
st
Framework
oM that is
uth pri art uth pri art
ma aB ma aB
included inorVisual
ize
dc
Studio
ve
rab
2012.
arb This particular methodorthrows ize
d
van
era exception
arb if the
op s os co bs os
ies does.cnots a . p ies s a .
specified condition all om evaluate to true. However, the concepts all
.co described
m here
ow ow
are common to all unit etesting d! frameworks. ed
!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/71
10/25/2019 20483A - Programming in C# | Skillpipe
• Create interfaces.
Th Th
sd i sd i
• Create
oc classes that implement a single interface.
u
oc
u
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
• Create
N ou classes
r bos
a@
gsthat implement multiple
to interfaces.
N ou os
a@
gs
to
na Ma na Ma
uth pri rta uth pri rta
ori m a Ba ori m a Ba
ze ve rbo ze ve rbo
• Implement the d co IComparable
pie
rab
s sa interface.
dc
op
rab
s sa
s.c . ies s.c .
sa om all om
llo ow
we ed
• Implement the IComparer d! interface. !
Introducing Interfaces
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
In Visual C#, an interface specifies a set of characteristics and behaviors; it does this
by defining methods, properties, events, and indexers. The interface itself does not
Th Th
specify
is how these members are implemented. Instead,
do
is
do classes can implement the
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/71
10/25/2019 20483A - Programming in C# | Skillpipe
interface and provide their own implementations of the interface members. You can
think of an interface as a contract. By implementing a particular interface, a class
guarantees to consumers that it will provide specific functionality through specific
members, even though the actual implementation is not part of the contract.
For example, suppose that you want to develop a loyalty card scheme for Fourth
Th Th
i i
Coffee.s dYou
oc
u
sd
might start by creating an interface named
oc
u
ILoyaltyCardHolder that
ma me ma me
nt nt
defines:a.b
r t belo r t a.b be
lon
No arbo ng N a r b gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho m a t h o m rta
riz av Ba riz av Ba
• A read-onlyd cinteger
e
op
e rab property rbo
s
named TotalPoints. e dc
o
e rab rbo
sa
ies s s a . p ies s s .
.co .co
all m all m
ow ow
• A method named AddPoints ed that accepts a decimal argument.ed!
!
The Tfollowing
h example shows an interface that defines
Th one read-only property and
is is
do d oc
two methods:
ma
um
en
c
ma
um
en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
Defining au an Interfacep art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
public interface ILoyaltyCardHolder
{
int TotalPoints { get; }
int AddPoints(decimal transactionValue);
Tvoid
his ResetPoints(); Th
is
do d oc
} cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un s a@ to un a oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
Note: Programmingco
pie
rab
ss convention
sa dictates that all interface co
pie
names
bs
s.c
should
os
a.
begin
.c .
with an "I". s allow om sa
llo
we
om
ed d!
!
Notice that the methods in the interface do not include method bodies. Similarly, the
properties in the interface indicate which accessors to include but do not provide any
implementation details. The interface simply states that any implementing class must
hisT his T
include dand
o provide an implementation for the three do members. The creator of the
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/71
10/25/2019 20483A - Programming in C# | Skillpipe
implementing class can choose how the methods are implemented. For example, any
implementation of the AddPoints method will accept a decimal argument (the cash
value of the customer transaction) and return an integer (the number of points
added). The class developer could implement this method in a variety of ways. For
example, an implementation of the AddPoints method could:
Th Th
is is
• Calculated do
o cu the number of points to add by multiplying cu the transaction value by a
ma me m me
r n t a r nt
fixedaamount.
t .ba belo t a.b
a
be
lon
No rbo ng N r b gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho t h rta
• Get the number riz
ed
m of
av points
a Ba to add by calling a service. o riz
ed
m av Ba
era rbo era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
• Calculate the number l l ow
ed
of points to add by using additional factors, l l ow
ed
such as the
! !
location of the loyalty cardholder.
T}h Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
The syntax for defining we an interface
d! is similar to the syntax for defining we
d! a class.
You use the interface keyword to declare an interface, as shown by the following
example:
Th Th
Declaring
is
d an Interface is
d
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au p au pri art
t ho
public interface r im rta tho m aB
riz av IBeverage Ba riz av arb
ed era rbo ed era
co b ss sa co bs os
{ pie . . pie s.c a.
sa c om sa om
llo llo
// Methods, properties, we events, and we
d! d!
indexers go here.
}
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/71
10/25/2019 20483A - Programming in C# | Skillpipe
• ToThdefine
i
a method, you specify the name of Tthe
hi method, the return type, and any
sd sd
oc oc
parameters:
ma
um
en ma
um
en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un osst
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
int GetServingTemperature(bool
riz
ed
av
era arb includesMilk); riz
ed
av
era arb
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
• To define a property, you specify the name of the property, the type of the property,
and the property accessors:
• To define an indexer, you specify the return type and the accessors:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/71
10/25/2019 20483A - Programming in C# | Skillpipe
Interface members do not include access modifiers. The purpose of the interface
is to define the members that an implementing class should expose to consumers,
so that all interface members are public. Interfaces cannot include members that
Th Th
is to the internal functionality of a class, such
relate is as fields, constants, operators,
do do
c um c um
ma en ma en
and rconstructors.
ta. tb
e rt a.b tb
elo
ba lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
Implementing Interfaces sa
llo
we
om sa
llo
we
om
d! d!
Th Th
is is
do d oc
c um um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s s c o b s os
a a.
To create a classpiethat s.c
s a implements om
. an interface, you add a colon pie s.c
s a followed om by the name
llo llo
we we
of the interface to your class d! declaration. d!
The following example shows how to create a class that implements the IBeverage
interface:
Th Th
is
Declaring is
do a Class that Implements an Interface do
c um c um
ma en ma en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
un s st un os st
a @ oM a @ oM
au pri art au pri art
tho m aB tho m aB
public class riz av
Coffee :arbIBeverage riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
{ sa om sa om
llo llo
we we
} d! d!
Within your class, you must provide an implementation for every member of the
interface. Your class can include additional members that are not defined by the
interface.
Th
is In fact, most classes will include additional
Th
is members, because generally
do do
c um cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/71
10/25/2019 20483A - Programming in C# | Skillpipe
the class extends the interface. However, you cannot omit any interface members
from the implementing class. The way you implement the interface members does
not matter, as long as your implementations have the same signatures (that is, the
same names, types, return types, and parameters) as the member definitions in the
interface.
Th Th
sd i sd i
The following
oc
u
example shows a trivial interface, together
oc
u
with a class that implements
ma me ma me
nt nt
the interface:
r t a.b be
lon
rt a.b be
lon
No arbo gs No arb gs
un sa to un os to
au @ Ma au a@ Ma
tho pri rta tho pri rta
riz m av Ba riz m av Ba
Implementing e d can Interface
e rab rbo
sa
ed
co
era
b
rbo
sa
op s s . pie s s.c .
ies .co sa om
all m llo
ow we
ed d!
!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/71
10/25/2019 20483A - Programming in C# | Skillpipe
Interface Polymorphism
As it relates to interfaces, polymorphism states that you can represent an instance of
a class as an instance of any interface that the class implements. Interface
polymorphism can help to increase the flexibility and modularity of your code.
Suppose you have several classes that implement the IBeverage interface, such as
Coffee,
Th Tea, Juice, and so on. You can write code
is
Th that works with any of these
is
do do
cu cu
classes
ma asminstances
en of IBeverage, without knowing
ma any
me details of the implementing
n
rta tb rta tb
.b lon e .ba loninstances without e
class.
No Forarexample,
bo gs you can build a collection of
No IBeverage
rbo gs
un sa to un sa to
@ M @ M
needingauto
thoknow
r
pri the details
ma
art au
a B of every class that implements
tho
r
prIBeverage.
im
a
art
aB
ize ve arb ize ve arb
dc rab os d co ra bs os
op s s a. pie s.c a.
ies .co sa o
all m low l m
ow
For example, If the Coffee ed
!
class implements the IBeverage interface,
ed
!
you can
represent a new Coffee object as an instance of Coffee or an instance of IBeverage:
Th Th
is is
do d oc
um c um
Coffee
ma coffee1
en = new Coffee(); ma en
rta tb rt a.b tb
.ba elo elo
IBeverage
No rbo coffee2 ng = new Coffee(); No arb ng
un sa st un os st
@ oM a @ oM
au pri art au p art
tho ma aB tho rim aB
riz v arb riz av arb
ed era ed era
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
You can use an implicit llo cast to convert to an
we interface type, because llo
we you know that
d! d!
the class must include all the interface members.
Th Th
is is
do do
IBeverage cu beverage = coffee1; cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
You must use r i ze an explicit
dc
ve
rab
cast
a rbo to convert from an interface ze type
dc
veto
rab
a derived
Ba
rbo class
op s s sa o p s s sa
. .
type, as the classiesmay .co
all include m members that are not definediesinal the .cinterface. om
ow low
ed ed
! !
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
In many cases, you will want to create classes that implement more than one
interface. For example, you might want to:
Th Th
is is
do do
• Implement
ma
c
um en
the IDisposable interface to enable
ma
the cu .NET runtime to dispose
me of
rta t r nt
belo t a be
your
No class
.ba
rbo correctly.
n gs No
.ba
rbo
lon
gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
r m a aB o r m a
• Implement ize the IComparable
dc
ve
rab arb interface to enable collection ize
d classes
ve
r ab
Bato sort
rbo
op s os co s sa
ies s.c a . pie s.c .
instances of yourallclass. om sa
llo
om
ow we
ed d!
!
• Implement your own custom interface to define the functionality of your class.
Th Th
is is
public do class Coffee : IBeverage
c
d oc
um um
ma e nt en ma
{ rta be a.b tbrt
.ba lon elo
No rbo gs No a rbo ng
sa int servingTempWithoutMilk
t s st
private
un
au @ o Ma { u get;
na set;
a @ }o M
tho p rim rta u tho p rim art
riz intavservingTempWithMilk B riz av aB
private ed era a rbo { get; set; ed } era arb
co b s s c o b s os
pie s.c a . pie s.c a.
s o
public int IBeverage.GetServingTemperature(bool
all m s o
all includesMilk)
m
ow ow
ed ed
{ ! !
if(includesMilk)
{
return servingTempWithMilk;
}
Th Th
is is
doelse do
cu cu
ma m en ma me
rta{ tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s
return
a@ t oservingTempWithoutMilk; un s a@ to
au pri M art a uth pri Ma
tho ma aB ori ma rta
} zed r i ve a z v Ba
rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
} sa om sa om
llo llo
we we
public bool IBeverage.IsFairTrade d! { get; set; } d!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
The .NET Framework includes d! various collection classes that enable d! you to sort the
contents of the collection. These classes, such as the ArrayList class, include a
method named Sort. When you call this method on an ArrayList instance, the
collection orders its contents.
Th Th
is is
How doesdo the ArrayList instance know how items
cu
din
oc the collection should be
u
m me m me
ordered? nt case of simple types, such as integers,
art In the art nthis
t b appears fairly
a.b be a.b el
l
arb on arb on
No o gs No o gs
straightforward.
un
au
s a@ Intuitively,
t oM three follows two and two un follows
a
s a@ one. to However, suppose
Ma
tho pri art uth pri rta
r ma aB ori ma Ba
you create azecollection
i
dc
ve
rab of Coffee
a rbo objects. How would thez e ArrayList
dc
ve rab instance
rbo
op ss sa op ss sa
ies .co . ies .co .
determine whether aone llo coffee
m is greater or lesser than another a coffee?
llo m The answer is
we we
d!
that the Coffee class needs to provide the ArrayList instance withd!logic that enables
it to compare one coffee with another. To do this, the Coffee class must implement
the IComparable interface.
• Return an integer value that indicates whether the current object instance should
beThplaced before, in the same position, or after
Th the passed-in object instance.
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o na a oM
@ interpreted
The integer
au
tho valuesp rim returned
Ma
rta by the CompareTo method u tho are p rim art
aB
as follows:
riz av B a riz av a
ed era rbo ed era rbo
co bs sa co bs sa
pie s.c . pie s.c .
sa om sa om
• Less than zero indicates l l o that the current object instance precedes l l o the supplied
we we
d! d!
instance in the sort order.
• Zero indicates that the current object instance occurs at the same position as the
supplied instance in the sort order.
Th
• More Th instance follows the supplied
is than zero indicates that the current object
is
do do
um c cu
instance
ma ein
nt the sort order. ma me
nt
rta be rt a.b be
.ba lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
au pri Ma au pri Ma
tho ma rta tho ma rta
riz ve Ba riz ve Ba
ed rab rbo ed rab rbo
co sa co sa
The following example pie
sa
ssillustrates
.c om
. what happens if you use the pie CompareTo
sa
ss
. com
. method to
llo llo
compare two integers:wed! we
d!
CompareTo Example
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/71
10/25/2019 20483A - Programming in C# | Skillpipe
int number1 = 5;
int number2 = 100;
int result = number1.CompareTo(number2);
// The value of result is -1, indicating that number1 should precede
number2 in the sort
order.
T Th
his is
do d oc
cum um
ma e nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
Note:
au
tho
All @ the
prim
built-in
M a rta
value types in the .NET Framework
au
tho
@
p rim
implement
art the
riz av B r a aB
IComparable ed einterface. arb For more information about ized the IComparable
vera arb
co rab os co bs os
pie ss a . p s a.
interface, seethe sa IComparable
.c om Interface page at i e sa . com
llo llo
we
http://go.microsoft.com/fwlink/?LinkID=267801. we
d! d!
When you call the Sort method on an ArrayList instance, the Sort method calls the
CompareTo method of the collection members to determine the correct order for the
collection.
Th
i
Th
is
sd d
oc oc
um um
ma ent ma en
rta be a.b rt tb
.ba l elo
WhenNo you implement
rbo on gs the IComparable interface
No in your
a rbo own ng classes, you
st
determine
un sa t o u na s a oM
au @ Ma @
the criteria thoby which p rim objects
rta should be compared. For u tho example, p rim you
art might
aB decide that
riz av B a riz av arb
ed era rbo ed era
coffees should be c op sorted
ies
b s s.c alphabetically
s a . by variety. c o pie b s s.c
os
a.
all o m s all o m
ow ow
ed ed
! !
The following example shows how to implement the IComparable interface:
Th Th
is is
do do
u c cu
public
ma m
classen Coffee: IComparable ma me
rta tb r nt
.ba elo t a .ba be
ng lon
{ No rbo s No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
public t ho double r im r
AverageRating
ta { get; set;ho}r t r im rta
riz av B arb ize a ve Ba
ed era dc rab rbo
public string c op b
Variety
ss o sa { get; set; } op ss sa
ies .co . ies .co .
all m all m
int IComparable.CompareTo(object o we obj) o we
d! d!
{
Coffee coffee2 = obj as Coffee;
return String.Compare(this.Variety, coffee2.Variety);
}
} Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/71
10/25/2019 20483A - Programming in C# | Skillpipe
In this example, because the values we want to compare are strings, we can use the
String.Compare method. This method returns -1 if the current string precedes the
supplied string in an alphabetical sort order, 0 if the strings are identical, and 1 if the
current string follows the supplied string in an alphabetical sort order.
Th Th
is sd i
Implementing
um the IComparer Interface
do
c oc
um
ma en ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
T T
Whenhisyou his
do call the Sort method on an ArrayList instance,
do the ArrayList sorts the
cu cu
ma en m ma en m
collection
rta based
t b on the IComparable interface implementation
e rta tb
e
in the underlying type.
.ba lon .ba lon
r r
For Nexample,
ou
n
bo
@
gs
saif you
M
N
tosort an ArrayList collection oof
bo
unintegers,
sa
@
gs
the to sort criteria is defined
M
au pri art au pri art
tho ma a tho ma a Bcreator of the
by the IComparable
r ize
dc
ve interface
rab
Ba
rbo
implementation in the Int32
riz
ed type. vera The arb
op s s c o b s os
ies hass.no a . pie s.c a.
ArrayList instance all
co control
m over the criteria that are used s all
to sort
o m the collection.
ow ow
ed ed
! !
In some cases, developers may want to sort instances of your class using alternative
sort criteria. For example, suppose you want to sort a collection of Coffee instances
by the value of the AverageRating property rather than the Variety property. To sort
an ArrayList instance by using custom sort criteria, you need to do two things:
Th Th
is is
do oc d
cum um
ma e n ma en
1. Create
r ta.
ba
a bclass
t
elo that implements the IComparer r ta. interface
b
tb
elo to provide your custom
No r bo n gs No a r bo ng
st
sort
un functionality.
au
sa
@ t o M u n a
sa
@ oM
tho pri art uth pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs co ab os
2. Call the Sort pie method s.c onsathe
. ArrayList instance, and pass
p ies in s an
s.co instance
a. of your
sa om a m
llo llo
IComparer implementation we
d! as a parameter. we
d!
The TIComparer
his
d
Interface Th
is
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
As youis dcan is
oc see, the IComparer interface declaresdaoc single method named Compare.
um um
ma en ma en
Implementations
rta
.
t b of this method must:
e rt a.b
elo
tb
ba lon ngarb
No rbo gs No st os
un sa to un a oM
au @ M au @
tho prim a rta tho p rim art
riz a B r a aB
• Compare two ed objects
v era ofarthe same type. ized vera arb
co bs b o co bs os
pie s.c sa pie s.c a.
sa . sa
om om
llo llo
• Return an integer value we that indicates whether the current object we instance should
d! d!
be placed before, in the same position, or after the passed-in object instance.
In the above example, because the values we want to compare are doubles, we can
make use of the Double.CompareTo method. This returns -1 if the current double is
less than the supplied double, 0 if the current double is equal to the supplied double,
and T1 if the current double is greater than the supplied
T double. It is always better to
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/71
10/25/2019 20483A - Programming in C# | Skillpipe
make use of a built-in comparison function, if one exists, rather than creating your
own.
Using
T
an IComparer Implementation Th
his is
do d oc
cum um
ma e
nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
u s to un os st
// Create
na a
some
@ instances
Ma of the Coffee class. a @ oM
uth pri au p art
ori ma rta tho rim aB
riz av
Coffee coffee1 ze
dc
v=era newBarCoffee();
bo ed era arb
op bs sa co bs os
ies s.c . pie s.c a.
coffee1.Rating =llo 4.5; a o m sa om
llo
we we
d! d!
Coffee coffee2 = new Coffee();
coffee2.Rating = 8.1;
Coffee coffee3 = new Coffee();
coffee3.Rating = 7.1;
// Add the Coffee instances to an ArrayList.
Th Th
is is
ArrayListdo coffeeList = new ArrayList(); docu
cu
ma me ma me
rta nt r nt
.ba b
coffeeList.Add(coffee1);
elo t a .ba be
n lon
No rbo gs No rbo gs
un sa
coffeeList.Add(coffee2); to un sa to
au @ M a u @ Ma
tho p rim arta p tho rim rta
riz av Ba riz av Ba
ed
coffeeList.Add(coffee3);
c
era rbo ed
co
era rbo
op bs sa pie b s sa
ies s.c . s.c .
// Sort the ArrayList
all om by average rating. sa om
ow llo
ed we
d!
coffeeList.Sort(new! CoffeeRatingComparer());
To sort the ArrayList using a custom comparer, you call the Sort method and pass in
a new instance of your IComparer implementation as an argument.
Th Th
is is
do d oc
cum um
Lesson 3: Implementing Type-Safe Collections
ma
rta
.ba
r
e nt
be
lon a.b
ma
a r
rt
en
tb
elo
ng
No bo gs No bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
ab os form or
Almost every application co
pie bs thatsayou create will use collectioncoclasses
s.c . p ies s s in
.co
one a.
sa om a m
llo llo
another. In most cases, we collections contain a set of objects of the
d!
wesame type. When
d!
you interact with a collection, you often rely on the collection to provide objects of a
specific type. Historically, this created various challenges. You had to create
exception handling logic in case a collection contained items of the wrong type. You
also had to box value types in order to add them to collection classes, and unbox
themThon
is
retrieval. Visual C# removes many of these
Th
is
challenges by using generics
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/71
10/25/2019 20483A - Programming in C# | Skillpipe
In this lesson, you will learn how to create and use generic classes to create strongly
typed collections of any type.
Lesson Objectives
After completing this lesson, you will be able to:
Th Th
is is
do d oc
c
um um
• ma
Describe egenerics.
nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
• au the advantages
Identify a
tho pri
m rta of generic classes over non-generic
u tho p rim classes.art
aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
• Apply constraints s a to type
llo
om parameters. sa
llo
om
we we
d! d!
• Use generic list collections.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av ab
ed era r e e ab that rare
Generics enable co you to
pie bs create
s.c
b os and use strongly typed collections
a.
d co
pie
r
ss os type safe,
a.
sa om sa .co
m
do not require you tollowcast ed
items, and do not require you to box land low unbox value
ed
! !
types. Generic classes work by including a type parameter, T, in the class or interface
declaration. You do not need to specify the type of T until you instantiate the class. To
create a generic class, you need to:
• Add
Th the type parameter T in angle brackets after
i
Th
i
the class name.
sd sd
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/71
10/25/2019 20483A - Programming in C# | Skillpipe
• Use the type parameter T in place of type names in your class members.
The Tfollowing
his
d example shows how to instantiateThais generic
d class:
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
N r b gs No arb
ng
Instantiating
ou
na
os a Generic
a@ to Class un a
st
os oM
uth Ma au @
pri r ta tho pri art
ori ma Ba riz m av aB
ze ve rbo ed era arb
dc rab co bs os
op ss sa pie s.c a.
ies .co . sa
all m om
ow llo
we
CustomList<Coffee>ed!clc = new CustomList<Coffee>; d!
When you instantiate a class, every instance of T within the class is effectively
replaced with the type parameter you supply. For example, if you instantiate the
CustomList class with a type parameter of Coffee:
• The
T Add method will only accept an argument
T of type Coffee.
his his
do do
cum cu
ma e m me
• ThertRemove
a.b
nt
belo
method will only accept an argument
a r t a.b of t type
n
be Coffee.
a ng a l ong
No rbo st No rbo st
un sa oM un sa oM
au @ au @
• The indexer
tho will
prim always a rta provide a return value of type tho Coffee.
p rim art
aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Advantages of Generics
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The use of generic classes, particularly for collections, offers three main advantages
over non-generic approaches: type safety, no casting, and no boxing and unboxing.
Type Safety
Th Th
is
Consider is to store a collection of Coffee
do an example where you use an ArrayListdo
c um c um
ma e ma en
objects.
rtaYou ncan
.
t b add objects of any type to an ArrayList.
e rta
.
t b Suppose a developer adds
e
ba lon ba lon
No rbo gs No rbo gs
an object
un of type
au
s a@ Tea t o Mto the collection. The code will un build
a
s a@without to complaint.
Ma
tho pri art uth pri rta
ma aB ori ma
However, a runtime
r i ze
dc
veexception
rab a rbo will occur if the Sort method ze dc
is called,
ve rab
Bbecause
arb the
op s sa o s os
s
ies to compare .co . p ies s.co a .
collection is unable all m objects of different types. Furthermore, all m when you
ow ow
retrieve an object fromethe d! collection, you must cast the object to the ed
! correct type. If
you attempt to cast the object to the wrong type, an invalid cast runtime exception will
occur.
The following example shows the type safety limitations of the ArrayList approach:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/71
10/25/2019 20483A - Programming in C# | Skillpipe
arrayList1.Sort();
// The cast throws a runtime exception because you cannot cast a Tea
instance to a Coffee
instance.
Th Th
is i
Coffee do coffee3 = (Coffee)arrayList1[2]; s do
c um c um
ma e nt ma en
rta be a.brt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
As an alternative
tho
riz
rimto thertArrayList,
av aB suppose you use t a
h generic
ori
z
r im av List<T> aB to store a
ed era a rbo ed era arb
collection of Coffee co
pie objects.
sa
bs
s.c
om
sa
When. you instantiate the list,cyou op bs
ies provide s.c
o
aosatype
.
llo all m
o
argument of Coffee. In we this case, your list is guaranteed to be homogenous,
d!
we
d! because
your code will not build if you attempt to add an object of any other type. The Sort
method will work because your collection is homogenous. Finally, the indexer returns
objects of type Coffee, rather than System.Object, so there is no risk of invalid cast
exceptions.
Th Th
is is
do d oc
um c u
The following
ma en example shows an alternative to the me
ma ArrayList approach using the
rta tb r nt
.ba elo ta. be
ng ba lon
generic
No List<T>
un
r bo
s class:
st No
un
rbo
sa
gs
to
a @ oM @ Ma
au pri art au pri
tho m aB tho ma rta
riz av arb riz ve Ba
ed era ed rab rbo
co bs os co ss sa
Type Safety in Generic p ies s .cCollections
o
a. pie
sa . com
.
all m llo
ow we
ed d!
!
genericList1.Add(coffee1);
genericList1.Add(coffee2);
// This line causes a build error, as the argument is not of type
Coffee.
genericList1.Add(tea1);
// The Sort method will work because the collection is guaranteed to
Th Th
is is
be homogenous.
do
c
d oc
um um
ma nt e ma en
arrayList1.Sort();
rta be rt a.b tb
. ba lon elo
No rbo gs No arb ng
// The sa
un indexer to
returns objects of type Coffee,
un o sa so s tthere
oM is no need
auth @ M au @
pri art tho pri art
ori ma aB riz ma aB
to cast the z ed returnv era arb ed ve arb
co bs os co r a bs os
pie s.c a. pie s.c a.
value. sa om sa om
llo llo
we we
Coffee coffee3 = genericList[1]; d! d!
No Casting
T
his his T
Casting dois a computationally expensive process. When
do you add items to an
cu cu
ma en m ma en m
ArrayList,
rta your
t b items are implicitly cast to the System.Object
e rta tb
e
type. When you
.ba lon .ba lon
No r bo g No bo gs r
retrieveun items sa froms an
@ to ArrayList, you must explicitly
M un cast sa them
@ toback to their original
M
au pri art au pr ar
th ma a B and retrieve imth ta
type. Usingorigenerics
ze
dc
ve to add
rab arb items withoutorcasting
ize
d
avimproves
er Ba
r
the
os co ab bo
op s s.c a. pie ss sa
performance of your ies application. sa .co .
all o m m
ow llo
ed we
! d !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/71
10/25/2019 20483A - Programming in C# | Skillpipe
int number1 = 1;
var arrayList1 = new ArrayList();
// This statement boxes the Int32 value as a System.Object.
arrayList1.Add(number1);
// This statement unboxes the Int32 value.
intT number2 = (int)arrayList1[0]; Th
his is
do do
cu
var genericList1 = new List<Int32>(); cu
ma me m me
rta n tb a r nt
elo t a.b be
//This.bastatement
rbo ng adds an Int32 value without a r
boxing.
lon
No st N ou b os gs
un sa o n a to
au @
genericList1.Add(number1); M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
//This statement e dc e rabretrieves rbo the Int32 value without e dc e runboxing.
ab rbo
op s s s a o p s s sa
ies .co . ies .co .
int number3 = genericList1[0]; a llo m a llo m
we we
d! d!
Constraining Generics
Th Th
is is
do d oc
c um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
In some cases, you may need to restrict the types that developers can supply as
arguments when they instantiate your generic class. The nature of these constraints
will depend
Th
is on the logic you implement in your generic
Th
is class. For example, if a
do do
cu cu
collection
ma class
me
n
uses a property named AverageRating
ma me to sort the items in a
n
rta tb rta tb
.ba lon e .ba loto e
collection,
No ryou
bo would
gs need to constrain the typeNoparameter
rbo ng classes that include the
s
un sa to un to sa
au @ Ma au @ Ma
AverageRating
t ho
riz
prproperty.
im
av
r ta Suppose the AverageRating
B
t ho property
r
p r im
a
isrtadefined
Ba
by the
ed era arb ize ve
os d r ab rb othe
IBeverage interface. co
pie To
bs implement
s.c a. this restriction, you would co
pie constrain ss
.co
sa type
.
sa om sa m
llo llo
parameter to classes wthat ed implement the IBeverage interface by wusing ed the where
! !
keyword.
The following example shows how to constrain a type parameter to classes that
implement a particular interface:
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/71
10/25/2019 20483A - Programming in C# | Skillpipe
where T : <name of base class> The type argument must be, or derive from, the specified class.
where T : U The type argument must be, or derive from, the supplied type
argument U.
Th Th
is is
do oc d
where T : new()
um c The type argument must haveuma public default constructor.
ma en ma en
rta tb rta tb
.ba elo .ba elo
where rbo
No T : struct n gs The type argument No be arbvalue
must ng
type.
un sa t u o s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
where T : class riz av B a The type argument must be a riz
reference atype.
v arb
ed era rbo ed era
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
You can also apply multiple d! constraints to the same class, as shown d! by the following
example:
Th Th
is is
do oc d
cum um
ma ent ma en
publicrta class be CustomList<T> where T : IBeverage,
rta t b IComparable<T>,
elo
.ba lon .ba
No r bo gs No r bo ng
new()un s to un s st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
{ r i ze ve Ba riz av arb
dc rab rbo ed era
op ss sa co bs os
i e . . pie s.c a.
} sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
One of the au mostp common
tho rim
M a rta and important uses of generics
au
tho isp rim collection
in art classes.
riz av B r a aB
iz v
Generic collections ed
co
pie
fallbs intoarbtwo
era
os broad categories: generic
a.
ed
clist
era
op collections bs
arb
os and generic
a.
s.c i e s . c
sa om sa om
dictionary collections.owA generic list stores a collection of objectsowof type T.
l l l l
ed ed
! !
string s1 = "Latte";
string s2 = "Espresso";
string s3 = "Americano";
string
Th s4 = "Cappuccino"; Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/71
10/25/2019 20483A - Programming in C# | Skillpipe
string s5 = "Mocha";
// Add the items to a strongly-typed collection.
var coffeeBeverages = new List<String>();
coffeeBeverages.Add(s1);
coffeeBeverages.Add(s2);
coffeeBeverages.Add(s3);
Th Th
is is
coffeeBeverages.Add(s4);
do
c
d oc
um um
ma nt e ma en
coffeeBeverages.Add(s5);
rta be rt a.b tb
. ba lon elo
No rbo gs No ng arb
sa items to o sa st
// Sort
un
au
the @ M using the default comparer.
un
au @ oM
tho prim a rta tho p rim art
r a B r a aB
// For objectsi z ed vof
era type arb String, the default comparer ized vera sorts arb the items
co bs o sa co bs os
pie s.c . pie s.c a.
alphabetically. sa om sa om
llo llo
we we
coffeeBeverages.Sort(); d! d!
• The Stack<T> class represents a strongly typed last in, last out collection of
objects.
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
Dictionary classess store all collections
om of key value pairs. The value s a is the
l
om object you
ow l ow
ed ed
want to store, and the key ! is the object you use to index and retrieve ! the value. For
example, you might use a dictionary class to store coffee recipes, where the key is
the name of the coffee and the value is the recipe for that coffee. In the case of
generic dictionaries, both the key and the value are strongly typed.
Th Th
is is
The Dictionary<TKey,
do
cu TValue> Class d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
TheNDictionary<TKey, l on TValue> class provides a general
a purpose,
ng strongly typed
ou rbo gs No rbo st
na s a t o u na s a o
@ @
dictionary uthclass. priYou M Ma
ma can
art add duplicate values to the uthcollection,
ma but rtathe keys must be
pri
ori aB ori Ba
ze ve arb ze ve rbo
dc rab d r ab
unique. The class op will throw
ies s s.c
oan
s a . ArgumentException if you co attempt
pie s s.cto addsa a key that
.
all om sa om
llo
already exists in the dictionary. o we
d!
we
d!
The following example shows how to use the Dictionary<TKey, TValue> class:
Th Th
is is
do d oc
cum um
ma e ma en
Other Generic Dictionary Classes
rta
.ba
nt
be
lon a.b rt tb
elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au a
The SortedList<TKey,
tho pri
m
artTValue> and SortedDictionary<TKey,
a
uth
o
pri
m TValue>
art
aB classes both
riz av Ba riz av a
ed era rbo e d e rab rb
provide genericcodictionariespie bs
s.c insa which the entries are sortedcoby
. pie key. ssThe odifference
.
sa
.
sa om sa com
llo llo
between these classes we is in the underlying implementation:
d!
we
d!
• The SortedList generic class uses less memory than the SortedDictionary
generic class.
• The
T
SortedDictionary class is faster and more
T
efficient at inserting and removing
his his
do
unsorted do
cu data. cu
m m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 44/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
The IEnumerable
is
do
cu
and IEnumerable<T> Interfaces
is
do
cu
ma me ma me
rta nt r nt
. belo t a . be
If you
No want
barbto be nable
o g s
to use a foreach loop to enumerate
N
b arb
o
over
lon
gs the items in your
un s a t o o u s a to
@ Ma n @ Ma
custom ageneric
uth
ori
pcollection,
r im r ta you must implement the aIEnumerable<T>
u t ho p r im rta interface. The
ze a ve B a r iz a v Ba
dc rab rbo e dc e rab rbo
IEnumerable<T> op method
ies ss
.co
defines
sa
.
a single method named GetEnumerator().
op
ies ss
.co
sa
.
This
al m all m
method must return lan ow object of type IEnumerator<T>. The foreach
ed
ow
ed statement relies
! !
on this enumerator object to iterate through the collection.
The IEnumerable<T> interface inherits from the IEnumerable interface, which also
defines a single method named GetEnumerator(). When an interface inherits from
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 45/71
10/25/2019 20483A - Programming in C# | Skillpipe
another interface, it exposes all the members of the parent interface. In other words,
if you implement IEnumerable<T>, you also need to implement IEnumerable.
Name Description
Name Description
Name Description
RemoveAt
T Removes the item at the specified index
T from the collection.
his his
do do
cum cu
ma e ma me
rta tb n rta nt
The IList<T>
.ba interface
elo defines the following properties:
.ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
au @ Ma au @ Ma
tho pri rta tho pri rta
riz m av Ba riz m av Ba
ed era rbo ed era rbo
co b s sa co b s sa
Name pDescription
ies s .co . pie
sa
s.c
om
.
all m llo
ow we
ed d!
!
IndexOf Determines the position of a specified item in the collection.
Name Description
Add Adds an item with the specified key and value to the collection.
Th Th
is
ContainsKey is
Indicates whether the collection includes a key-value pair with the specified key.
do do
cu cu
ma me ma me
rta nt rt nt
.ba
GetEnumerator belo Returns an enumerator of a .ba
KeyValuePair<TKey, be TValue> objects.
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
Remove hor t r im r
Removes
ta the item with the specified key t ho from the r im collection. rta
ize av B a r iz a v Ba
dc e rab rbo e dc e rab rbo
op ss sa op ss sa
TryGetValue i e .c
Attempts .
to set the value of an output parameter to i e s athe value. c .
sa om om associated with a
llo llo
wespecified key. If the key exists, the method returns true. weIf the key does not
d! d!
exist, the method returns false and the output parameter is unchanged.
his T Th
Name do Description is
d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 47/71
10/25/2019 20483A - Programming in C# | Skillpipe
Name Description
Item Gets or sets the value of an item in the collection, based on a specified key. This
property enables you to use indexer notation, for example myDictionary[myKey] =
myValue.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
To enumerate over a collection, you typically use a foreach loop. The foreach loop
exposes each item in the collection in turn, in an order that is appropriate to the
collection. The foreach statement masks some of the complexities of enumeration.
For the
Th foreach statement to work, a generic collection
is
Th
is class must implement the
do do
um c um c
IEnumerable<T>
ma en interface. This interface exposes
ma a method,
en GetEnumerator,
rta tb rta tb
.ba elo .ba elo
which
No mustboreturn
r
s
ng an IEnumerator<T>
st type. No rbo
sa
ng
st
un a @ oM un @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
The IEnumerator<T> Interface
pie
sa
s.c
om
a. pie
sa
s.c
om
a.
llo llo
we we
d! d!
The IEnumerator<T> interface defines the functionality that all enumerators must
implement.
Name Description
Reset Sets the enumerator to its starting position, which is before the first item in the
collection.
Th Th
is is
The IEnumerator<T>
do
c
interface defines the followingdo properties:
c
um um
ma en ma en
rta tb r t a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
Name tho a a
u priDescription
ma
a r taB
u t h ori
p r ima
art
aB
riz v arb z v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
Current Gets
s a the item om that the enumerator is pointing to. sa om
llo llo
we we
d! d!
An enumerator is essentially a pointer to the items in the collection. The starting point
for the pointer is before the first item. When you call the MoveNext method, the
pointer advances to the next element in the collection. The MoveNext method
returns true if the enumerator was able to advance one position, or false if it has
T
his his T
reached dothe end of the collection. At any point during
do the enumeration, the Current
cu cu
ma returns
en m m en m
property
rta t b the item to which the enumeratorartis
a
currently
tb pointing.
.ba elo elo
.ba
No rbo ng No ng
rbo
un sa st un sa st
@ oM @ oM
au p art au p art
tho rim aB tho rim aB
When you create
riz
ed an
av enumerator,
era arb you must define: riz
ed
av
era arb
co b s os co b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
• Which item the enumerator should treat as the first item in the collection.
• In what order the enumerator should move through the items in the collection.
TheThIEnumerable<T>
is
d
Interface Th
is
d
oc oc
um um
ma e nt ma en
The IEnumerable<T>
r ta. be interface defines a single method a.b rt t named
be GetEnumerator.
ba lon a lon
No r bo gs No r bo gs
This returns
un san to
a@ IEnumerator<T> instance. un sa to
au Ma au @ Ma
tho pri r ta t ho p r im rta
riz ma B r a Ba
ed ve a ize ve
rab rbo dc rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa omcollection class.
The GetEnumerator llo method
we
returns the default enumerator for lloyour
we
d! d!
This is the enumerator that a foreach loop will use, unless you specify an alternative.
However, you can create additional methods to expose alternative enumerators.
The following example shows a custom collection class that implements a default
enumerator,
T
together with an alternative enumerator
T
that enumerates the collection in
his his
reversedorder:
oc
um
do
cu
me
m e m
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 49/71
10/25/2019 20483A - Programming in C# | Skillpipe
{
// This method returns the default enumerator.
// The implementation details are not shown.
}
Th Th
is
#endregion is
do do
cu cu
ma m en ma me
#region
rta t IEnumerable Members r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
IEnumerator
un sa IEnumerable.GetEnumerator()
to un sa to
au @ M a uth @ Ma
tho pri art pri rta
r m a aB o r m a Ba
{ ize ve arb ize ve
dc rab os d r ab rbo
op s a co s sa
i s . . p i s. .
// This esmethod all
co is required because IEnumerable<T>
m
es
all
co inherits
m
ow ow
e ed
from IEnumerable d! !
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
// Use
un the s
sa alternative o
enumerator to iterate o sathrough st
@ to
M un @ o M the collection:
au p a au p art
tho rim rta tho rim aB
foreach(int riz
ed number
av
era in
B arb numbers.Backwards()) r ized
a vera arb
co bs o sa co bs os
p ies s .co . p ies s .co a.
{ all m all m
ow ow
// … ed ed
! !
hisT Th
Implementing
do
c
the Enumerator is
d oc
um um
ma ent ma en
rta be a.brt tb
You Ncan provide
. barb l onan enumerator by creating a customarclass
gs No bo
elothat implements the
ng
ou os t u s st
na a @ o na a @ oM
IEnumerator<T>
uth pri interface.
m
Ma
r taB
However, if your custom u t collection
h p r im
classart uses an
aB
ori av ori av
ze era a rboto store data, you can use an zed era arb
underlying enumerable dc
op b s type
s.c s a c iterator
o pie b s to
s.c
implement
os
a.
the
ies . s
all o m all o m
IEnumerable<T> interface ow
ed
without actually providing an IEnumerator<T> ow
ed
! !
implementation. The best way to understand iterators is to start with a simple
example.
The following example shows how you can use an iterator to implement an
enumerator:
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba elo
Implementing
No rbo an
lon Enumerator
gs by Using an Iterator
N arb
o
ng
st
un s a@ to ou sa oM
au Ma na @
tho pri rta uth pri art
riz ma Ba ori ma aB
ed ve rbo ze ve arb
co rab dc rab os
pie ss sa op s s a.
sa .c . ies .co
om all m
using System; llowe ow
ed
d! !
using System.Collections;
using System.Collections.Generic;
class BasicCollection<T> : IEnumerable<T>
{
Thprivate List<T> data = new List<T>();
Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 51/71
10/25/2019 20483A - Programming in C# | Skillpipe
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
Th Th
} is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
The example tho
riz showsrim
av a custom
rta
B generic collection class tho that uses
riz
rim
av a List<T>
aB instance
ed era a rbo ed era arb
co bs sa co bs os
to store data. The pie List<T>
sa
s.c instance
om
. is populated by the FillList pie
sa
method.
s.c
om
aWhen
. the
llo llo
GetEnumerator method we is called, a foreach loop enumerates the
d!
we underlying
d!
collection. Within the foreach loop, a yield return statement is used to return each
item in the collection. It is this yield return statement that defines the iterator—
essentially, the yield return statement pauses execution to return the current item to
the caller before the next element in the sequence is retrieved. In this way, although
the GetEnumerator
Th
is method does not appear toThreturn
is an IEnumerator type, the
do do
u c um c
compiler
ma ismable
en to build an enumerator from themiteration
a en logic that you provided.
rta tb rta tb
.ba elo .ba elo
No r bo ng No rbo ng
un s st un sa st
a @ oM @ oM
au pri art au pri art
Demonstration: Adding Data Validation and Type-Safety to
tho
riz
ed
m av
era
aB
arb
tho
riz
ed
m av
era
aB
arb
co bs os co bs os
the Application Lab pie
sa
llo
s.c
om
a. pie
sa
llo
s.c
om
a.
we we
d! d!
In this demonstration, you will learn about the tasks that you will perform in the lab for
this module.
Scenario
Now that the user interface navigation features are working, you decide to replace
the simple structs with classes to make your application more efficient and
straightforward.
You Thave
his also been asked to include validation Tlogic
his in the application to ensure that
do do
um c um c
whenmaa userenadds grades to a student, that the data
ma is evalid
n before it is written to the
rta tb rta tb
ba .lon e ba lon . e
database.
No rYou
bo
s
decide
gs to create a unit test project
No that rbwill
os perform
gs tests against the
un a@ to un a@ to
au p Ma au p Ma
required validation
t h ori r i ma for different
r taB grade scenarios. t h ori r ima rta
Ba
ze ve a r ze ve rbo
dc rab bo dc rab
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
Teachers who have seen ed the application have expressed concern
!
edthat the
!
students in
their classes are displayed in a random order. You decide to use the IComparable
interface to enable them to be displayed in alphabetical order.
Finally, you have been asked to add functionality to the application to enable teachers
Th Th
to addisstudents to and remove students from a class,
d
is
d
and to add student grades to
oc oc
me u um
the database.
ma
r nt ma
rt
en
tb
ta. be a.b elo
ba lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
Objectives riz
ed
m av
era Ba
rbo
riz
ed
av
era
aB
arb
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
After completing thisllolab, we you will be able to: llo
we
d! d!
• Create classes.
• Implement
Th
is the IComparable interface. Th
is
do d oc
c um um
ma e nt ma en
tb
• Usertgeneric
a.b
arb
becollections.
lon
rt a.b
arb
elo
ng
No o gs No os st
un s a@ to un a oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
Estimated Time: 60 minutes om om
llo llo
we we
d! d!
• Password:
Th
i
Pa$$w0rd Th
is
sd d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 53/71
10/25/2019 20483A - Programming in C# | Skillpipe
Scenario
In this
T
exercise, you will convert the existing Teacher,
T
Student, and Grade structs into
his his
classes.doThis
cu
m
do
will enable you to implement the additional
cu
m
functionality required for
ma en ma en
rta tb rta t
each class,
.ba such
elo as adding constructors, properties,
n
.baand bmethods.
elo
n
In the Teacher
No rbo gs No rbo gs
un sa to sa to
and Student
au
t
classes,
@
pr Myou
ar will make the passwordunproperty
au
t
@ write-only,
pr Ma
r
add the
imho ta ho im ta
riz
av Ba riz av Ba
VerifyPassword
e d c method,
op
e rab and
rbo then
sa
define their respective
e d c constructors.
op
e rab rbo
sa
ies s s . ies s s .
.co .co
all m all m
ow ow
ed ed
! !
You will also modify the Logon_Click method to use the VerifyPassword method to
verify passwords when a user logs on.
Finally, you will run the application and verify that it still functions correctly, allowing a
student
Th or a teacher to log on. Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
TheNmain atasks
. b l for
o this exercise are as follows: elo
rbo n gs No a rbo ng
ou s t u s st
na a @ o Ma na a @ oM
uth pri r t u t h p r i art
ori m av aB ori m av aB
ze era a rbo zed era arb
dc
1. Convert the op Grades
ies
b s s.c struct s a . into a class c o pie b s s.c
os
a.
all o m s all o m
ow ow
ed ed
!
2. Convert the Students and Teachers structs into classes !
3. Use the VerifyPassword method to verify the password when a user logs in
4. Build and run the application, and verify that a teacher or student can still log on
Th Th
is is
do d oc
cum um
ma e nt maen
r rt tb
Task 1:taConvert
.ba be the Grades struct into a class a.
lon ba elo
ng
No r bo gs No r bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs co running. ab os
1. Start the MSL-TNG1 pie s.c virtual
sa
. machine if it is not already p ies s s.co a.
sa om a m
llo llo
we we
d! d!
2. Start the 20483A-SEA-DEV11-04 virtual machine and log on as Student with
the password Pa$$w0rd.
3. Start Visual Studio and open the GradesPrototype.sln solution from the
E:\Labfiles\Starter\Exercise 1 folder.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 54/71
10/25/2019 20483A - Programming in C# | Skillpipe
4. In the Data folder, in Grade.cs, convert the Grade struct into a class.
5. Define a class constructor that takes the following parameters and uses them to
populate the public properties of the class:
o studentID
Th Th
ois do assessmentDate is
d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba subject elo
Noo rbo
lon
gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
o riz
assessment av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
o comments wed! we
d!
6. Define a default class constructor that takes no parameters and assigns the
following default values to the public properties:
o Student ID: 0
Th Th
is is
do d oc
c
moa AssessmentDate: the current date
um um
en ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
st os st
ouna SubjectName:
sa
@ oM Math un
au a @ oM
uth pri art tho p rim art
ori m av aB riz av aB
ze era arb ed era arb
dc b os co b os
o Assessment:
opie
sa
s s.A
co
a. pie
sa
s s.c
om
a.
llo m llo
we we
d! d!
o Comments: an empty string
Th
Note: An application should not be able
Th
to read passwords; only set
is is
do
c
them and verify that a password is correctdo
c
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 55/71
10/25/2019 20483A - Programming in C# | Skillpipe
4. Define a class constructor that takes the following parameters and uses them to
populate the public properties of the class:
o studentID
Th Th
ois do userName is
d
c oc
um um
ma ent ma en
rta be rt a.b tb
o .ba password lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
o firstName
riz
ed
av
era Ba
rbo
riz
ed
av
era arb
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
o lastName wed we
d!
!
o teacherID
5. Define a default class constructor that takes no parameters and assigns the
following default values to the public properties:
Th Th
is is
do d oc
m
o cStudent
um
en
ID: 0 ma
um
en
art t be rt tb
a.b lon a.b elo
No arb gs No arb ng
o
ouna UserName: sa to an empty string un os st
@ Ma a @ oM
uth pri au p art
ori m rta tho rim aB
ze a ve Ba riz av arb
dc rab rbo ed era
o Password: op an
s empty sa string co b s os
ies s.c . pie s.c a.
all om sa om
ow llo
ed we
! d!
o FirstName: an empty string
8. Define a class constructor that takes the following parameters and uses them to
populate the public properties of the class:
o teacherID
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 56/71
10/25/2019 20483A - Programming in C# | Skillpipe
o userName
o password
o firstName
o lastName
Th Th
is is
do oc d
c
moa className
um um
en ma en
rta tb r t a.b tb
.ba elo elo
No rbo ng N arb ng
saa defaults o
to class constructor that takesunno parameters o sa st
9. Define
un
au @
p M a au @
p
o Mand assigns
art
the
tho rim rta tho rim aB
riz av B r i a
following ed default
co
era values
bs
arb to the public properties:
o
zed
co
vera
bs
arb
os
pie s.c sa pie s.c a.
sa . sa
om om
llo llo
o TeacherID:w0ed! we
d!
Task 3: Use the VerifyPassword method to verify the password when a user
logs in
1. ThIn the Views folder, in the LogonPage.xaml.cs Th code, modify the code in the
is is
do do
cu cu
me
mLogon_Click method to call the VerifyPassword ma me method to verify the teacher’s
art nt rta nt
a.b be . be
arb l ong b arb lon
Nopassword. o s N o o gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
2. Modify the e d c code rabto check rbo whether teacher is null before e dc e
examining
rab rbo the
op ss sa op ss sa
ies .co . ies .co .
UserName property. a llo m a llo m
we we
d! d!
3. In the Student class, modify the code in the Logon_Click method to use the
VerifyPassword method to verify the student’s password.
4. Modify the code to check whether student is null before examining the
ThUserName property. Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 57/71
10/25/2019 20483A - Programming in C# | Skillpipe
Task 4: Build and run the application, and verify that a teacher or student can
still log on
1. Th
Build the solution and resolve any compilation
T
errors.
is his
do do
c
um cu
mLog m me
2. art in as
a.b
e nt vallee with a password of password.
b a r t a.b
nt
be
elo lon
No arbo ng N a r b gs
un sa st ou os to
@ o M n a @ Ma
3. au thatpyou can
Verify art log on as a teacher. au pri
tho rim a t h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
4. Log off from the s a application.
llo
om sa
llo
om
we we
d! d!
5. Log in as grubere with a password of password.
Th Th
sd i is
The main
oc tasks for this exercise are as follows:
u
d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 58/71
10/25/2019 20483A - Programming in C# | Skillpipe
2. Add validation logic to the Grade class to check the data entered by the user
3. Add a unit test to verify that the validations defined for the Grade class functions
as expected.
Th Th
is is
do d oc
cum um
ma e
nt ma en
r rt tb
Task 1:aCreate
t .ba bela
on list of valid subject names a.b
arb
elo
No rbo gs No ng
un sa to un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bfrom o co 2 folder, bs os
1. In Visual Studio, pie ss
.c
the sa E:\Labfiles\Starter\Exercise
. p i e s . c
open a. the
sa om sa om
llo llo
GradesPrototype.sln we
d! solution. we
d!
2. In the Data folder, in the DataSource class, define a generic List collection to
hold the names of valid subjects.
3. In the CreateData method in that class, populate the list with the following
Th Th
subject
is
do names: is
d
cu oc
me um
ma nt ma en
rta be rt a.b tb
o .ba Math lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
o English
r ize
dc
a ve
rab
Ba
rbo
riz
ed
av
era arb
op s sa co b s os
ies s.c . pie s.c a.
all om sa om
o llo
o History we
d!
we
d!
o Geography
o Science
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
TaskNo2: Add rbo validation gs logic to the Grade class
No to a check
r bo ngthe data entered
st by the
un s a t o u n s a oM
@ M @
user a uth
ori
pri
ma
art
aB
a uth
ori
pri
ma
art
aB
ze ve a rbo ze ve arb
dc rab dc rab os
op s s sa o p s s a.
ies .co . ies .co
all m all m
ow ow
1. In the Data folder, edin the Grade.cs code, add validation code
!
edto the
!
AssessmentDate property to ensure that the following requirements have been
met:
Th T
is that the user has provided a valid date. his
• Verify
d oc d oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 59/71
10/25/2019 20483A - Programming in C# | Skillpipe
• Check that the date is no later than the current date. If it is, throw an
ArgumentOutOfRangeException exception.
Th Th
is is
do d oc
c
um um
• If the
ma grade en is not valid, then throw an ArgumentOutOfRangeException
ma en
rta tb rta tb
.ba elo .ba elo
exception.
No r bo
s
ng
st No rbo
sa
ng
st
un a @ oM un @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
Task 3: Add a unit test to verify that the validations defined for the Grade class
functions as expected.
1. Add a Unit Test Project called GradesTest to the solution and reference the
ThGradesPrototype project from it. Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 60/71
10/25/2019 20483A - Programming in C# | Skillpipe
2. In the UnitTest1 class, define the following tests and support methods:
• TestValidGrade: to check that valid data passes the validation logic successfully
Th Th
is is
do do
• TestBadDate:
cu
me to check that dates in the future are cunot valid
me
ma n m a nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r b gs
• TestDateNotRecognized:
un sa
@
st
o M
to check that non-dates
ou
n are os not valid
a @ to
Ma
au pri art au pri
tho m a t h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
• TestBadAssessment: co
pie b s s.cto check
s a. that assessment values outside
c o pie b sthe
s.c permitted
sa
. range
sa om sa om
llo llo
are not valid we
d!
we
d!
• TestBadSubject: to check that subject names not in the list are not valid
his T his T
Exercisedo
c
3: Displaying Students in Name doOrder
c
um um
ma en ma en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
un s st un os st
a @ oM a @ oM
au au
Scenariothoriz primav arta B tho
riz
pri
m av
art
aB
ed era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
s
In this exercise, youallowill write o m code to display s
the students in alphabetical all o m order of last
we ow
d! ed
!
name and then first name.
add code to the CompareTo method in the Student class, enabling students to be
sorted based on their last name and first name.
Task 1: Run the application and verify that the students are not displayed in
any specific order when logged on as a teacher
Th Th
1. Inis Visual Studio, from the E:\Labfiles\Starter\Exercise
do
is
d
3 folder, open the
c oc
um um
mGradesPrototype.sln
art e n solution. m a en
a.b t be r ta. tb
l o b elo
No a r bo n gs No a r bo ng
un s t u s st
a @ o n a @ oM
2. Buildauth the solution
pri
ma
M arand
ta
resolve any compilation uerrors.
a
tho pri
m
art
aB
ori Ba riz av
ze ve rbo e e arb
dc rab dc rab os
op s s sa o p s s a.
ies .
.co a password ies the.cstudents
3. Log in as vallee all with m of password. Verify thatall o m are not
ow ow
ed ed
displayed in any specific ! order. !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 62/71
10/25/2019 20483A - Programming in C# | Skillpipe
1. In the Grade.cs code window, locate the Student class definition, and modify it
to implement the IComparable<Student> interface.
Th Th
2. Inisdthe CompareTo method, concatenate the is FirstName and LastName
do
oc cu
um me
mproperties
art e nt of each of the students being compared, m a nt and then use the
a.b belo r t a.b be
a ng a lon
rbo
NoString.Compare st method to establish the order
N ou r
that
b os they gs should be displayed in
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
the list. riz
ed
m av a Ba o riz
ed
m av Ba
era rbo era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
llo llo
we we
d! d!
Th Th
1. Inis the Data folder, in the DataSource.cs code,
do
is
d
in the DataSource class, modify
c oc
um um
mthe
art Students
e nt ArrayList collection to be a generic
m a enList collection.
a.b be rta tb
l o . b elo
No a rbo n gs No a rbo ng
un sa t u s st
@ o na of the a @ Students oM
2. In athe
uth CreateDatapri Ma method, modify the creation
r t u t h p r i art collection to
ori m av aB ori mav aB
ze era a rList zed era a rbo
create adnew co
pie
genericbs bo
sa collection. co
pie bs sa
s.c . s.c .
sa om sa om
llo llo
we we
d! d!
4. Verify that the students are displayed in order of ascending last name.
Scenario
Th
is
Th
is
do oc d
cum um
ma en m a en
In this exercise,
rta
.ba
t be you will write code that enables a rtteacher
lon a.b t b to add a student and then
elo
No rbo gs No a rbo ng
s s st
enroll uthem
na
uth
in a a
@ class.
pri
t o Ma This will be implemented asu natwo
u
separate
a @
p
o Msteps, because a
art
ori m r taB t h ori r im aB
av av
teacher may ewant z
dc toeraadd arbstudent
a
o
before knowing which zed classerthey
c a will
arb be enrolled
os
op b s s a o pie b s a.
ies s.c . s.c
in. You will also enable all
ow
a oteacher
m to remove a student from a class.
s all
ow
When
o m adding or
ed ed
removing a student, you! will display a prompt to confirm that the teacher ! wants to
perform the action.
To enroll a student in a class or remove them from a class, you modify the TeacherID
property of that student. The application now includes the AssignStudentDialog
Th Th
is i
window, owhich
d
cu displays a list of students who are snot do assigned to a class. You need
cu
ma m en ma me
t b this window to assign a student to the nt
to add rcode
ta.
ba to elo r t a .ba teacher’sbe
lon class and to update
No rbo ng No rbo gs
sa s
the listunof
au students @ to appropriate. You also need uto
as Ma na addsacode @ to remove a student
to Ma
tho pri r ta u t ho p r im rta
riz ma B r a Ba
from a class and i
d c to enable rteachers to add grades to their d c students.
e v e a ze ve rbo
rab bo rab
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
After a student has been added to the database, that student will be able to log on to
view their own grades.
2. Add the EnrollInClass and RemoveFromClass methods for the Teacher class
4. Add code to enable a teacher to remove the student from the assigned class
Th Th
is is
do od
5. c tocuamestudent
mAdd
ucode
me to enable a teacher to add a grade
art nt m art nt
a.b be a.b be
a lon a lon
No rbo gs No rbo gs
6. Run
u s
na the application
a t o and verify that students ucan
na be added s a to to and removed from
uth @ M uth @ Ma
pri art pri rta
ori ma aB ori ma Ba
classes, ze and that
dc
ve
rab grades a rbo can be added to students ze
dc
ve
rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
1. In the Data folder, in the Grade.cs code, in the Teacher class, implement the
EnrollInClass method as follows:
• If the student is not in another class, set the TeacherID property of the
student to the current TeacherID.
2. ThIn the Teacher class, add code to the RemoveFromClass Th method as follows:
is is
do do
cu cu
m•a Verify me m me
rta n tbthat the Student is actually assigned
a r t to
a.b
thent class for the given teacher.
be
.ba elo lon
No rbo ng N a r b gs
un sa st ou os to
@ o M n a @ Ma
• aIfuththeori
student
pri
ma
art part of the class, reset the aTeacherID
is aB
uth
ori
pri property
ma rta of the student
ze ve a ze ve Ba
dc rab rbo dc rab rbo
to zero. op
ies ss
.co
sa
. op
ies ss
.co
sa
.
all m all m
ow ow
e ed
• If the student isd!not part of the class, throw an ArgumentException !
Th• Verify that the Grade object passed to the Th method does not belong to
is is
do do
another
cu
m
student. cu
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No• If itrbodoes not n gs belong to another student,Noadd the rbo gs to the student’s record
un sa
@ to un grade
sa
@ to
au pri M art a uth pri Ma
tho r
by setting
r ize
m the
a a
ve StudentID Ba
rbo
property of the Gradeizeobject.ve ta Bar
o r m a
dc rab dc rab bo
op ss sa op ss sa
ies .co . ies .co .
all m all m
• If it does belong o we to another student, throw an ArgumentException o we exception
d! d!
to show that the grade belongs to a different student.
• Inside the try block, determine which student the user clicked by using the
Tag property of the studentClicked button.
• Find this student in the Students collection and prompt the user to confirm
Th that they wish to add the student to theirThclass.
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 66/71
10/25/2019 20483A - Programming in C# | Skillpipe
• If the user confirms this, add the student to the class by calling the
EnrollInClass method, and then refresh the display.
Th
• Detect if the user is a teacher. If they are not,Thexit the method.
is is
d oc d oc
um um
ma ent ma en
rta be a.brt tb
• Add a.btryar
block.l on a r
elo
ng
No bo gs No bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
m a m
• Inside the riz try block,
ed
av
era display Ba
rbo
a message box to prompt o riz the user
e d
av
e r
toa Bconfirm
arb that the
co bs sa co ab os
pie s . p s s a.
current student sshould all
.co be removed
m from their class. ies
all
.co
m
ow ow
ed ed
! !
• If the user confirms, call the RemoveFromClass method of the current teacher to
remove this student from their class, and then return to the previous page.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 67/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do o d
• Detect
m
uifmthe user is a teacher. If they are not, exitcthe
e
c
m
um method.
e
art nt art nt
a.b be a.b be
a lon a lon
No rbo gs No rbo gs
• Addunaa try sblock.
a@ to
M u na s a @ to
Ma
uth pri art uth pri rta
ori ma aB ori ma Ba
ze ve a r ze ve rbo
dc rab bo dc rab
• Inside the try pblock,
o
ies s use
s .co the
s a . GradeDialog to get the details
o p ies of the
s s.co assessment
sa
.
all m all m
ow ow
grade and use them edto create a new Grade object.
!
ed
!
• Refresh
Th the display so that the new grade appears.
Th
is is
do oc d
cum um
ma n e m en
• Addrtaa.bcatch t be block to display a message to the ruser
l
a ta.
b
ift an
be exception occurs.
lon
arbo on a rbo
No gs No gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
Task 6: Run the application d! and verify that students can be added d! to and
removed from classes, and that grades can be added to students
• Password: password
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 68/71
10/25/2019 20483A - Programming in C# | Skillpipe
6. For the student Darren Parker, add a new grade by using the following
information:
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta be date rt a.b tb
• Date: .bcurrent
arbo
lon arb
elo
ng
No gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
m aB
• Subject: rEnglish
ize
dc
av
e rab
Ba
rbo
riz
ed
av
era arb
op s sa co bs os
ies s .co . pie s.c a.
all m sa om
llo
• Assessment: B owed we
d!
!
• Comments: Good
Th Th
Module
is
do Review
is
d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 69/71
10/25/2019 20483A - Programming in C# | Skillpipe
In this module, you have learned how to work with classes, interfaces, and generic
collections in Visual C#.
Question
Th
is
Th
is
do d oc
cum um
ma e n ma en
Which rof tb
ta. the following types is a reference type? rt a.b tb
b e lon elo
No arb gs No arb ng
un sao to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
Select the corrected answer. era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
Boolean we we
d! d!
Byte
Decimal
Int32
Th Th
is Object is
do d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
TestNYour
ou Knowledge
r bos gs
to
No
un os st
na a@ Ma a @ oM
uth pri au p art
ori m rta tho rim aB
ze a ve Ba riz av arb
dc rab rbo ed era
op s sa co b s os
ies s.c . pie s.c a.
Question all om sa om
ow llo
ed we
! d!
Which of the following types of member CANNOT be included in an interface?
Events
Th Th
is is
do d oc
c
Fields
um um
ma en ma en
rta tb rt a.b tb
.ba elo elo
r
No Indexers bo ng No arb ng
un s st un os st
a @ oM a @ oM
au pri art au pri art
tho m aB tho m aB
Methods riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
Properties llo llo
we we
d! d!
Question
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 70/71
10/25/2019 20483A - Programming in C# | Skillpipe
Question
You want to create a custom generic class. The class will consist of a linear collection of values,
and will enable developers to queue items from either end of the collection. Which of the following
should your class declaration resemble?
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 71/71
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
Contents:
is
do
cu
is
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho Module pri tho p rim art
av Overview
m rta aB
riz Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
Lesson 1: Creating llo Class Hierarchies
we
llo
we
d! d!
language. It is also one of the most powerful tools in your developer toolbox.
Essentially, inheritance enables you to create new classes by inheriting
characteristics and behaviors from existing classes. When you inherit from an
existing class and add some functionality of your own, your class becomes a more
T
his his T
specialized
do instance of the existing class. Not only ddoes
o this save you time by
cu cu
ma me ma me
reducing rta the amount
n tb
elo
of code you need to write, it also
r t a enables
nt
be you to create
.ba .ba lon
No r bo n gs N r bo gs
hierarchies
un ofsa related
@ to classes that you can then ouse
M un interchangeably,
sa
@ to
Ma
depending on
au pri art a uth pri
tho ma aB ori ma r ta
your requirements. riz
ed ve
r arb ze
d
ve
r
Ba
rbo
co ab o sa c op a b sa
pie ss . i ss .
sa .c om e sa . com
llo llo
w we
In this module, you willedlearn ! how to use inheritance to create class d! hierarchies and to
extend .NET Framework types.
Objectives
AfterThcompleting
is
this module, you will be able to:
Th
is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/43
10/25/2019 20483A - Programming in C# | Skillpipe
In this lesson, you will learn how to use inheritance to create class hierarchies.
Th Th
is is
do d oc
c
Lesson
ma
rt
Objectives
nt
b
um
e ma
rt
um
en
tb
a.b elo a.b elo
No arb ng No arb ng
o s st os st
After completing
una
uth
a @ this
pri
oM lesson,
art
you will be able to: un
au a @
p
oM
art
ori m aB tho rim aB
ze a ve arb riz av arb
dc rab ed era
op s os co b s os
ies s.c a. pie s.c a.
o m sa om
• Describe inheritance. a llo
we
llo
we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/43
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
In VisualautC#,
ho
a class
prim can
M a rta inherit from another class. auWhen pyou create
tho rim art a class that
riz av B r a aB
arb iz v arb
inherits from eanother
dc
op
era
class,
bs your
os
a
class is known as the derived ed
co
p
era
classbs and os the class
a.
ies s .co . ies s .co
a m a m
that you inherit from oisw known as the base class. The derived class
l l l l ow inherits all the
ed ed
! !
members of the base class, including constructors, methods, properties, fields, and
events.
Now you want to create a class to represent coffees. Coffee is a type of beverage. It
Th Th
i i
sharess all
cu
sd
do the characteristics and behaviors of a beverage.
oc
u
Rather than creating a
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/43
10/25/2019 20483A - Programming in C# | Skillpipe
class from scratch to represent coffees, you can create a class that inherits from the
Beverage class. The derived class inherits all the members of the Beverage class,
such as the servingTemperature field, the Name property, the IsFairTrade property,
and the GetServingTemperature method. Within the derived class, you just need to
add members that are specific to coffees.
Th Th
sd i sd i
The following
oc
u
example shows how to create a class ocfor coffees that inherits from the
u
ma me ma me
nt nt
Beverage
r t a.b class: be
lon
rt a.b be
lon
No arbo gs No arb gs
un sa to un os to
au @ Ma au a@ Ma
tho pri rta tho pri rta
riz m av Ba riz m av Ba
The Coffee Class e dc e rab rbo
sa
ed
co
era
b
rbo
sa
op s s . pie s s.c .
ies .co sa om
all m llo
ow we
ed d!
!
class means the same as saying the Coffee class inherits from the Beverage
class.
As you
T can see in the previous examples, the syntax
T for inheriting from a class is
his his
do do
similar to the
c um syntax for implementing an interface. This cu
me is because inheriting from a
ma en ma nt
rta tb r ta. be
class and .baimplementing
rbo
elo
ng
an interface are both examples b arb of inheritance.
lon However, you
No s No o gs
s t s t
do notunneed
au
tho
toa@
duplicate
pri
oM
art the base class members in
un
au the aderived
tho
@
pri
oM
class.
art By adding the
riz m av a B r m a aB
arb ize ve ar
base class toedyour co
era
class bs declaration,
os you make all the members dc
op
raof
bs the bbaseos class
pie s.c a. i e s . a.
sa o sa com
available to consumers llo of myour derived class. llo
we we
d! d!
The following example shows how to use base class members in a derived class:
When you create a class, you should consider whether you or other developers will
need to use it as a base for derived classes. You have full control over whether, and
how,Thyour
is
d
class can be inherited. Th
is
d
oc oc
um um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
arb
ng
Abstract Classes and Members
No
un
rbo
s a@
gs
to un
No
a @
st
os oM
au pri Ma au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
e
As part of an object-oriented rbo design, you may want to create e e
classes that
dc
op
rab
ss sa
dc
op
rab
s os serve solely
ies .co . ies s .co a.
as base classes for lother a low m
types. The base class may contain missing a llo mor incomplete
ed we
! d!
functionality, and you may not want to enable code to instantiate your class directly.
In these scenarios, you can add the abstract keyword to your class declaration.
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/43
10/25/2019 20483A - Programming in C# | Skillpipe
Note: You can only include abstract members within abstract classes. A non-
abstract class cannot include abstract members.
Sealed Classes
You Tmay
h want to create classes that cannot be Tinherited
h from. You can prevent
is is
do oc d
developers
m
umfrom inheriting from your classes by marking
e
c
m
um the class with the sealed
e
art nt art nt
a.b be a.b be
keyword.
N arb lon
gs No arb lon
gs
ou os to un os to
na a @ Ma au a@ Ma
uth pri rta tho pri rta
ori ma Ba riz m av Ba
ze ve rbo ed era rbo
The following dexample
co
pie
rab
s shows
s.c sahow
.
to use the sealed modifier:
co
pie b s s.c sa
.
sa om sa om
llo llo
we we
d! d!
Creating a Sealed Class
Th Th
is is
Any staticdoc class is also a sealed class. You can never do inherit from a static class.
um cu
ma en ma me
rta anyt static r nt
Similarly, .ba belo members within non-static classest a .ba are be not inherited by derived
lon
No rbo ng No rbo gs
un s s t un s to
classes. a@ oM a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
Creating Base Class Members llo
we
d!
llo
we
d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/43
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.brt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
You mayautwant
ho
@to
primimplement
M a rta
a method in your base auclass, but
tho
@
p rim allow art derived classes to
riz av B r a aB
arb iz v arb
replace your emethod dc
op
eraimplementation
bs o sa with more specific efunctionality.
d co
era
bs Tooscreate
a.
a
ies s .co . p ies s.co
member that developers all m override in a derived class, you use
can all themvirtual
ow ow
ed ed
! !
keyword.
Adding
Th Virtual Members Th
is is
do d oc
cum um
ma ent ma
en
rta be a.b tb
rt
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ Beverage o Ma na a @ oM
publicautclass
ho p rim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
{ co
pie b s s a c o pie b s os
a.
s.c . s.c
sa om sa om
protected intllowservingTemperature; llo
we
ed d!
!
public string Name { get; set; }
public bool IsFairTrade { get; set; }
public virtual int GetServingTemperature()
{
Th // This is the default implementation Th of the
is is
do do
cu
GetServingTemperature method. cu
ma me ma me
rta n tb r nt
.ba Because elo t a .ba be
// rbo ng the method is declared virtual,rbo
lon you can override
No s No gs
un s a@ t oM un s a@ to
au
the implementation pri art in a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
derived classes. co ss sa op ss sa
pie .c . i e . c .
sa om sa om
llo
return servingTemperature; llo
we we
d! d!
}
}
When you create a class, you can use access modifiers to control whether the
Th Th
is
members is
do of your class are accessible to derived types.
do You can use the following
c um c um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/43
10/25/2019 20483A - Programming in C# | Skillpipe
Access Details
Modifier
Members of a class are private by default. Private members are not inherited by
derived classes. If you want members that would otherwise be private to be
Th Th
accessible
is
d to derived classes, you must prefix the is member with the protected
d
oc oc
um um
keyword.
ma
rt
e nt
be
ma
rt
en
tb
a.b lon a.b elo
No arb gs No arb ng
un o sa to un os st
@ Ma a @ oM
au pri au p art
tho rta tho rim
Inheriting from a Base Class
riz
ed
co
m av
era Ba
rbo
riz
ed
co
av
era
aB
arb
os
pie b s sa pie b s a.
s.c . s.c
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au p au
t
To inherit hfrom
ori r
another
im rclass,
ta you add a colon followed tho by pthe rim name art
a Bof the base class
ze a ve Ba riz av arb
dc rab rbo ed era
op sa co bs os
to your class declaration. ies ss
.co . pie
sa
s.c
om
a.
all m llo
ow we
ed d!
!
The following example shows how to inherit from a base class:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/43
10/25/2019 20483A - Programming in C# | Skillpipe
The derived class inherits every member from the base class. Within your derived
Th Th
class, isyouc
is
do can add new members to extend the functionality
do
c
of the base type.
um um
ma en ma en
rta tb r t a.b tb
.ba elo elo
No rbo ng N arb ng
s o o st
A classun can only
au
sa
@ inherit
to
M from one base class. However,
un
au
syour
a @ classo M can implement one
tho prim a rta tho p rim art
r a B r a aB
or more interfaces i z ed ineraaddition
v arb to deriving from a base type.
o
iz ed vera arb
os
co bs sa co bs a.
pie s.c . pie s.c
sa om sa om
llo llo
we we
d! d!
Overriding Base Class Members
In some cases you may want to change the way a base class member works in your
derived class.
Th
For example, the Beverage base class includesThais method named
is
do do
um c cu
GetServingTemperature:
ma en
tb
ma me
nt
rta elo rt a.b be
.ba arb lon
No rbo ng No gs
un sa st un os to
@ oM a@ Ma
au p art au pri
t
Adding Virtualh ori r
Members
i m aB tho m rta
ze av arb riz av Ba
dc era ed era rbo
op b s os co b s sa
ies s.c a. pie s.c .
all o m sa om
ow llo
ed we
! d!
public class Beverage
{
protected int servingTemperature;
public virtual int GetServingTemperature()
T{h Th
is is
do do
um c cu
ma return en servingTemperature; ma me
rta tb r nt
.ba elo t a .ba be
ng lon
N}
ou r bos s N o r b o gs
na a@ t oM un s a@ to
uth pri art a uth pri Ma
// Other ori class
ma members
aB not shown. ori ma rta
ze ve a ze ve Ba
dc rab rbo dc rab rbo
} op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
The following example shows how to override a virtual method in a derived class:
Th Th
is is
do d oc
cum um
ma
public e maen
rt class
nt
a.b b
Coffee : Beverage
elo a.b rt tb
elo
No ar bo n gs No a r bo ng
{ un s a t o u s a
st
oM
au @ M n a @
tho pri art uth pri art
publicrizenew aint m a
GetServingTemperature()
Ba o riz m av aB
ve rbo e e arb
dc rab dc rab os
op s s sa o p s s a.
{ ies .co . ies .co
all m all m
ow ow
// … ed ed
! !
}
}
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/43
10/25/2019 20483A - Programming in C# | Skillpipe
When you use the override keyword, your method extends the base class method.
By contrast, when you use the new keyword, your method hides the base class
method. This causes subtle but important differences in how the compiler treats your
base class and derived class types.
When you override a base class member, you can prevent classes that derive from
your class from overriding your implementation of the base class member by using
the sealed keyword.
Th Th
is is
do
The following do
example shows how to seal an overridden base class member:
cu cu
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
sa
un an Overridden to un a@ to
Sealing au
tho
@
pri Ma Member
rta
au
tho pri Ma
rta
riz m av Ba riz m av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!
public class Coffee : Beverage
{
sealed public override int GetServingTemperature()
{
// Derived classes cannot override this method.
Th Th
is is
} do d oc
cum um
ma ent ma en
} r ta. be a.brt tb
ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa co s os
By sealing an overridden p ies s .comember, . you force any classes p
that ies derive s.cofroma. your class
all m all m
ow ow
to use your implementation e d of the base class member, rather than creating e d their own.
! !
You can only apply the sealed modifier to a member if the member is an override
member. Remember that members are inherently sealed unless they are marked as
virtual. In this case, because the base class method is marked as virtual, any
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/43
10/25/2019 20483A - Programming in C# | Skillpipe
descendants are able to override the method unless you seal it at some point in the
class hierarchy.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
You can use the base keyword to access base class methods and constructors from
within a derived class. This is useful in the following scenarios:
Th Th
i i
• Yous override
do
cu a base class method, but you stillswant
do
cu to execute the functionality in
m me m me
nt nt
theabase
rta
.b be method in addition to your own aadditional
classlo
rta
.b be functionality.
lo
No arb ng No arb ng
un os st un os st
a @ oM a@ oM
au p art au p art
• t
You create ori a new r t r
av method, but you want to call a base ori class av method a B as part of your
h i m aB h im
ze era arb ze era arb
dc b o dc b os
sa
method logic.opies ss
.co . op
ies s s.c
o
a.
all m all m
ow ow
ed ed
! !
• You create a constructor and you want to call a base class constructor as part of
your initialization logic.
Th Th
is is
do d oc
cum um
ma ma
Calling
rta Base
. be Class Constructors from a Derived
e nt
a.
en
tb
e
Class rt
ba lon ba lon
No rbo gs No gs rbo
un sa to un to sa
@ M @ Ma you create
You cannot
auth override
ori
pri
ma
constructors
art
aB
in derived classes.a uthInstead,
ori
pri when
ma rta
ze ve a ze ve Ba
d ca derived rab rbo dc rab call rbo
constructors in op ss class, sa your constructors will automatically
op ss the
sa default
ies .co . ies .co .
all m a m
base class constructor ow before they execute any of the logic thatlloyou
ed we have added.
! d!
However, in some circumstances, you might want your constructors to call an
alternative base class constructor. In these cases, you can use the base keyword in
your constructor declarations to specify which base class constructor you want to
call.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/43
10/25/2019 20483A - Programming in C# | Skillpipe
constructor.
// The declaration is implicitly equivalent to public Coffee()
: base()
// You can include additional code here.
Th Th
is is
} doc do
cu
um me
ma en ma nt
public
rta tb
Coffee(string name, bool isFairTrade,
r t a be int servingTemp,
. ba elon . ba lon
No rbo gs No rbo gs
string
un bean, s a@ string to un to sa
au Ma au Ma @
tho pri rta pri tho rta
r ma Ba riz ma Ba
roast) i ze ve ed ve
dc rab rbo rab rbo
op ss sa co ss sa
ies .c . pie . c .
: base(name, all om
isFairTrade, servingTemp) sa om
ow llo
ed we
{ ! d!
You can call base class methods from within method bodies or property accessors in
a derived class. To do this, you use the base keyword as you would use an instance
variable.
Th Th
is is
do do
The followingcu
me example shows how to call base class cumethods:
m
ma nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ a @ oM
Calling Base
a uth Class
pri
m
Methods
Ma
rta
au
tho p rim art
aB
ori a Ba riz av
ze ve rbo ed era arb
dc rab co b os
op s s.c sa pie s s.c a.
ies . sa
all om om
ow llo
ed we
! d!
public class Beverage
{
protected int servingTemperature;
public virtual int GetServingTemperature()
T{h Th
is is
do d oc
cu
return servingTemperature; um
ma me ma en
rta nt rt tb
} .bar be a.b elo
lon arb ng
No bo gs No osst
u s a@ to un a oM
//naConstructors
uth pri Ma and additional
rta
au
class members
tho
@ are
pri not
art shown.
ori ma Ba riz m av aB
ze ve rbo ed era arb
} dc rab co bs os
op ss sa pie s.c a.
ies .co . sa
a m om
public class Coffee llo
we : Beverage llo
we
d! d!
{
bool iced = false;
protected int servingTempIced = 40;
public override int GetServingTemperature()
T{h Th
is is
do d oc
if(iced)
cu
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/43
10/25/2019 20483A - Programming in C# | Skillpipe
{
return servingTempIced;
}
else
{
return base.GetServingTemperature();
Th Th
is is
do} d oc
c um um
ma nt e ma en
} rta. be rt a.b tb
ba lon elo
No rbo gs No arb ng
sa to os st
} un
au @ Ma un
au a @ oM
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
ow ll llo
Remember that the rules
ed of inheritance do not apply to static classes we
! d! and members.
As such, you cannot use the base keyword within a static method.
Demonstration Steps
Th Th
is is
do do
1. Start u c
the MSL-TMG1 virtual machine if it is not calready
um running.
ma m en ma en
rta tb r t a tb
.ba elo .ba elo
No rbo ng No rbo ng
s s s st
2. Start
un
au the a 20483-SEA-DEV11-05
@
pri
t o M art
virtual machine.
u n a uth
a @
pri
oM
art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs s co os
3. Log on to Windows p ies s .co8 as Student
a . with the password Pa$$w0rd. p ies s s.co a.
all m all m
ow ow
ed ed
! !
6. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.
10. In Solution Explorer, double-click Coffee.cs and review the contents of the
class.
11. Note that the Coffee class inherits from the Beverage class.
Th Th
is is
12. Notecumthat the Coffee class contains a default dconstructor
do oc
um and an alternative
ma en ma en
rta t be rta t be
constructor.
.ba
rbo
lon .ba
rbo
lon
No gs No gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
13. Note that m a o m
r ize the alternative
a ve Ba constructor explicitly callsizethe alternative
r a ve Ba constructor in
dc rab rbo dc rab rbo
op s s s a o p s s sa
the base class. i es
all
.co
m
. i es
all
. co
m
.
ow ow
ed ed
! !
14. In Solution Explorer, double-click Program.cs and review the contents of the
class.
15. Note that the Program class creates two instances of the Coffee type: one by
using the default constructor, and one by using the alternative constructor.
Th Th
is is
do do
c
um cu
16. mOn
art the e Build
n tb
menu, click Rebuild Solution.
m art
me
nt
a.b elo a . be
arb ng b arb lon
No o s N o o gs
un s a@ twice t oM un s a@ to
17. Pressau F11
tho pri so
art that the first line of executablea uth code pri in the Ma Program
rta
class is
riz ma aB ori ma Ba
e ve a ze ve
highlighted. dc
op
rab
ss
rbo
sa
dc
op
rab
ss
rbo
sa
ies .co . ies .co .
all m all m
ow ow
18. Press F11. Note that ed ed
! the debugger steps into the default constructor ! for the
Coffee class.
19. Press F11. Note that the debugger steps into the default constructor for the
Beverage class.
Th Th
is is
20. Point
do out that derived class constructors implicitly
cu
do
cu call the default base class
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/43
10/25/2019 20483A - Programming in C# | Skillpipe
21. Press F11 six times, until the debugger returns to the default constructor for the
Coffee class.
22. Point out that the base class constructor logic is executed before the derived
Thclass constructor logic. Th
is is
do do
cu cu
mPress me m me
23. art
a.b
F11
nt six times, until the debugger returns
b a r t a.b
to the
nt Program class.
be
elo lon
No arbo ng N a r b gs
un sa st ou os to
@ o M n a @ Ma
24. Pressau F11.p The second executable line of code au in thep Program
tho rim art
a t h o r im rta class should be
riz av Ba riz av Ba
ed era rbo ed era rbo
highlighted. co
pie b s s.c s a. c o pie b s s.c sa
.
sa om sa om
llo llo
we we
d! d!
25. Press F11. Note that the debugger steps into the alternative constructor for the
Coffee class.
26. Press F11. Note that the debugger steps into the alternative constructor for the
Beverage class.
Th Th
is is
do do
27. Hover cu over the Beverage constructor parameters,
m
cu
me and point out that the Coffee
ma en ma nt
rta t be has passed argument values to this rta be
constructor
.ba
rbo
lon .ba constructor.
rbo
lon
No gs No gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
28. Press iF11 m
sixvtimes, a Bauntil the debugger returns to iztheo m
ed alternative Ba constructor for
r ze a r a ve
dc era rbo r ab rbo
op bs s a co s sa
the Coffee class. i es s .co . p i es s. co .
all m all m
ow ow
ed ed
! !
29. Press F11 six times, until the debugger returns to the Program class.
31. When the console window appears, point out that it makes no difference to
Thconsumers of the class whether variables Twere his set by the derived class
is
do do
cu cu
me
mconstructor or the base class constructor. ma me
art nt rta nt
a.b be . be
arb l ong b arb lon
No o s N o o gs
un s a@ t oM un s a@ to
32. Pressau Enter
tho pri to close
art the console window. a uth pri Ma
rta
riz ma aB ori ma Ba
ed ve a rbo ze ve rbo
co rab dc rab
p ss sa op ss sa
33. Close Visual sStudio. i e
all
.c om
. i e sa . com
.
ow llo
ed we
! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/43
10/25/2019 20483A - Programming in C# | Skillpipe
The .NET Framework contains several thousand classes that provide a wide range of
functionality. When you create your own classes, you should look to build on these
classes by inheriting from .NET Framework types wherever possible. Not only does
this reduce the amount of code you need to write, it also helps to ensure that your
classes work in a standardized way.
Th Th
sd i sd i
The .NEToc Framework also enables you to create extension
u
oc
u
methods to add
ma me ma me
nt nt
functionality
r t a.b to esealed
b
lon .NET Framework types. Thisa.benables
r t be you to extend the
lon
No arbo gs No a rbo gs
functionality
una s
ofa built-int o types, such as the String class,
u na s
when
a theto inheritance
uth @ M uth @ Ma
pri art pri rta
ori ma aB ori ma Ba
approach is znot ed permitted.
co
ve
rab a rbo
ze
dc
ve
rab rbo
pie s s.c s a. o pie s s.c sa
sa sa .
om om
llo llo
we we
d! d!
In this lesson, you will learn how to extend .NET Framework types by using
inheritance and extension methods.
Lesson Objectives
T T
After hcompleting
is
do this lesson, you will be able to: his do
cu cu
ma me ma me
rta nt rt nt
.ba be a.b be
lon lon
arb
No rbo gs No o gs
• Create
un
au
classes
sa
@ that
to inherit from .NET
Ma
Framework
un types.
au
sa
@ to
Ma
tho pri rta tho pri rta
riz m av Ba riz m av Ba
ed era rbo ed era rbo
• Create custom co exception b s classes.
sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!
• Throw and catch custom exceptions.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/43
10/25/2019 20483A - Programming in C# | Skillpipe
There are almost 15,000 public types in the .NET Framework. Although not all of
these are extendable classes, many of them are. When you want to develop a class,
in many cases there is a built-in .NET Framework class that can provide a foundation
for your code.
There are two key advantages to creating a class that inherits from a .NET
Th Th
sd i sd i
Framework
oc class, rather than developing a class from
u
oc scratch:
u
ma me ma me
rta nt r nt
.ba belo t a.b be
ng a lon
No rbo st N ou r b os gs
u s a o a to
• Reduced
na
uth development
@
pri M art time. By inheriting from na an existing
uth @
pri class,
Ma
rta
you reduce the
ori ma aB ori ma Ba
amount ofzelogic dc
op
ve
thatrab you arbhave to create yourself.
os
ze
dc
o
ve
rab rbo
sa
ies s s a . p ies s s .
.co .co
all m all m
ow ow
• Standardized functionality. ed Just like implementing an interface, ed inheriting from a
! !
standard base class means that your class will work in a standardized way. You
can also represent instances of your class as instances of the base class, which
makes it easier for developers to use your class alongside other types that derive
from the same base class.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
rbo inheritance a rbo ng
TheNrules
ou of s a
gs
t o apply to built-in .NET No
Framework
u s a
classes st
o M in the same way
na @ Ma na @
uth pri rta u tho p rim art
they apply oto riz custom
ed
ma
v era
classes:B a riz
ed
av
era
aB
arb
rbo os
co b s s a c o b s a.
pie s.c . pie s.c
sa om sa om
llo llo
we we
• You can create a class d! that derives from a .NET Framework class, d! providing that
• You can override any base class members that are marked as virtual.
• If you inherit from an abstract class, you must provide implementations for all
Th Th
is is
abstractdoc members.
um
do
cu
ma en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz Ba
When you create ed
co
aveclass, aselect
rab rbo a base class that minimizes ze dc the
ve rabamount rbo of coding
pie ss sa o p s s sa
.co . ies .co .
and customizations required. all
ow
m If you find yourself replicating functionality all
ow
m that is
ed ed
available in built-in classes, ! you should probably choose a more specific ! base class.
On the other hand, if you find that you need to override several members, you should
probably choose a more general base class.
For example, consider that you want to create a class that stores a linear list of
Th Th
is sd i
values. dThe
oc
um
class must enable you to remove duplicate
oc
u
items from the list. Rather
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/43
10/25/2019 20483A - Programming in C# | Skillpipe
than creating a new list class from nothing, you can accomplish this by creating a
class that inherits from the generic List<T> class and adding a single method to
remove duplicate items. In addition, you can take advantage of the Sort method in
the List<T> class. If you call the Sort method, any duplicate items will be adjacent in
the collection, which can make it easier to identify and remove them.
Th Th
sd i sd i
The following
oc
u
example shows how to extend the List<T>
oc
u
class:
ma me ma me
rta nt r nt
.ba belo t a.b be
ng a lon
No rbo st N ou r b os gs
u s o to
Extending
na
uth a .NET
a @
pri Framework
M art Class na
uth
a @
pri Ma
ori ma aB ori ma rta
ze ve a ze ve Ba
dc rab rbo dc rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
public class UniqueList<T> : List<T> ! !
{
public void RemoveDuplicates()
{
base.Sort();
Th Th
is is
dofor (int i = this.Count – 1; i > 0; do i--)
cu cu
ma m en ma me
rta{ t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa to
if(this[i].Equals(this[i-1])) un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
{ed c era arb ze ve rbo
bs os d co r ab
op s.c a pie s s.c sa
ies . sa .
this.RemoveAt(i);
all om om
ow llo
ed we
! d!
}
}
}
}
Th Th
is is
do d oc
c um u
me
When
mayou use
rt nt this approach, consumers of your
b
e maclass
rt have
nt
b
access to all the
a.b elo a.b elo
arb ng arb ng
functionality
No
u osprovided
a
s t by the base List<T> class.
o
No They
u oalso
sa have
st
o
access to the
na @ Ma na @ Ma
u pri u p
additionalthRemoveDuplicates
ori
ze
ma
ve
rta
Ba
tho
method that you provided e
rim
riz in your
rta
av derived
Ba class.
dc rab rbo dc era rbo
op ss sa op bs sa
ies .co . ies s.c .
all m all o m
ow ow
Creating Custom Exceptions ed
!
ed
!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/43
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ a @ oM
The .NET au Framework
tho pri
m
Macontains
rta built-in exception classes
au
tho top represent
rim art most common
riz av Ba riz av aB
ed era rbo ed era arb
error conditions. co For example:
pie b s sa co
pie bs os
a.
s.c . s.c
sa om sa om
llo llo
we we
d! d!
• If you invoke a method with a null argument value, and the method cannot handle
null argument values, the method will throw an ArgumentNullException.
• If you attempt to divide a numerical value by zero, the runtime will throw a
DivideByZeroException.
Th Th
is is
do do
c
um cu
• If you
ma attempt en to retrieve an indexed item from maa collection,
me
nt and the index it outside
rta t b r t a be
.ba elo .ba l on
the
No bounds rbo of nthe
sa
gs collection, the indexer will Nthrow
ou ran
bo
s
gs
un @ t o na a @ to
au pri M art uth pri Ma
IndexOutOfRangeException.
tho
riz m av aB ori m a
rta
Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
Note: Most built-in exception classes are defined in the System namespace.
For more information about the System namespace, see the System
Namespace page at http://go.microsoft.com/fwlink/?LinkID=267804.
Th Th
is is
do do
When you cu need to throw exceptions in your code, you
m
cu should reuse existing
me .NET
ma en ma nt
rta tb r t bethere may be
Framework .ba exception
rbo
elo
ng
types wherever possible. However,a .ba
rbo
lon
No s No gs
un s a@wheno M t un s a@exception to
circumstances
au
tho pri you
art want to create your own custom
a uth pri Ma
rta
types.
riz ma aB ori ma B
ed ve arb ze ve arb
co rab os dc rab os
pie ss a . o p s s a.
sa .co ies .co
m m
When Should You Create a Custom Exception Type?
llo
we
a llo
we
d! d!
• Existing exception types do not adequately represent the error condition you are
identifying.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/43
10/25/2019 20483A - Programming in C# | Skillpipe
• The exception requires very specific remedial action that differs from how you
would handle built-in exception types.
Remember that the primary purpose of exception types is to enable you to handle
specific error conditions in specific ways by catching a specific exception type. The
Th Th
is is
exception
do type is not designed to communicate the
cu
doprecise details of the problem. All
cu
m me m me
art
exception nt include a message property forartthis nt
a.b classes
be
l a.b purpose.
be
l
Therefore, you
arb on arb on
No os gs No os gs
should nnot
u
au create
a @ a t custom
o M exception class just to
u n communicate
au a @ to the nature
Ma of an
tho pri art t h pri rta
riz m av a o rizyou needm av
error condition. ed Create era a B custom
arb exception class only if ed era to Bhandle
arb that error
co bs os co bs os
pie s.c a. pie s.c a.
condition in a distinct s a way.
llo
om sa
llo
om
we we
d! d!
• The Source property enables you to specify the item or application that caused
the error condition.
• The
Th Data property enables you to provide more
i
Th information about the error
i
sd sd
oc oc
condition
ma
umeas key-value pairs. ma
um
en
rta n tb r tb
.ba elo ta. elo
n b a ng
No r bo gs No r bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
When you create co a custom bs exception
sa type, you should make co use ab of these os existing
pie s.c . p ies s s a.
sa om .co
a m
properties whereverllopossible, we
d!
rather than creating your own alternative llo
we
d!
properties. At
a high level, the process for creating a custom exception class is as follows:
Th Th
is is
do oc d
cum um
ma e ma en
Note:
rta
.ba
When
n tb
elo you create a custom exception rclass,
ta. titb is a best practice
elo to
n b a ng
No include r bo the word gs Exception at the end ofNyour
o r
class
bo name. st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
pie s.c . p ies s s a.
sa om .co
llo a llo m
Throwing and Catching Custom Exceptions we
d!
we
d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/43
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c um um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un have sa s to o o
un yousacan st
After you @ created M your custom exception type, @ throwo M and catch custom
au p a au p art
tho rim rta tho rim aB
riz av B arb that you would throw and catch r iz a v arbexceptions. To
exceptions inedthe co same era way
bs o sa
ed
co any eraother
bs os
pie s.c . pie s.c a.
sa om sa om
throw a custom exception, llo
we
you use the throw keyword and create llo a new
we
instance of
d! d!
your exception type.
The following code shows how you can throw a custom exception:
Throwing
Th a Custom Exception Th
is is
do d oc
c um um
ma ent en ma
rta be a.b tb rt
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
publicautLoyaltyCard
ho p rim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
{ co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
public staticllowint GetBalance(string loyaltyCardNumber) llo
we
ed d!
!
{
var customer = LoyaltyCard.GetCustomer(loyaltyCardNumber);
if(customer == null)
{
To catch the exception, you use a try/catch block. Remember that you should always
attempt to catch the most specific exceptions first, and the most general exception
(typically System.Exception) last.
The following example shows how you can catch a custom exception:
Th Th
is is
do d oc
um c um
Catching
ma
rta a Custom
en
tb Exception ma
rt
en
tb
.ba elo a.belo
No rbo ng No arb
ng
un sa st un st
os
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
p
public bool PayWithPoints(int
ies s .co a. costInPoints, string p s
ies cardNumber)
.co a.
all m all m
ow ow
try ed ed
! !
{
int totalPoints = LoyaltyCard.GetBalance(cardNumber);
// Throws a LoyaltyCardNotFoundException if the card number is
invalid.
Th Th
if(totalPoints
is
do
>= costInPoints) is
do
cu cu
ma m en ma me
{ rta t r nt
.ba belo t a .ba be
n lon
No r b g
LoyaltyCard.DeductPoints(costInPoints);
o s N o r b o gs
un sa to un sa to
au @ M a uth @ Ma
t h pri art pri rta
returnori m
true;
a aB ori m a Ba
ze ve arb ze ve rbo
dc rab os d co r ab
opie s s.c a pie s s.c sa
} sa om
. sa om
.
llo llo
else return false; we we
d! d!
}
catch(LoyaltyCardNotFoundException)
{
// Take appropriate action to remedy the invalid card number.
Treturn
his false; Th
is
do d oc
cu um
} ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo
catch(Exception) gs No os st
un s a@ to un a oM
au Ma au @
t ho p r im rta tho pri art
{ riz av Ba riz m av aB
ed era rbo ed era arb
co b sa
ss unanticipated co bs os
// Catchespiesother .co . exceptions. p ies s .co a.
all m all m
ow ow
return false; ed! ed
!
}
Inheriting
T
from Generic Types Th
his is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/43
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
When you au inherit
tho primfrom M aarta generic class, you must decide
au
tho how p rim you awant
rta to manage the
riz av B arb r iz a v B ar
ed era ed era
type parameters co of the
pie bs base osclass. You can handle type parameters
a. co
pie bs inbtwo os
a.
ways:
s.c s.c
sa om sa om
llo llo
we we
d! d!
• Leave the type parameter of the base type unspecified.
Th Th
is i
Considerdo an example where you want to create ascustom
do list class that inherits from
c um c um
ma ne ma en
List<T>.rta If youbeleave the type parameter of the base
.ba
t
lon
rta type
.ba
t bunspecified, you must
elo
No rbo gs No rbo ng
st
includeunathe same sa
@ type
t o Ma parameter in your class declaration.
u na s a @ oM
uth pri r t u t h p r i art
ori m av aB ori m av aB
ze era a rbo zed era arb
dc b c b os
op s s.c s a o pie s s.c a.
ies .
The following example all
ow
showso m how to inherit from a generic bases all typemwithout
ow
o
ed ed
specifying a type argument: ! !
Th Th
is is
d
publicocclass CustomList<T> : List<T> do
um cu
ma en ma me
tb nt
{ } rta.b elo r t a . b
be
lon
No arb ng N arb gs
un o s s t o un o s to
a@ oM a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rb
In the above example,
co
pie swhen
s.c sa
you. instantiate the CustomList op
i class ss and oprovide
sa
. a type
sa om e sa . com
llo llo
we we
argument for T, the same d! type argument is applied to the base class. d!
Alternatively, you can specify a type argument for the base type in your class
declaration. When you use this approach, any references to the type parameter in the
base type are replaced with the type you specify in your class declaration.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/43
10/25/2019 20483A - Programming in C# | Skillpipe
The following example shows how to specify a type argument for a base type:
If the base class that you are inheriting from contains multiple type parameters, you
can specify type arguments for any number of them. The important thing to
Th Th
remember
is
do is that you must either provide a type argument
is
do or add a matching type
cu cu
me me
parameter
ma
rt tontyour
b
class declaration for each type
ma parameter
rt nt
b
in the base type.
a.b elo a.b elo
No arb ng No arb ng
un o sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
The following riz example
ed
av
era shows arb the different ways in which riz youacan
ed vera inherit arb from a base
co b s os co b s os
pietype parameters:
s.c a. pie s.c a.
type with multiple sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/43
10/25/2019 20483A - Programming in C# | Skillpipe
Regardless of how many—if any—type parameters the base type includes, you can
add additional type parameters to your derived class declarations.
The following example shows how to add additional type parameters to derived class
declarations:
Th Th
is is
d
Adding Type
o Parameters to Derived Class do
Declarations
cu cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
// Pass the ed base era type rboparameter on to the derived ed era
class, rboand add an
co b s s a. c o b s sa
pie s.c pie s.c .
additional type llo s a o m s a o m
llo
we we
d! d!
parameter.
public class CustomCollection1<T, U> : List <T>
// Provide an argument for the base type parameter, but add a new
type parameter.
public class CustomCollection2<T> : List<int>
Th Th
is is
//Inheritdo from a non-generic class, but add do
cu cu a type parameter.
ma m en ma me
rta class t b CustomCollection3<T> : CustomBaseClass
r nt
public .ba elo t a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a u @ Ma
tho p rim a rta p tho rim rta
riz av Ba riz av Ba
ed e rab rbo ed era rbo
co ss sa co b s sa
pie .co . pie s.c .
sa m sa om
llo llo
Creating Extension
we
d! Methods we
d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
In most cases, if youllowant we to extend the functionality of a class,lloyou we use inheritance
d! d!
to create a derived class. However, this is not always possible. Many built-in types
are sealed to prevent inheritance. For example, you cannot create a class that
extends the System.String type.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/43
10/25/2019 20483A - Programming in C# | Skillpipe
namespace FourthExtensionMethods;
Th Th
is is
{ do d oc
c um um
ma e nt ma en
rta
public be
static class FourthCoffeeExtensions
a.b tb rt
.ba lon elo
No rbo gs No a rbo ng
u s t u s st
{ nau a @ o Ma na a @ oM
th p r
im r ta u p im a th ta r r
ori av Ba ori av
publicze
d c static era bool
rbo ContainsNumbers(this ze String
d era s)Barb
op bs sa co bs os
ies s.c . pie s.c a.
{ all o m s all o m
ow ow
ed ed
!
// Use regular expressions to determine whether ! the string
contains any
numerical digits.
return Regex.IsMatch(s, @"\d");
}
Th Th
is is
} do d oc
c um um
ma e nt ma en
} r ta. be a.b rt tb
ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa co s os
To use an extension p ies method, s .co you
. must explicitly import the namespace p ies s.co that
a. contains
all m all m
ow ow
your extension method edby using a using directive:
!
ed
!
Th Th
usingis FourthExtensionMethods;
d
is
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/43
10/25/2019 20483A - Programming in C# | Skillpipe
You can then call the extension method as if it was an instance method on the type
that it extends:
You are also concerned about security. Teachers and students all require a
password, but it is important to maintain confidentiality and at the same time ensure
that students (who are children) do not have to remember long and complex
passwords. You decide to implement different password policies for teachers and
students; teachers' passwords must be stronger and more difficult to guess than
student passwords.
Th Th
is is
do d oc
cum um
ma nte ma en
Also, you a.b haveebeen asked to update the application tb
ba limit
to elo the number of students
r t b a rt
arb lon .
No g N r b ng
o sa s o o sa throws st
that canun be added
au @
p
to a class. You decide to add code
to M a
un
au that @
p
o M a custom exception
art
tho rim rta tho rim aB
riz av B r i a
if a user triesedtoc enroll era a student
bs
arb
o
in a class that is already zedat capacity.
co
vera
bs
arb
os
op s sa p s a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
Objectives
After completing this lab, you will be able to:
Scenario
In this exercise, you will create an abstract base class called User that contains the
UserName and Password properties, and the VerifyPassword method that is
common
Th to the Student and Teacher classes. Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/43
10/25/2019 20483A - Programming in C# | Skillpipe
You will modify the definitions of the Student and Teacher classes to inherit from the
User class, and remove the UserName and Password properties and the
VerifyPassword method from these classes.
Finally, you will build and run the application without making any other changes to the
application, and then verify that it still works correctly.
Th Th
is is
do d oc
cum um
ma nt e maen
r rttb
The main t a.b taskselfor this exercise are as follows:
arb
b
on
a.b
arb
elo
No g N ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
1. Create the ed User era abstract base class ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
2. Modify the Student d! and Teacher classes to inherit from the User d! class
3. Start Visual Studio and open the GradesPrototype.sln solution from the
E:\Labfiles\Starter\Exercise 1 folder.
4. In the Grade.cs file in the Data folder, create a new abstract class called User.
Th Th
is is
5. d
Addocuthe UserName and Password properties doto the User class.
cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
6. NoAdd the rbo VerifyPassword
s method to the User
N o r
class.b o gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
Note: Copy llo the code for the UserName and Password
we
llo
we properties and
d! d!
the VerifyPassword method from either the Student class or the
Teacher class. You must also add the private _password field to the
UserName class; this field provides the storage for the Password
property.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/43
10/25/2019 20483A - Programming in C# | Skillpipe
Task 2: Modify the Student and Teacher classes to inherit from the User class
1. In the Grade.cs file, modify the Student class to inherit from the User class.
Remove the UserName and Password properties, and the private _password
Th Th
field.
is
do Also remove the VerifyPassword method
is
do from the Student class.
cu cu
ma m en ma me
rta tb r nt
eloTeacher class to inherit from the User t a.b be
2. Modify
No
.ba the
rbo ng N a r b
class.lon Remove the
gs
un sa st ou os to
@ o n a @
UserName
au
tho pri and Password
m
M art
a
properties, and the au private
t h pri_password
m
Ma
rta field. Also
riz av B o r i a B
arb z v arb
removeethe op
era
d c VerifyPassword
bs
s
os
a
method from the Teacher ed
co class.
p
era
bs
s
os
a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
5. Select student Kevin Liu and verify that the report card listing the grades for this
student appears.
Results: After completing this exercise, you should have removed the duplicated
code from the Student and Teacher classes, and moved the code to an abstract
base
T class called User. T
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/43
10/25/2019 20483A - Programming in C# | Skillpipe
Scenario
T Th
his is
do oc d
um c um
In thisaexercise,
m
rta
e nt you will add an abstract method called m art eSetPassword
nt to the User
.ba belo a.b be
ng a l o ng the SetPassword
class.
No In the
un
rbo Teacher
sa s t and Student classes youNwill
oM o u implement
rbo
sa st
oM
au @ n au @
t pr a r t p r art
method. This h ori method
ze
i ma
ve
willta Bset the password for the user
arb
h ori (either
z
ima a teacher
v
aB
arb
or a
dc rab ed era
o co o
student). The SetPassword op
ies ss
.co
sa
method
. for a teacher will check piethat bthe ss password
.co
sa
. is at
all m sa m
o l l ow
least eight characterswlong ed
! and contains at least two numeric characters. ed
! The
SetPassword method for a student will check that the password is at least six
characters long. If the password meets these requirements, it is set and the method
will return true, otherwise it will return false.
You Twilld
Th
his then modify the set accessor of the Password
is
d property in the User class to
oc oc
me u me u
call the
ma SetPassword
rt nt
b
method to change the user's
ma password.
rt nt
b
a.b elo a.b elo
No arb ng No arb ng
un o sa st un os st
@ oM a @ oM
au p art au p art
tho rim a B feature tho rim aB
Next, you will riz integrate
ed
av
era
this arb into the user interface riz of the
ed
av application
era arb to enable
co b s os co b s os
a. a.
a user to changepietheir sa
s.c
password.
om
pie
sa
s.c
om
llo llo
we we
d! d!
Finally, you will build and run the application to test the password functionality.
Th Th
is is
1. Define
do
cu the SetPassword abstract method
d
um
oc
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a
2. NoImplementr bo
s
the
gs SetPassword method in the
t
NoStudent r bo and
s
ng Teacher classes
st
un a @ o M u n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
3. Set the passworde dc e rab for a rbonew student e dc e rab
op s sa o s os
ies s .co . p ies s.co a.
all m all m
ow ow
4. Change the password ed for an existing user ed
! !
2. In the User class, define a public abstract method called SetPassword. This
method should take a string parameter containing the password and return a
Boolean value indicating whether the password has been set successfully.
Th Th
is is
do do
3. In the cu User class, modify the set accessor of the
me
cu Password property to call the
me
ma n m a n
rta tb r t a.b tot bthe
SetPassword
.ba
rbo
elo
ng method rather than directly writing a rbo
elo _password field. Throw
ng
No s No st
un sa to un sa oM
anaArgumentException
uth @
pri M art exception if the SetPassword
au
t h
@
p r i
method art returns false.
ori ma aB ori ma aB
ze ve arb zed vera arb
dc rab os co bs os
op s s a . p s a.
ies .co ies .co
all m all m
ow ow
ed ed
! !
Task 2: Implement the SetPassword method in the Student and Teacher classes
1. In the User class, make the _password field protected rather than private; it
Thneeds to be accessible in the Student andThTeacher classes.
is is
do do
cu cu
ma m en ma me
nt
2. Inrtathe
.ba Student
t belo class, implement the SetPassword
r t a .ba method.
be
lon
The method should
No rbo n gs No rbo gs
verify sa the tpassword sa is at least
au that specified as the parameter Ma six characters
un @ oM un @ to
pri art au pri
tho m aB t h ori m rta
long. Ifriztheed password
av
era aris
b of
os
sufficient length, then populate
ze
d
av the _password
era Ba
rbo field
co b s a co b s sa
pie s.c . pie s.c .
and return true; s a otherwise,
llo
om return false. sa
llo
om
we we
d! d!
3. In the Teacher class, implement the SetPassword method. The method should
verify that the password specified as the parameter is at least eight characters
long and contains at least two numeric characters. If the password is of
sufficient complexity, then populate the _password field and return true;
Thotherwise, return false. Th
is is
do d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un s to u oM
au Note: a@ You
pri Mwill
art need to use the followingauregular
n a @ expression
pri art to verify the
tho ma aB tho m aB
rvalidity
ize of
ve the password:
arb riz av arb
dc rab ed era
op s os co bs os
ies s .co a. pie s.c a.
all m sa om
ow llo
ed we
! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/43
10/25/2019 20483A - Programming in C# | Skillpipe
1. In the code for the StudentsPage view, locate the NewStudent_Click method.
This method runs when a teacher creates a new student.
2. In this method, modify the statement that sets the password for the new student
Th Th
toisdcall
oc the SetPassword method. If the password
is
do
cu
is not sufficiently complex and
um me
ma en ma
therta method
.ba
t b returns false, throw an Exception
elo rta withnt a
.ba be suitable error message.
ng lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
Note: co If you
pie b s were
s.c shappy
a. with the default exception c o pie thrown
b s s.c bysausing
. the
sa om sa om
Password llo property, you could retain the code as is.lloHowever, in this
we we
d! d!
case you have decided to throw a different exception with a more
meaningful and less generic error message, so you chose to call the
SetPassword method directly.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
r arb ng
Tasko4:
N
un
Changeb o sa the
gs password
to for an existingNouser
u os
a
st
oM
au @ Ma na @
tho pri rta uth pri art
riz m av Ba ori m av aB
ed era rbo ze era arb
co b dc b os
pie s s.c sa op s s.c a.
sa . ies
1. Build the solution. om all o m
llo ow
we ed
d! !
2. In the XAML definition of the MainWindow window, find the definition of the
Change Password button. When the application runs, this button appears at
the top of the page. If the user clicks this button, the ChangePassword_Click
method runs.
Th Th
is is
do oc d
3. In the
m
umMainWindow.xaml.cs file, review the ChangePassword_Click
e
c
m
um
e
method.
ar nt ar nt
ta. be ta. be
N
This bamethod
rb
lon displays a dialog called ChangePasswordDialog
g N
ba
rb
lon
g
that enables a
ou os st ou os st
na a@ oM na a@ oM
useruthto changepri
ma
their
art password.
aB
uth pri
ma
art
aB
ori ori
ze ve a rbo ze ve arb
dc rab dc rab os
op s s sa o p s s a.
ies folder, .co review . ies .co window.
4. In the Controls all m the ChangePasswordDialog.xaml all m This
ow ow
window contains ethree d! text boxes that prompt the user to provide ed
! their old
password, enter a new password, and confirm the new password. When the
user clicks OK the new password is set.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta b rt
a.b tb
.ba elo elo
NoFIGURE rbo ng N arb ng
un sa 5.1: s THE
to CHANGEPASSWORDDIALOG o un o saWINDOW st
oM
au @ M au @
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
o os
5. Examine cthe op code
ies s .co .
co
bs in thesaok_Click method in the ChangePassword.xaml.cs
p ies
bs
s .co a.
all m all m
ow ow
file. This method eruns
d! when the user clicks OK in the Change ed Password dialog
!
box. Currently, this method does nothing.
b. Verify that the old password specified in the dialog is correct by using the
VerifyPassword method of the User class. If the password is incorrect,
display a message and return from the method without changing the
Th
is password. Th
is
do d oc
cum um
ma e nt ma en
r
c.ta.ba Verify be that the new password and confirm rt
a.b password tb text boxes in the
lon elo
No r bo gs No a r bo ng
sa to sa s to
au dialog @ contain Ma the same value. If they are
un un different, @ display
Ma a message and
pri au p
tho ma r ta t ho r im rta
riz B r i a B
return ed
co
ve the amethod
from rab rbo without changing thezepassword. dc
ve
rab arb
os
pie ss sa o p s s a.
sa .co . ies .co
llo m a llo m
we
d. Set the password d! by using the SetPassword method wof ed the current user. If
!
this method returns false, display a message and return without changing
the password.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/43
10/25/2019 20483A - Programming in C# | Skillpipe
Task 5: Run the application and test the change password functionality
4. Change the password for the current user. First try setting it to a password that
is insufficiently complex, and then change it to password101.
5. Log out and then log back in again as vallee, and verify that the password has
Th Th
is is
do changed to password101.
been d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a ng
6. NoCreate rbo a new gs student and verify that the student No rbpassword
o s t must be at least six
un sa t o u na s a oM
au @ Ma u @
tho p rim rta tho p rim art
characters riz
ed
long.
av Use B a
the Enroll Student feature rto
ized
verify av that athe Ba student is
era rbo era rbo
co b ss sa c op b ss sa
successfully piecreated.
sa .co . i es . co .
llo m a llo m
we we
d! d!
7. Log off and then close the application.
Th Th
is is
do do
Results: cu After completing this exercise, you should
m
cuhave implemented a
me
ma en ma nt
polymorphic
rta
.ba
t bmethod named SetPassword that exhibits
elo r t a .ba bdifferent
elo behavior for
No rbo ng No rbo ng
students
un and sa teachers.
@
s to You will also have modified
un thesaapplication @
s to to enable users
au p Ma au p Ma
to change t ho their im r passwords. r ta t ho r im r ta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b ss sa c op b ss sa
pie .c . i e . c .
sa om sa om
llo llo
we we
d! d!
Scenario
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/43
10/25/2019 20483A - Programming in C# | Skillpipe
In this exercise, you will create a new custom exception class called
ClassFullException. You will modify the EnrollInClass method of the Teacher class
to raise this exception if too many students are added to a teacher's class. You will
update the application to catch this exception, and then you will build and run the
application to test this feature.
Th Th
sd i is
The main
oc tasks for this exercise are as follows:
u um
d oc
ma me ma en
rta nt rt tb
.ba belo a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
1. Implement @ the ClassFullException
M class @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
2. Throw and catch p ies the
s .co ClassFullException
. p ies s .co a.
all m all m
ow ow
ed ed
! !
3. Build and test the solution
3. Add a private string field called _className and a public virtual read-only
string property called ClassName to the ClassFullException class. This
property should return the value in the _className field. The _className
Th Th
field
is
do will hold the name of the class that is full
is when the exception is raised.
do
cu cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
4. lon
NoAdd a rbodefault ng public constructor to the ClassFullException
s No rbo gs class. This
un s a t o u n s a t o
au @ Ma au @ M
constructor
tho pri should
ma rtasimply delegate its responsibilities tho prto
im the aequivalent
rta
riz ve B a r iz a v Ba
ed rab rbo e dc e rab rbo
constructoropiin c
es
thessException
.co
sa
. class. op
ies ss
.co
sa
.
all m all m
ow ow
ed ed
5. Add a public constructor ! to the ClassFullException class that ! takes a string
7. Add a public custom constructor that takes the exception message and the
name of the class that is full as parameters. Invoke the Exception constructor
with the exception message, but store the name of the class in the _className
Thfield. Th
is is
do do
cu cu
ma me m me
rta n tb a r nt
8. Add.baar public elo custom constructor that takes the t a.bexception be
ng a lon message, the name of
No bo s N o r b o gs
un sa to un sa to
theauclass
tho
@that
pri is full, M art and an Exception objectacontaining uth @
pri an Mainner exception as
rta
riz m av a Ba o riz m av Ba
parameters. e dc e
Invokerab therbo Exception constructor withdthe e e
exception
rab rbomessage and
op s s a c o s sa
ies s .co . p ies s.co .
the inner exception, a llo m
but store the name of the class in the a ll_classNamem field.
we ow
d! ed
!
Th Th
is is
do do
1. In the c Teacher class, add a private constant cu
integer
ma
um en ma me field called
rta t r nt
.ba belo t a .ba 8.beThis
MAX_CLASS_SIZE
No rbo n gs and initialize it with the
No value rbo
lon
gs field specifies the
un sa t o u na s a to
au @ Msize @ Ma
maximum tho pclass
rim art for a teacher.
aB
uth
ori
pri
m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
2. In the EnrollInClass sa
llo
ommethod of the Teacher class, if thes acurrent
llo
om number of
we we
students is alreadyd! equal to the value in MAX_CLASS_SIZE,d!then throw a
ClassFullException with a suitable message and the name of the class that is
full (the name of the class is available in the Class property of the Teacher).
4. Add a catch handler after the try block that catches the ClassFullException.
In this catch handler, display a suitable message that includes the exception
Th Th
message
is
do and class name from the exception.
is
d
cu oc
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/43
10/25/2019 20483A - Programming in C# | Skillpipe
Question
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/43
10/25/2019 20483A - Programming in C# | Skillpipe
Question
Which of the following types of method must you implement in derived classes?
Th Abstract methods. Th
is is
do d oc
cu um
me
ma Protected ma en
rta nt methods. rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
unPublic smethods.
a @ to
Ma un a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
Static methods.co b s sa co bs os
a.
pie s.c . pie s.c
sa om sa om
llo llo
Virtual methods. wed! we
d!
Question
Th Th
is is
do do
uc cu
You mwant tomcreate
en an extension method for the String class.
ma You
me create a static method within a
art t r nt
a.ba Howeldo
static class. b you indicate that your method extends the t a .ba String be type?
on lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
Select the correctcanswer. bs os d co r ab
op s.c a pie s s.c sa
ies . sa .
all om om
ow llo
The return type of the ed method must be a String. we
! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/43
10/25/2019 20483A - Programming in C# | Skillpipe
Contents:
Th Th
is is
do d oc
cum um
ma nt e ma en
rta be rt a.b tb
elo
rbo Module Overview
.ba lon arb
No gs No ng
un sa t un os st
@ o Ma a @ oM
au pri au p art
tho m rta tho rim aB
Lesson 1: rizeReading
dc
av
e rab
and Ba Writing Files
rbo
riz
ed
av
era arb
op s sa co bs os
ies s .co . pie s.c a.
all m sa om
Lesson 2: Serializing l
ed and Deserializing Data
ow l ow
ed
! !
Objectives
After completing this module, you will be able to:
hisT his T
• Read doand write data to and from the file system dby
o
using file I/O.
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/62
10/25/2019 20483A - Programming in C# | Skillpipe
• Convert data into a format that can be written to or read from a file or other data
source.
• Use streams to send and receive data to or from a file or data source
T T
Lesson
his
do
cu 1 : Reading and Writing Files
m
his
do
cu
m
ma en ma en
rta tb rta tb
.ba elo .ba elo
No rbo ng N r b ng
un sa s to o un o sa st
@ M @ oM
au au
The .NETthFramework
ori
pr i ma provides
a r taB the System.IO namespace, t h ori
p r i which
ma
arcontains
ta
Ba
a number
ze ve a r ze ve rbo
d rab bo dc rab
of classes that chelp op
ies simplify
s s .co
applications
s a . that require I/O functionality.
o p ies s s.co
sa
.
all m all m
ow ow
ed ed
! !
In this lesson, you will learn how to use the classes in this namespace to read and
write data to and from files, and to manipulate files and directories on the file system.
Lesson Objectives
Th Th
is is
do do
After completing
cu
m this lesson, you will be able to: cu
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
un sa to un sa to
@ M @ Ma
• Read uand
a
tho write pri data
m
artby using the File class.
aB
a uth
ori
pri
m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
• Manipulate filess by all using om the FileInfo and the File classes.s a
llo
om
ow we
ed d!
!
• Manipulate directories by using the DirectoryInfo and Directory classes.
Th Th
is is
Reading
m
um and Writing Data by Using the
e
do
c
m
do
cu
me File Class
art nt art nt
a.b be a.b be
arb lon arb lon
No o gs No os gs
un s a@ to un a@ to
au pri Ma au pri Ma
tho ma rta tho ma rta
riz ve Ba riz ve Ba
ed rab rbo ed rab rbo
co ss sa co ss sa
pie .c . pie . c .
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/62
10/25/2019 20483A - Programming in C# | Skillpipe
The File class in the System.IO namespace exposes several static methods that you
can use to perform atomic operations for direct reading and writing of files. These
methods are atomic because they wrap several underlying functions into a single
method call. Typically, to read data from a file, you:
The static methods that the File class exposes are convenient because they
encapsulate intricate, low-level functions. However their convenience and the fact
that they shield the developer from the underlying functionality means in some cases
hisT his T
they don’t
do offer the control or flexibility that applications
c
do
c
require. For example, the
um um
ma en ma en
ReadAllText
rta
.
tmethod
be will read the entire contents rof
ta. a file
t b into memory. For small files
e
ba lon ba lon
No rbo gs gs No rbo
this will
un be fine,
a
sa but tfor
@ o M large files it can present scalability
un
a
sa issues,
@ to and may result in
M
uth pri art uth pri art
ori ma aB ori ma aB
an unresponsive
ze
d
UIvein
r
yourarbapplication. ze
d
ve
rab arb
co ab os co os
pie ss a. pie s s.c a.
sa .co sa om
llo m llo
we we
Reading Data from Files d! d!
The File class provides several methods that you can use to read data from a file.
The format of your data and how your application intends to process it will influence
the method that you should use. The following list describes some of these methods:
Th Th
is is
do do
uc cu
• The
ma ReadAllText
m en method enables you to read
ma the contents
me
nt of a file into a single
rta tb r t a b
.ba elo .ba elo
string
No variable.
rbo ngThe following code example N
s shows
o rbhow
o tongread
st the contents of the
un s a t o u n s a oM
au @ M a uth @
settings.txt
tho pri into a
file art string named settings. pri art
riz ma aB ori ma aB
ed ve a r ze ve arb
co rab b os d co r ab os
pie ss a . p ies s s a.
sa .co .co
llo m a llo m
we we
string filePath = "C:\\fourthCoffee\\settings.txt";d!
d !
• The ReadAllLines method enables you to read the contents of a file and store
Th T
each
is line at a new index in a string array. Thehfollowing
d
is
d code example shows how
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/62
10/25/2019 20483A - Programming in C# | Skillpipe
to read the contents of the settings.txt file and store each line in the string array
named settingsLineByLine.
Each of these methods enables you to read the contents of a file into memory. You
could use the ReadAllText method if you wanted to cache the entire file in
memory
T
in a single operation. Alternatively, ifT you wanted to process a file line-by-
his his
line, dyou
oc could use the ReadAllLines method todoread
um cu
m
each line into an array.
ma en ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av riz av
Writing Data to Files
ed
co
era
b s
arb
os
a.
ed
co
era
b s
arb
os
a.
pie s.c pie s.c
sa om sa om
llo llo
The File class also provides we methods that you can use to write different we types of data
d! d!
to a file. For each of the different types of data you can write, the File class provides
two methods:
• If the specified file does not exist, the Writexxx methods create a new file with the
Th Th
newis data. If the file does exist, the Writexxx methods
do
is
do overwrite the existing file
cu cu
ma themnew
with me
t b data.
en ma nt
rt a.b elo rt
a be
arb . b arb lon
No ng N gs
un o s s t o un o s to
a@ oM a@ Ma create a new file
• If the specified
auth
ori
pri file does
ma
art
aB
not exist, the Appendxxx a uthmethods
ori
pri
ma
also rta
ze ve a ze ve Ba
d c data.rabHowever, rbo dc rbo
rab is written
with the new op ss sa if the file does exist, the new op data ss sa to the end
ies .co . ies .co .
all m all m
of the existing file. ow
ed
ow
ed
! !
• The
Th WriteAllText method enables you to write
i
Th the contents of a string variable to
i
sd sd
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/62
10/25/2019 20483A - Programming in C# | Skillpipe
a file. If the file exists, its contents will be overwritten. The following code example
shows how to write the contents of a string named settings to a new file named
settings.txt.
string
Th
is settings = "companyName=fourth coffee;";
Th
is
do do
cum cu
ma e m me
rta n tb a r nt
.ba elo t a.b be
lon
File.WriteAllText(filePath,
No rbo ng
st settings); N ou
a r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
• The WriteAllLines e dc e rabmethod rbo enables you to write the contents
s
e dc e raof
b
a string
rbo
sa
array to a
op s s a . o p s s .
ies .co ies .co
file. Each entry inallothe we
string
m array represents a new line in the all file. m
ow The following
d! ed
!
code example shows how to write the contents of a string array named hosts to a
new file named hosts.txt.
T
his rawSettings = {99,111,109,112,97,110,121,78,97,109,101,61,102,111,
his T
byte[]
do do
cu cu
ma me mame
rta nt rt nt
.ba belo a .ba be
ng lon
N r b N r b gs
117,114,116,104,32,99,111,102,102,101,101};
ou
na
os
a@
s t oM o un o s a@ to
uth pri art a uth pri Ma
ori ma aB ori ma rta
ze ve a ze ve Ba
dc rab rbo dc rab rbo
op ss sa op ss sa
File.WriteAllBytes(filePath,
ies
all
.co
m
rawSettings);
. ies
all
.co
m
.
ow ow
ed ed
! !
• The AppendAllText method enables you to write the contents of a string variable
to the end of an existing file. The following code example shows how to write the
contents of a string variable named settings to the end of the existing settings.txt
file.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/62
10/25/2019 20483A - Programming in C# | Skillpipe
File.AppendAllText(filePath, settings);
Each of these methods enables you to write data to a file. If you want to add data
toThan d
T
is existing file that may already exist, then hyou
is
d
should use an Appendxxx
oc oc
me u me u
method.
ma
r
Ifntyou want to overwrite an existing file,
ma then
r nyou
t should use a Writexxx
ta. be ta. be
ba lon ba lon
method.
N ou r bThen,
os
a@
gdepending
st
oM
on how you want Nthe
o un
information
r b o sa
gs is stored (whether
to as
na a @ Ma
uth pri art uth pri rta
binary data, ori
ze
a textual
m a ve
ablob
Ba in a string, or an array of o rstrings
ize
m a representing
ve Ba each
dc rab rbo dc rab rbo
op use the sa
ss xxxAllBytes, op ss method. sa
individual line) ies .co . xxxAllText, or xxxAllLines ies .co .
all m all m
ow ow
ed ed
! !
Manipulating Files
Th Th
is is
do d oc
c um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
As well as reading from and writing to files, applications typically require the ability to
interact with files stored on the file system. For example, your application may need
to copy a file from the system directory to a temporary location before performing
some
Th further processing, or your application may
is
Th need to read some metadata
is
do do
c um cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/62
10/25/2019 20483A - Programming in C# | Skillpipe
associated with the file, such as the file creation time. You can implement this type of
functionality by using the File and FileInfo classes.
• The Delete method enables you to delete an existing file from the file system. The
Th Th
is is
d
following do
um code example shows how to delete the existing settings.txt file.
oc cu
ma en ma me
rta tb rta n tb
.ba elo .ba elo
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri ar= a uth pri art
string tho filePath m ta "C:\\fourthCoffee\\settings.txt";
o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
File.Delete(filePath); co bs sa co s os
pie s.c . p ies s.co a.
sa om a m
llo llo
we we
d! d!
• The Exists method enables you to check whether a file exists on the file system.
The following code example shows how to check whether the settings.txt file
exists.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/62
10/25/2019 20483A - Programming in C# | Skillpipe
• The GetCreationTime method enables you to read the date time stamp that
describes when a file was created, from the metadata associated with the file. The
Th Th
is is
following
do
cu code example shows how you can determine
do
cu when the settings.txt file
m me ma me
nt
wasartcreated. rt nt
a.b be a.b be
arb l on lon arb
No o stg No os gs
un sa o u n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
string filePath co b s = "C:\\fourthCoffee\\settings.txt";
s a. c o b s sa
pie s.c pie s.c .
sa om sa om
DateTime settingsCreatedOn l l ow = File.GetCreationTime(filePath); l l ow
ed ed
! !
There are many other operations and metadata associated with files that you can
utilize in your applications. The FileInfo class provides access to these through a
number of instance members.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
st
File Manipulation by using the FileInfo class
un
au
tho
sa
@
p rim
t o Ma u na
u tho
s a @
p rim
oM
art
rta aB
riz av B a riz av arb
ed era rbo ed era
c b c b os
The FileInfo class op provides
ies s s.c instance
s a . members that you can o use
pie tos manipulate
s.c a. an
all o m s all o m
ow ow
existing file. In contrast edto the File class that provides static methods
!
ed for direct
!
manipulation, the FileInfo class behaves like an in-memory representation of the
physical file, exposing metadata associated with the file through properties, and
exposing operations through methods.
The Tfollowing
his Th an instance of the FileInfo class
code example shows how to createis
do do
um c cu
that represents
ma en the settings.txt file.
tb
ma me
nt
rta elo rt a.b be
.ba arb lon
No r bo ng No gs
un s st un os to
a @ oM a@ Ma
au pri art au pri
Instantiatingt tho rta
riz the aFileInfo a B Class
h o m ma
ve arb riz ve Ba
ed rab ed rab rbo
co ss os co ss sa
pie .co a. pie . .
sa sa com
llo m llo
we we
d! d!
string filePath = "C:\\fourthCoffee\\settings.txt";
FileInfo settings = new FileInfo(filePath);
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/62
10/25/2019 20483A - Programming in C# | Skillpipe
After you have created an instance of the FileInfo class, you can use the properties
and methods that it exposes to interact with the file. The following list describes some
of these properties and methods:
• The CopyTo method enables you to copy an existing file to a different directory on
the file system. The following code example shows how to copy the settings.txt file
Th Th
is is
from thed do directory.
o cu C:\fourthCoffee\ directory to the C:\temp\ cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
string pri
tho sourceSettingsPath art = t
"C:\\fourthCoffee\\settings.txt";
h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
c o
string destinationSettingsPath b s s a. = "C:\\temp\\settings.txt"; c o b s sa
pie s.c pie s.c .
sa om sa om
llo llo
bool overwrite w=ed true; we
d!
!
FileInfo settings = new FileInfo(sourceSettingsPath);
settings.CopyTo(destinationSettingsPath, overwrite);
Th
is
Note: The overwrite parameter passedThto is
the CopyTo method call
do do
indicates
cu
me that the copy process should overwrite cu
me an existing file if it exists
ma n ma
t
rta at thebdestination
elo path. If you pass false to rta the nCopyTo
tb
elo method call, and
.ba .ba
No rbo n gs No rbo ng
un the file sa already to exists, the CLR will throwunaa System.IO.IOException.
sa s to
au @ Ma uth @ Ma
tho pri rta pri rta
riz m av Ba o r m a Ba
ed era ize ve
rbo d r ab rbo
co b s s a co s sa
pie s.c . pie s.c .
sa om sa om
llo llo
• The Delete methodweenables d! you to delete a file. The followingwcode ed
! example
shows how to delete the settings.txt file.
• The Exists method enables you to determine if the file exists within the file
system. The following code example shows how to check whether the settings.txt
file exists.
string
T filePath = "C:\\fourthCoffee\\settings.txt";
T
his his
do do
FileInfo
cu
m settings = new FileInfo(filePath);
cu
m
ma en ma en
rta be t rta be t
bool .bapersistedSettingsExist
lon = settings.Exists;
.ba lon
No rbo gs No gs rbo
un sa to un sa to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
• The Extensionsproperty all om enables you to get the file extension s a of aom
l l
file. The
ow ow
ed ed
following code example ! shows how to get the extension of a path ! returned from a
method call.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b rta.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
It is a common
au
tho requirement
prim
M a rta for applications to interactau andpmanipulate
tho rim art the file system
riz av B r a aB
ed era arb ized vera arb
directory structure, co
pie
whetherbs oto
sa check that a directory exists co before
pie bs writing os a file or to
a.
s.c . s.c
sa om sa om
remove directories when l l ow running a system cleanup process. The l l ow .NET Framework
ed ed
! !
class library provides the Directory and DirectoryInfo classes for such operations.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d o
• The c
method enables you to determinemif a cdirectory
m Exists exists on the file
um um
e art nt e art nt
a.b b b
system.
N
eo
arbThe lfollowing
ng code example shows Nhowa.bto elo
arbdetermine
ng if the
ou os st ou os st
na a@ oM na a@ oM
C:\fourthCoffee\tempData
utho prim a rta directory exists. u tho p rim art
aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
string directoryPath d! = "C:\\fourthCoffee\\tempData"; d!
• The GetDirectories method enables you to get a list of all subdirectories within a
specific
Th
is directory on the file system. The following
Th
is code example shows how to get
do do
uc cu
a list
ma of all m en the sub directories in the C:\fourthCoffee\tempData
ma me
nt directory.
rta t b r t a be
.ba elo .ba l on
No rbo ng No rbo gs
un sa st u s to
@ o M na a @ Ma
au pri art uth pri
tho m aB o m rta
r
string izdirectoryPath ave r
arb = "C:\\fourthCoffee\\tempData"; ize a ve Ba
ed rab d r ab rbo
co s os co s sa
pie s.c a . pie s.c .
string[] subDirectories sa om = sa om
llo llo
we we
d!
Directory.GetDirectories(directoryPath); d!
• The GetFiles method enables you to get a list of all the files within a specific
directory on the file system. The following example shows how to get a list of all
Th Th
the isfiles in the C:\fourthCoffee\tempData directory.
d
is
d
oc oc
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
u s t u s st
string
n a
directoryPath
@ o M = "C:\\fourthCoffee\\tempData";
n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
e e
string[]d cfilesrab= Directory.GetFiles(directoryPath);
rbo e dc e rab
op s sa o s os
ies s .co . p ies s.co a.
all m all m
ow ow
ed ed
! !
The DirectoryInfo class provides instance members that enable you to access
directory metadata and manipulate the directory structure.
Th
Manipulating
is
do Directories by using the TDirectoryInfo
his
do Class
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/62
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to create an instance of the DirectoryInfo
class that represents the C:\\fourthCoffee\\tempData directory.
Th Th
is is
do d oc
cum um
ma e
nt enma
r tbrt
Instantiating
t a.b
arb
the
belo DirectoryInfo Class a.b
arb
elo
No ng N ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
string directoryPath sa om= "C:\\fourthCoffee\\tempData"; sa om
llo llo
we we
d! d!
DirectoryInfo directory = new DirectoryInfo(directoryPath);
When you have created an instance of the DirectoryInfo class, you can then use its
properties and methods to interact with the directory. The following list describes
Th Th
some iof
s d these properties and methods:
o
is
d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a ng
No rbo gs No rbo
• The unCreate sa
@
method t o Ma
enables you to create a new
u na directory s a @
sonto the file system. The
Ma
au p u p
tho rim rta tho rim rta
following izexample
r
ed
ave shows
r
Ba how to create the C:\fourthCoffee\tempData
r
r ize
d
a ve
r
Ba
rbo
directory.
co ab b os co ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
string directoryPath = "C:\\fourthCoffee\\tempData";
DirectoryInfo directory = new DirectoryInfo(directoryPath);
directory.Create();
Th Th
• Theis Delete
do
cu
is
method enables you to delete a directory
do
cu at a specific path. The
m me m me
art nt nt
art C:\fourthCoffee\tempData
following
a.b code
be example shows how to delete the
l a.b be
l
arb on arb on
No o gs No o gs
directory,
un
au and
s a@ all oitst
M contents. un
a
s a@ to
Ma
tho pri art uth pri rta
riz ma aB ori ma Ba
ed ve a rbo ze ve rbo
co rab dc rab
pie ss sa op ss sa
sa .c . i e sa . c .
om om
string directoryPath l l o = "C:\\fourthCoffee\\tempData"; l l o
we we
d! d!
bool recursivelyDeleteSubContent = true;
DirectoryInfo directory = new DirectoryInfo(directoryPath);
directory.Delete(recursivelyDeleteSubContent);
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d o
• The c cu
m Exists property enables you to determine
m if a directory exists on the file
um me
e art nt art nt
a.b b b
system.
N
eo
arbThe lfollowing
ng code example shows Nhowa.bto elo
arbdetermine
ng if the
ou os st ou os st
na a@ oM na a@ oM
C:\fourthCoffee\tempData
utho prim a rta directory exists. u tho p rim art
aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
string directoryPath d! = "C:\\fourthCoffee\\tempData"; d!
• The
Th FullName property enables you to get the
is
Th full path to the directory. The
is
do do
uc cu
following
ma m eexample
n
shows how to get the full path ma tomthe en tempData directory.
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
string rizdirectoryPath
ed
av
era B a rbo = riz
"C:\\fourthCoffee\\tempData";ed
av
era arb
co b s s c o b s os
pie s.c a . pie s.c a.
DirectoryInfoal directory s o m = new DirectoryInfo(directoryPath); s a o m
low llo
ed we
string fullPath = directory.FullName; ! d!
• The GetDirectories method enables you to get a list of all subdirectories within a
specific directory on the file system. In contrast to the static File.GetDirectories
Th Th
method,
is
d
this instance method returns an array isof type DirectoryInfo, which
d
oc oc
me u me u
enables
ma
r
you
nt to use each of the instance properties
ma
r
fornt each subdirectory. The
ta. be ta. be
arb b lo arb
ngexample shows how to get allN of the ng b lo
following
No
u ocode
sa st
o ou sub
os
a
directories
st
o
in the
na @ Ma na @ Ma
uth pri r uth pri rta
C:\fourthCoffee\tempData
oriz m av
ta B arb
directory. ori
ze
ma
ve Ba
ed era dc rab rbo
co b ss o sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
we we
d! d
string directoryPath = "C:\\fourthCoffee\\tempData";!
DirectoryInfo directory = new DirectoryInfo(directoryPath);
DirectoryInfo[] subDirectories = directory.GetDirectories();
his T T
• The GetFiles
do method enables you to get a listhisofdoall the files within a specific
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/62
10/25/2019 20483A - Programming in C# | Skillpipe
directory on the file system. In contrast to the static File.GetFiles method, this
instance method returns an array of type FileInfo, which enables you to use each
of the instance properties for each file. The following example shows how to get all
of the files in the C:\fourthCoffee\tempData directory.
string
Th
i
directoryPath = "C:\\fourthCoffee\\tempData";
Th
i
sd sd
cu o cu o
DirectoryInfo
m me directory = new DirectoryInfo(directoryPath);
m me
art nt art nt
a.b be a.b be
FileInfo[]
a l onsubFiles = directory.GetFiles(); a lon
No rbo gs No rbo gs
un sa t o u n s a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
Depending on whether s a o you require a simple one-line-of-codelloapproach to
m s a o m
llo
we we
d! d!
manipulate a directory, or something that offers slightly more flexibility, either the
static Directory or instance DirectoryInfo class should fulfill your requirements.
Manipulating
Th File and Directory Paths
Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
All files and all directories have a name, which when combined to point to a file in a
Th Th
is is
directory,
do constitute a path. Different file systems can
c
do have different conventions and
c
um um
ma en ma en
rules forta.bwhat bconstitutes
r t
elo a path. The .NET Framework r ta.
b
provides
tb
elo the Path class,
No a r bo n gs No a r bo ng
s
which uencapsulates
na sa
@ toa variety of file system utility ufunctions
Ma na sa thattoyou can use to parse
@ Ma
uth pri r ta u t ho pri rta
ori ma r ma
and construct ze validvfile
dc e rab names, B a rbo directory names, and paths ize dc within v e rab the BaWindows file
rbo
op ss sa op ss sa
ies . . i e . .
system. These functions all
c ocan
m be useful if your application needs s a to write
llo
com a file to a
ow we
ed d!
temporary location, extract ! an element from a file system path, or even generate a
random file name.
The following code shows how to create a new directory on the root of the C: drive.
Th Th
is i
Creating
do a Temporary
cu Directory the Hard Way s docu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/62
10/25/2019 20483A - Programming in C# | Skillpipe
However, with the above approach, you are making many assumptions, including
Th Th
is your application has the necessary privileges
whether is
do do to perform I/O at the root of the
c um c um
ma
C drive, .
e
rtaand nwhether
tb
e the C drive actually exists.marta. elo
en
tb
ba lon ng ba
No rbo gs No st rbo
un sa to un sa oM
au @ M au @
tho p rim a rta tho p rim art
r a B r a aB
A better way eisi z
d c to use
v era the astatic
rbo GetTempPath method provided
ized vera by the arb Path
os
class to
op bs sa co bs a.
ies s .co . p ies s .co
get the path to the current all muser’s Windows temporary directory. all m
ow ow
ed ed
! !
Th Th
is is
do d oc
cum um
ma e nt en ma
rta tb rt
.Additional
ba
be
lon Reading: For more informationa.babout
a
ethe
lon Path class, see the
No rbo gs No rbo gs
un PathsaClass @ topage at http://go.microsoft.com/fwlink/?LinkID=267805.
M un sa
@ to
Ma
au pri art a uth pri
tho m aB ori m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
sa om sa om
llo llo
we we
d! d!
Project/Solution.
15. In the code editor, click in the blank line below the comment, and then type the
following code:
Th if (!Directory.Exists(logDirectoryRoot)) Th
is is
do do
cuthrow new DirectoryNotFoundException(); cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz Ba
16. In the Task e d c Listrawindow,
v e
b
a rbo double-click the TODO: 02:d Get all ze
c
ve rablog file rbo paths. task.
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
17. In the code editor,edclick ! in the blank line below the comment,edand ! then type the
following code:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/62
10/25/2019 20483A - Programming in C# | Skillpipe
18. In the Task List window, double-click the TODO: 03: Check for existing
combined log file and delete if it already exists. task.
19. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
is is
do (File.Exists(combinedLogPath))
if d oc
cu um
ma me ma en
nt
rta File.Delete(combinedLogPath); rt tb
.ba belo a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
20. In the Task List p ies window, s .co double-click
. the TODO: 04: p
Writeies the .cheading
s a. to the
all m all om
ow ow
combined log file.edtask. !
ed
!
21. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
iFile.AppendAllLines(combinedLogPath,
sd is heading);
oc do
um cu
ma en ma me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth 05: Get@ Ma
22. In the tho Task priList window,
art double-click the TODO: pri the log
rta file name
riz m av aB ori m a Ba
ed era arb ze ve rbo
co file extension. os task. d co r ab
without the pie b s s.c a . pie s s.c sa
.
sa om sa om
llo llo
we we
d! d!
23. In the code editor, click in the blank line below the comment, and then type the
following code:
var logName =
Th Th
Path.GetFileNameWithoutExtension(logPath);
is is
do do
cum cu
ma e ma me
rta nt rt nt
.ba belo a .ba be
ng lon
No rbo s No rbo gs
u s a@ t oM un s a@ to
24. Innatheuth Task priList
ma
window,
art double-click the TODO: a uth Task 06:
pri
ma
Read
Ma
rta the contents of
ori aB ori Ba
ze v arb ze ve
the existing d c logerafile. b task. o dc rab rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
25. In the code editor,edclick ! in the blank line below the comment,edand ! then type the
following code:
26. In the Task List window, double-click the TODO: Task 07: Write the log file
contents to the combined log file. task.
27. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
is sd i
do
File.AppendAllLines(combinedLogPath, ologContent);
cu cu
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un sa to un to a@
au @ Ma au Ma
tho pri rta pri tho rta
28. On therizBuild m avmenu, Bclick Build Solution. riz m av Ba
ed era arb ed era rbo
co b s os co b s sa
pie s.c a. pie s.c .
sa om sa om
29. On the Debug menu, l l ow click Start Without Debugging. l l ow
ed ed
! !
30. In the Command Prompt window, when prompted to press any key to
continue, press Enter.
Lesson Objectives
After completing this lesson, you will be able to:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/62
10/25/2019 20483A - Programming in C# | Skillpipe
• Describe the purpose of serialization, and the formats that the .NET Framework
supports.
his T Th
• Serialize
do an object as XML. is
d oc
cu um
ma me ma en
rta nt rt tb
. be a.b elo
• Serialize
No
b arboan object
lon
gs as JSON. No arb
os
ng
st
un sa to un a oM
au @ M au @
tho pri art tho p rim art
riz ma aB riz av aB
• Create a custom ed
co
v eserializer
ra
arb by
os
implementing the IFormatter ed
co
interface.
era arb
os
pie bs a. pie bs a.
s.c s.c
sa om sa om
llo llo
we we
d! d!
What Is Serialization?
Applications typically process data. Data is read into memory, perhaps from a file or
web service call, processed, and then passed to another component in the system for
Th processing.
further Th
is is
d oc d oc
um um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
The components
do
c
of a system may run on the same domachine, but commonly
c
um um
m nrun e nt m e
components
art
a.b t b on different platforms, on different
el
art hardware,
a.b be
l
and even in different
arb on arb on
No o s g No o gs
geographical
un
au
s alocations.
@ t o M The format of the data also un needs
a
s a@to be to lightweight so that it
Ma
tho pri art uth pri rta
r ma aB ori ma
can be transported
i ze
dc
vover
e rab a avariety
rbo of protocols, such as zHTTP
e dc or
v e SOAP.
rab
Ba Serialization
rbo
op ss sa op ss sa
ies . . i e . .
is the process of converting all
c om the state of an object into a form sthat all can
combe persisted or
ow ow
ed ed
transported. ! !
Serializable Formats
The requirements of your system, and how you intend to transport the data, will
influence
Th
is the serialization format you choose. The
Th following table describes some of
is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/62
10/25/2019 20483A - Programming in C# | Skillpipe
Format Description
Binary Serializing data into the machine-readable binary format enables you to preserve the
fidelity and state of an object between different instances of your application. Binary
Th Th
serialization is also fast and lightweight, because the binary format does not require the
is is
do do
cum cu constructs. Binary serialization is
processing and storage of unnecessary formatting
ma e mm en
rta nt art t b between applications running
.ba bcommonly
elo used when persisting and transportinga.b objects elo
No rbo ng N arb ng
un s
sa on thetosame platform. Binary Example o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o
01000255255255255100000001220007273110105701051081018310111410597108
sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
10512210111444328610111411510511111061494648464846484432671171081161
17114101611101011171161149710844328011798108105997510112184111107101
11061110117108108510003873110105701051081018310111410597108105122101
11446831011141181059910167111110102105103117114971161051111103000106
Th Th
is is
71111101021051037897109101166897116979897115101721111151167897109101
do do
cu cu
ma m me
en 19651121121081059997116105111110689711697809711610411120006300020701
ma
rta t r nt
.ba b t a be
e11117114116104671111021021011019568101102971171081166400028100971169
.ba
lon lon
No rbo gs No rbo gs
un sa to un sa to
au @ 79897115101504857461021111171141161049911110210210110146991111096500
M a uth @ Ma
tho pri art pri rta
riz m a aB ori m a Ba
ve ze ve
ed 03267589210211111711411610499111102102101101929711211210810599971161
arb rbo
co rab os d co r ab
pie s s.c a pie s s.c sa
0511111010097116979211
sa . sa .
om om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/62
10/25/2019 20483A - Programming in C# | Skillpipe
Format Description
XML Serializing data into the XML format enables you to utilize an open standard that can be
processed by any application, regardless of platform. In contrast to binary, XML does not
preserve type fidelity; it only lets you serialize public members that your type exposes.
The XML format is more verbose than binary, as the serialized data is formatted with
XML constructs. This makes the XML format less efficient and more processor intensive
Th his T
is during the serializing, deserializing, and transporting processes. XML serialization is
do do
cum cu
ma e commonly used to serialize data that can be
matransported me via the SOAP protocol to and
rta n tb r nt
.ba elo t a.b be
lon
No rbo from ng web services. XML Example
st No arb
os gs
un sa o u n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed <SOAP-ENV:Envelope
era rbo ed era rbo
co b s s a. c o b s sa
pie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
s.c pie s.c .
sa om sa om
l l ow
xmlns:xsd="http://www.w3.org/2001/XMLSchema" l l ow
ed ed
! !
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP- ENV=http://schemas.xmlsoap.org/soap/envelope/
xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:ServiceConfiguration id="ref-1"
Th Th
is is
xmlns:a1="http://schemas.microsoft.com/clr/nsassem/
do do
cu cu
ma m en ma me
FourthCoffeeSerializer/%2C%20Version%3D1.0.0.0%2C%20
rta t r nt
.ba belo t a .ba be
n Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"> lon
No rbo gs No rbo gs
un sa to un sa to
au @ M <ConfigName id="ref-3"> a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arFourthCoffee_Default ze ve rbo
co b b os d co r ab
pie s a
s.</ConfigName> p s s sa
sa co . i es . co .
llo m a llo m
we <DatabaseHostName id="ref-4"> we
d! d!
database209.fourthcoffee.com
</DatabaseHostName>
<ApplicationDataPath id="ref-5">
C:\fourthcoffee\applicationdata\
</ApplicationDataPath>
Th </a1:ServiceConfiguration> T
is his
do </SOAP-ENV:Body> do
cu cu
ma m en </SOAP-ENV:Envelope> ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/62
10/25/2019 20483A - Programming in C# | Skillpipe
Format Description
JSON Serializing data into the JSON format enables you to utilize a lightweight, data-
interchange format that is based on a subset of the JavaScript programming language.
JSON is a simple text format that is human readable and also easy to parse by machine,
irrespective of platform. JSON is commonly used to transport data between
Asynchronous JavaScript and XML (AJAX) calls because unlike XML, you are not limited
Th his T
is to just communicating within the same domain.
do d JSON Example oc
cum um
ma ent en ma
rta b a tb rt
.ba e{
lon . ba elo
No rbo gs No rbo ng
un sa to un sa st
@ "ConfigName":"FourthCoffee_Default",
M @ oM
au p a au p art
tho rim rta tho rim aB
riz v arb r
a"DatabaseHostName":"database209.fourthcoffee.com",
B iz a v arb
ed era ed era
co bs o sa co bs os
pie "ApplicationDataPath":"C:\\fourthcoffee\\applicationdata\\"
s.c . pie s.c a.
sa om sa om
} l l ow l l ow
ed ed
! !
Alternatively, if you want to serialize your data to a format that the .NET Framework
does not natively support, you can implement your own custom serializer class.
Th Th
is is
do d oc
cum um
Creating
rta
ma
.b
na
t b Serializable Type
el
e ma
rt a.b
en
tb
elo
arb on arb ng
No o g st No os st
un sa oM un a oM
au @ au @
tho pri art tho p rim art
riz m av aB riz av aB
ed era arb ed era arb
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do do
um c cu
The .NET
ma Framework
en
tb
provides many classes that
ma aremserializable.
en
tb
If you want to
rta elo rta elo
.ba .ba
create
No your rboown types
sa
ng
st that are serializable, youNoneed rto bo ensure
sa
ng
s t that the type
un @ o M u n @ oM
au pri art a uth pri a
definition thincudes
ori
ze
mathe necessary
ve
aB configuration and functionality
ori
z
ma forrtthe
v
a B serilalizer to
dc rab a rbo e dc e rab arb
sa provides the System and op os
consume. The .NET op
ies Framework
s s .co . ies s s.co a.
all m all m
ow ow
System.Runtime.Serialization ed
!
namespaces, which provide classes ed to enable
!
serialization support.
Th Th
1. Define
is
do a default constructor. is
d
cu oc
m um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/62
10/25/2019 20483A - Programming in C# | Skillpipe
[Serializable]
public class ServiceConfiguration
{
Th Th
is is
do ... do
cu cu
ma m en ma me
t nt
}rta.b be
lon
rta
.ba be
lon
No arbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
p s s a p s s sa
3. Implement the i es ISerializable
all
.co
m
. interface provided in the es a i . co
m
.
ow llo
ed we
System.Runtime.Serialization ! namespace. The GetObjectData d! method
enables you to extract the data from your object during the serialization
process.
Th [Serializable] Th
is is
do do
publiccu
m class ServiceConfiguration : ISerializable
cu
me
ma en ma nt
rta tb r t a be
{ .ba elo .ba lon
No rbo ng No rbo gs
un s s t un s to
oM
au ...a@p art a uth
a@
pri Ma
tho rim aB ori ma rta
riz av a z v Ba
public e dc e
void rbo
rab GetObjectData(SerializationInfo e dc e rainfo, rbo
op ss sa op b ss sa
ies .co . ies .co .
StreamingContext a llo m context) a llo m
we we
d! d!
{
...
}
}
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/62
10/25/2019 20483A - Programming in C# | Skillpipe
[Serializable]
Th public class ServiceConfiguration T:
is his ISerializable
do do
cu cu
ma{ me
n m a
me
nt
rta tb r t a.b be
.ba... elo a lon
No rbo ng N r b gs
un sa st ou os to
@ o M n a @ Ma
au public pri ServiceConfiguration(SerializationInfo
art au pri
tho m a t h o m rtinfo,
aB
riz av Ba riz av arb
ed era rbo ed era
StreamingContext co bs co bs os
pie s.c ctxt) sa
. pie s.c a.
sa om sa om
{ l l ow l l ow
ed ed
! !
...
}
}
Th Th
is is
5. do
Define do
cu the public members that you want to serialize.
cu You can instruct the
ma me ma me
r nt rt nt
serializer
t a.ba beto ignore private
lon fields by decorating.bthem
a
a
bwith
elo the NonSerialized
No rbo gs No rbo ng
sa to sa s to
attribute.
un
au @
pri Ma un
au @
pri Ma
tho m rta tho m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
... we we
d! d!
[NonSerialized]
private Guid _internalId;
public string ConfigName { get; set; }
public string DatabaseHostName { get; set; }
Th public string ApplicationDataPath T{ his get; set; }
is
do do
cu cu
ma ... m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
The following e dc
op
code
rab example rbo
sa
shows the complete ServiceConfiguration
e dc
op
e rab rbo
sa
class,
ies ss . ies ss .
.co .co
which is serializable all
ow by
m any of the .NET Framework IFormatter
all
ow
m
ed ed
! !
implementations.
Serializable Type
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/62
10/25/2019 20483A - Programming in C# | Skillpipe
[Serializable]
public class ServiceConfiguration : ISerializable
{
[NonSerialized]
private Guid _internalId;
Thpublic string ConfigName { get; set; Th }
is is
do do
c um cset;
um
mpublic
art e nt
string DatabaseHostName { get; m a en }
a.b b r t a.b t b
elo elo
No public arb
o
string
ng
s
ApplicationDataPath N{ get;
o
arb set;
o
ng }
st
un sa to un sa oM
au @ M a u @
public tho p a
ServiceConfiguration()
rim rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
{ co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
} l l ow l l ow
ed ed
! !
public ServiceConfiguration(SerializationInfo info,
StreamingContext ctxt)
{
this.ConfigName
Th = info.GetValue("ConfigName",
Th typeof(string)).ToString();
is is
do do
um c
this.DatabaseHostName cu
ma en ma me
rta t r nt
.ba belo t a .ba be
= n info.GetValue("DatabaseHostName", lon
No rbo gs No rbo gs
un sa to un sa to
a uth @ M a uth @ Ma
pri
typeof(string)).ToString(); art pri rta
ori m a aB ori m a Ba
ze ve arb ze ve rbo
dc rab os d co r ab
this.ApplicationDataPath
op s s.c a pie s s.c sa
ies . sa .
all om om
o
= info.GetValue("ApplicationDataPath", l l o
we we
d! d!
typeof(string)).ToString();
}
public void GetObjectData(SerializationInfo info,
StreamingContext context)
Th{ Th
is is
do do
um c
info.AddValue("ConfigName", cu
this.ConfigName);
ma en ma me
rta tb r nt
elo
.ba info.AddValue("DatabaseHostName", t a be
.bathis.DatabaseHostName);
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au info.AddValue("ApplicationDataPath",
pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
this.ApplicationDataPath);
co
pie ss sa op ss sa
sa .c . i e sa . c .
om om
} llo llo
we we
d! d!
}
Serializing
Th
is
Objects as Binary Th
is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
The .NET au Framework
tho prim
M provides
a rta the BinaryFormatter au classp in the
tho rim art
riz av B r a aB
ed era arb ized vera arb
System.Runtime.Serialization.Formatters.Binar
co
pie bs o sa y namespace,co
pie bs which os you
a.
can use
s.c . s.c
sa om sa om
to serialize and deserialize l l ow objects as binary. l l ow
ed ed
! !
This example, serializes the ServiceConfiguration object, and writes the serialized
data to a file. It is important to note that serialization doesn’t just imply writing data to
a file. Serialization is the process of transforming a type into another format, which
you can then write to a file or database, or send over HTTP to a web service.
Th Th
is is
do d oc
cum um
ma ma
Deserialize
rta
.
nt an Object by Using the BinaryFormatter
be
e
a.
en
tb
e
Class rt
ba lon ba lon
No rbo gs No rbo
gs
un sa to un sa to
@ M @ Maback into
Deserializing
auth
ori
is pthe
r i m
processart
aB
of transforming your serialized
a uth
ori
probject
im rta a format
ze ave arb ze a ve Ba
d r d r rbo
that your application co
pie
acan
b s s.c
process.
os
a To deserialize an object coby using
pie
ab the
s s.c sa
sa . sa .
om om
BinaryFormatter class, l l o we perform the following steps:
l l o we
d! d!
The following code example shows how to use the BinaryFormatter class to
deserialize binary data to an object.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/62
10/25/2019 20483A - Programming in C# | Skillpipe
The above example reads the serialized binary data from a file, and then deserializes
the binary into a ServiceConfiguration object. The process is the same for
Th
serializing Th formatters that implement the
and deserializing objects by using any
is is
do do
um c um c
IFormatter
ma einterface.
nt This includes the SoapFormatter
ma enclass, and any custom
t
rta be rta be
.ba lon .ba lon
formatters
No rthat
bo
sa
you gs may implement.
to
No rbo
sa
gs
to
un @ Ma un @ Ma
au pri au pri
tho m rta tho m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b sa co b sa
Serializing Objects as XML pie
sa
llo
s s.c
om
. pie
sa
llo
s s.c
om
.
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
The .NET Framework co bprovides
ss sa the SoapFormatter class cin o the s os
pie .co . p ies s.co a.
sa m a m
llo
System.Runtime.Serialization.Formatters.Soap
we
d! namespace,llowhich we
d! you can use to
serialize and deserialize objects as XML.
The following code example shows how to use the SoapFormatter class to serialize
an object as XML.
Th Th
sd i sd i
// Create
oc
u
the object you want to serialize.
oc
u
m me m me
art nt art nt
ServiceConfiguration
a.b be
l
config = ServiceConfiguration.Default;
a.b be
l
arb on arb on
No os gs No os gs
u
// Create athe t o
formatter u
you want to use nto a
serialize to
na
uth @
pri M art au @
pri Ma the object.
ori ma aB t h ori ma rta
IFormatter ze formatter ve a = new SoapFormatter(); ze ve Ba
dc rab rbo dc rab rbo
op s s s a o p s s sa
i .co . ies .co .
// Create the esstream all
ow
mthat the serialized data will all be buffered
ow
m too.
ed ed
FileStream buffer =! File.Create("C:\\fourthcoffee\\config.xml"); !
The following code example shows how to use the SoapFormatter class to
deserialize XML data to an object.
Th Th
is is
SoapFormatter
doc
um
Deserialize Example do
cu
ma en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
// Createzethe r i ve
formatter you want to use to z
serialize v Ba object.
dc rab a rbo e dc e rab the rbo
op ss sa op ss sa
ies .co . ies .co .
IFormatter formatter all m= new SoapFormatter(); all m
ow ow
ed e
// Create the stream ! that the serialized data will bed!buffered too.
The .NET Framework also supports serializing objects as JSON by using the
DataContractJsonSerializer
T class in the System.Runtime.Serialization.Json
T
his his
do do
namespace.
cu The JSON serialization steps are different
m
cu because the
m
ma en ma en
rta be t rta be t
DataContractJsonSerializer
.ba
r
lon class is derived from .the
ba abstract
r
lon XmlObjectSerializer
No bo gs No bo gs
un sa to un sa to
class, andauth it is not
@
pri anMimplementation
art of the IFormatter
a uth interface.
@
pri Ma
rta
ori m av aB ori m a Ba
ze era arb ze ve rbo
dc b os dc rab
op s s.c a. op s s.c sa
ies ies .
all o m all om
Serialize an Object by Using the DataContractJsonSerializer Class
ow
ed
ow
ed
! !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
sd i sd i
// Create
oc
u
the object you want to serialize.
oc
u
m me m me
art nt art nt
ServiceConfiguration
a.b be
l
config = ServiceConfiguration.Default;
a.b be
l
arb on arb on
No os gs No os gs
u
// Create
na a t o
a@ DataContractJsonSerializer u
object
na a thatto you
@ will use to
uth pri M art uth pri Ma
ori ma aB ori ma rta
serializezethe ve arb ze ve Ba
dc rab os dc rab rbo
op s s a o p s s sa
ies .co . ies .co .
// object to JSON. all m all m
ow ow
ed ed
DataContractJsonSerializer ! jsonSerializer !
= new DataContractJsonSerializer(config.GetType());
// Create the stream that the serialized data will be buffered too.
FileStream buffer = File.Create("C:\\fourthcoffee\\config.txt");
// Invoke the WriteObject method.
Th Th
is is
do
jsonSerializer.WriteObject(buffer, do
config);
c um c um
ma nte ma en
rta
// Close rt tb
.ba the be stream.
lon a.b
arb
elo
No rbo gs No ng
un sa to un os st
buffer.Close();
au @ Ma au a @ oM
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Deserialize an Object by using the DataContractJsonSerializer
Class
To deserialize JSON to an object by using the DataContractJsonSerializer class,
perform the following steps:
Th Th
is is
do oc d
cum um
ma e
n ma en
1. Create
rta
.ba
ant b instance of the DataContractJsonSerializer
elo r ta.
b
tb
elo class that you want to
No r b n gs No a r bo ng
un to oserialize st
use au
sa
@ t o your
M type. The constructor also
u n a
requiressa
@ you
o M to pass in a Type
tho pri art uth pri art
m a o m aB
object,rizrepresenting
ed
av
era Bthe
arb type of object you want to riz deserialize.
ed
av
era arb
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
2. Create a stream wthat
ed
!
will read the serialized JSON into memory. we
d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
You may want to serialize d! data into a format other than binary, XML, d! or JSON. The
.NET Framework provides the IFormatter interface in the
System.Runtime.Serialization namespace, so you can create your own formatter.
Your custom formatter will then follow the same pattern as the BinaryFormatter and
SoapFormatter classes.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/62
10/25/2019 20483A - Programming in C# | Skillpipe
Custom IniFormatter
using
Th System; Th
is is
do d oc
um c
using System.Collections.Generic; um
ma en ma en
rta tb rt a.b tb
using .ba
System.IO; elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
using aSystem.Reflection;
uth pri
m
art au
tho p rim art
ori av aB riz av aB
ze era arb ed era arb
dc
using System.Runtime.Serialization; b os co b os
op s s.c a. pie s s.c a.
ies o sa om
a llo m llo
namespace FourthCoffee.Serializer we we
d! d!
{
class IniFormatter : IFormatter
Th
{ Th
is is
do d oc
c um StreamReader buffer um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 35/62
10/25/2019 20483A - Programming in C# | Skillpipe
= new StreamReader(serializationStream);
// Get the type from the serialized data.
Type typeToDeserialize = this.GetType(buffer);
// Create default instance of object using type name.
Object obj
=
Th Th
is
FormatterServices.GetUninitializedObject(typeToDeserialize); is
do do
cu cu
ma me m me
rta n
// t b Get all the members for the rttype. a nt
.ba elo a.b be
ng a lon
No rbo st N ou r b os gs
un sa
MemberInfo[] o members n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m a a Ba o riz m av Ba
ed = vera rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
FormatterServices.GetSerializableMembers(obj.GetType(),
sa om sa om
llo llo
we we
this.Context); d! d!
Th sarr[1].Trim()); // Variable
T value.
is his
do do
um }
c cu
me
ma en ma nt
rta tb r t a be
.ba // elClose o the underlying stream. .ba lon
No rbo ng No rbo gs
un s s t un s to
a@ oM a@ Ma
au
tho
buffer.Close();
pri art a uth pri rta
riz ma aB ori ma Ba
e ve a ze ve
//d coCreate rab a rlist bo to store member values dc as rabtheir rbo correct
pie ss sa op ss sa
sa .c . i e sa . c .
om om
type. llo
we
llo
we
d! d!
List<object> dataAsCorrectTypes = new List<object>();
// For each of the members, get the serialized values as
their correct type.
for (int i = 0; i < members.Length; i++)
Th
{ Th
is is
do
cum FieldInfo field = members[i] doas
cu FieldInfo;
m
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/62
10/25/2019 20483A - Programming in C# | Skillpipe
if(!serializedMemberData.ContainsKey(field.Name))
throw new SerializationException(field.Name);
// Change the type of the value to the correct type
// of the member.
object valueAsCorrectType = Convert.ChangeType(
serializedMemberData[field.Name],
Th Th
is field.FieldType); is
do oc d
cum um
ma ent m art en
rta
.ba belo dataAsCorrectTypes.Add(valueAsCorrectType); a.b tb
elo
No rbo ng N arb ng
un sa
} s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz// Populateav B the
arb object with the r i
deserialized
z a v values.
arb
ed era ed era
co b s o s c o b s os
pie s.c a. pie s.c a.
return s a FormatterServices.PopulateObjectMembers(
om sa om
llo llo
we we
obj, d! d!
members,
dataAsCorrectTypes.ToArray());
}
public void Serialize(Stream serializationStream, object graph)
Th Th
is { is
do do
cu cu
ma m en ma me
rta // t Get all the fields that you want
r nt serialize.
to
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un MemberInfo[]
sa
@ to
M
allMembers un sa
@ to
Ma
au pri art a uth pri
tho m aB ori m rta
riz = av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
FormatterServices.GetSerializableMembers(graph.GetType(),
sa om sa om
llo llo
we we
this.Context); d! d!
allMembers);
Th
} Th
is is
do d oc
c sw.Close();
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/62
10/25/2019 20483A - Programming in C# | Skillpipe
}
private Type GetType(StreamReader buffer)
{
string firstLine = buffer.ReadLine();
string[] sarr = firstLine.Split(_delim);
string nameOfClass = sarr[1];
Th Th
is is
return Type.GetType(nameOfClass);
do do
umc c um
ma en ma en
rta} tb
elo rt a.b tb
elo
.ba arb
No rbo ng No ng
} una sa st un os st
@ oM a @ oM
uth pri art au p art
ori ma aB tho rim aB
} ze ve arb riz av arb
dc rab ed era
op s os co bs os
ies s .co a. pie s.c a.
all m sa om
ow llo
ed we
! d!
3. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.
7. Double-click the TODO: 01: Decorate the type with the Serializable attribute.
task.
8. In the code editor, click in the blank line below the comment, and then type the
Th Th
following
is
do code: is
d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/62
10/25/2019 20483A - Programming in C# | Skillpipe
[Serializable]
9. In the Task List window, double-click the TODO: 02: Implement the ISerializable
interface. task.
Th Th
is is
do d o
10. mIn the c cu comment, and then type the
umcode editor, click in the blank line below the
e m me
art nt art nt
a.b elo b a.b be
N following code:
arb ng arb lon
ou os st No os gs
na a@ oM un a@ to
uth pri art au pri Ma
ori ma aB tho m rta
ze ve arb riz av Ba
dc rab ed era rbo
op s os co b s sa
ies s .co a. pie s.c .
: ISerializable all m sa om
ow llo
ed we
! d!
11. Right-click the text ISerializable, point to Implement Interface, and then click
Implement Interface.
12. TIn the GetObjectData method, replace theT existing code to throw a new
his his
do
NotImplementedException do
object with the following code:
cu cu
ma m en m ma en
rta tb rta tb
.ba elo .ba elo
No rbo n gs No rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim
info.AddValue("Title", rta this.Title); tho rim aB
riz av B a riz av arb
ed era rbo ed era
c o b s s c o b s os
info.AddValue("Details",
pie s.c a . this.Details); pie s.c a.
sa om sa om
llo llo
we we
d! d!
13. In the Task List window, double-click the TODO: 03: Add a deserialization
constructor. task.
14. In the code editor, click in the blank line below the comment, and then type the
Th Th
is
following code: is
do d oc
cu um
ma m en ma en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
un s st un os st
a @ oM a @ oM
a
public
uth ExceptionEntry(
pri art au pri art
ori ma aB tho m aB
ze ve arb riz av arb
d rab ed era
SerializationInfo
co
pie ss os
a. info, co
pie bs os
a.
.co s.c
sa m sa om
StreamingContext llo context) llo
we we
d! d!
{
this.Title = info.GetString("Title");
this.Details = info.GetString("Details");
}
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/62
10/25/2019 20483A - Programming in C# | Skillpipe
15. In the Task List window, double-click the TODO: 04: Create a SoapFormatter
object and serialize the entry object. task.
16. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
is sd i
var do formatter = new SoapFormatter(); oc
cu um
ma m en ma en
rta tb
formatter.Serialize(stream, entry); r t a.b tb
.b el on el on
No arb gs No arb gs
un os t o u os to
au a @ M n au a @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
co b s s a c o b s sa
17. In the Task List p ies window, s .co double-click the TODO: 05: Create
. p ies a .SoapFormatter
s co .
all m all m
ow ow
object and deserialize ed
! the stream to the entry object. task. ed!
18. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
ivar
sd formatter = new SoapFormatter(); is
oc do
um cu
maentryen = formatter.Deserialize(stream) ma m
rta t b r t
asentExceptionEntry;
be
.ba elo a .ba lon
No rbo ng N r b gs
un sa s to o un o sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co os Build Solution. d co r ab
19. On the Build pie menu, b s s.c click a . pie s s.c sa
.
sa om sa om
llo llo
we we
d! d!
20. On the Debug menu, click Start Without Debugging.
21. In the Exception Logger window, create a new exception entry by using the
following information, and then click Save:
27. Switch to Visual Studio, and on the Debug menu, click Start Without
Debugging.
When you work with data, whether the data is stored in a file on the file system or on
a web server accessible over HTTP, the data sometimes becomes too large to load
into memory
Th
is and transmit in a single atomic operation.
Th
is For example, imagine trying to
do do
cu cu
load maa200-gigabyte
me
n
video file from the file system
ma intomememory
n
in a single operation.
rta tb rta tb
.ba elo .ba elo
Not Nonly
ou
would
rbo thegs operation take a long time, but
n No it would rbo also
ng consume a large
st
na s a t o u na s a oM
u @ Ma u @
amount ofthomemory.
riz
prim
av
rta
B
tho
riz
p rim
av
art
aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
In this lesson, you will welearn how to use streams to read from and
d!
wewrite to files without
d!
having to cache the entire file in memory.
Lesson Objectives
AfterT completing this lesson, you will be able to:T
his his
do do
c um cu
ma e ma me
rta nt rt nt
be a.b be
• Describe
No
.ba the
rbo
lopurpose
ng of a stream. No arb lon
gs
un s st un os to
a @ o Ma a@ Ma
au pri au pri
tho ma rta tho ma rta
• Describe zthe r rthe
i ed different ve
rab types
Ba
rbo of streams provided in ize .NET
dc
ve Framework.
rab
Ba
rbo
co ss sa op ss sa
pie .co . ies .co .
sa m all m
llo ow
• Describe how to use we a stream.
d! ed
!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
The .NET au Framework
tho prim
M enables
a rta you to use streams. aA
u stream
tho p rim a sequence
is art of bytes,
riz av B r a aB
ed era arb ized vera arb
which could come co from
pie bs a file oson the file system, a network
a. coconnection,
pie bs or
os memory.
a.
s.c s.c
sa om sa om
Streams enable you oto l l we read from or write to a data source in small,
l l ow manageable data
d! ed
!
packets. Typically, streams provide the following operations:
The .NET Framework provides several stream classes that enable you to work with a
variety of data and data sources. When choosing which stream classes to use, you
need to consider the following:
Th Th
is is
• d
What otype of data you are reading or writing, for doexample, binary or alphanumeric.
cu cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
• N
Where r
theos data is stored, for example, on N
the local r file system, to in memory, or on a
ou b s o b o gs
na a@ t oM un s a@
uth pri art a uth pri Ma
rta
web server ori
ze over ma a network.
ve
aB
a
ori
ze
ma
ve Ba
dc rab rbo dc rab rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
The .NET Framework class library provides several classes in the System.IO
namespace that you can use to read and write files by using streams. At the highest
level of abstraction, the Stream class defines the common functionality that all
streams provide. The class provides a generic view of a sequence of bytes, together
with Tthe d
Th
his operations and properties that all streams is provide. Internally, a Stream
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/62
10/25/2019 20483A - Programming in C# | Skillpipe
object maintains a pointer that refers to the current location in the data source. When
you first construct a Stream object over a data source, this pointer is positioned
immediately before the first byte. As you read and write data, the Stream class
advances this pointer to the end of the data that is read or written.
You cannot use the Stream class directly. Instead, you instantiate specializations of
Th Th
sdi sd i
this class
oc that are optimized to perform stream-based
u
oc I/O for specific types of data
u
ma me ma me
nt nt
sources.a.bFor example,
r t belo the FileStream class implements r t a.b bae stream that uses a disk
lon
No arbo ng N a r b gs
s st ou os to
file as the
una data
uth
a @ source,
pri
o M and
art
the MemoryStream class
na
uth
implements
a @
pri Ma a stream that uses
ori ma aB ori ma rta
Ba
a block of memory ze
dc
vas
e rabthe data
a rbo source. ze
dc
ve
rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
Types of Streams in the .NET Framework
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d!
The .NET Framework provides many stream classes that you can duse ! to read and
write different types of data from different types of data sources. The following table
describes some of these stream classes, and when you might want to use them.
Stream
Th
is
class Description
Th
is
do do
cum cu
ma e ma me
FileStream nt Enables you rto nt
rta
. be ta. establish be a stream to a file on the file
ba lon ba lon
No rbo gs system. TheN r
o uFileStreamb gs handles operations such
a@ class
un s to os to
au a@ Ma na Ma
tho pri rta u t
as opening and closing ho p r
the imfile, and rta provides access to
riz ma Ba riz av Ba
ed ve rbo ed era rbo
co rab the file through a raw sequence co ofs bytes.
b
pie ss sa pie s.c sa
sa .c . sa .
om om
llo llo
MemoryStream we Enables you to establish a stream we to a location in
d! d!
memory. The MemoryStream class handles operations
such as acquiring the in-memory storage, and provides
access to the memory location through a raw sequence
of bytes.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do do
Stream c
class
u Description cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
StreamReader
un sa
@ toEnables you to read textual data fromuan na underlying sa
@ datato source stream, such as a
au pri M art uth pri Ma
tho m aB m rta
riz av FileStream, arb
MemoryStream, or NetworkStream ori
ze
object.
a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
StreamWriter s aEnables omyou to write textual data to an underlying data s asourceostream,m such as a
llo llo
we we
d!
FileStream, MemoryStream, or NetworkStream object. d!
BinaryReader Enables you to read binary data from an underlying data source stream, such as a
FileStream, MemoryStream, or NetworkStream object.
BinaryWriter Enables you to write binary data to an underlying data source stream, such as a
FileStream, MemoryStream, or NetworkStream object.
Th Th
is is
do d oc
cum um
ma e en ma
Reading and Writing Binary Data bya.bUsing
rta
.ba
nt
be
lon a
tb
elo Streams rt
No rbo gs No rbo ng
un s to un sa st
a@ Ma @ oM
au p au
pri of reasons,
art
Many applications
t ho
riz
r im store
av
rtadata in
Ba
raw binary form for athnumber
or ma aB such as the
ed era ize ve arb
rbo d ra os
following: c op b ss sa co bs a.
ies .co . pie s.c
all m sa o m
ow llo
ed we
! d !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 44/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho tho rim
• Writing binaryriz
ed
data
m av isrtafast.
Ba riz
ed
av aB
arb
era rbo era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
• Binary data takes oup l l we less space on disk. llo
we
d! d!
You can read and write data in a binary format in your .NET Framework applications
hisT his T
by using dothe BinaryReader and BinaryWriter classes.
do
cu cu
ma me mema
rta nt nt
rt
.ba belo a .ba be
n lon
No rbo gs No rbo g
To readun or write
au
sa binary
@ to data, you construct a BinaryReader
M un
a
sa
@ ors tBinaryWriter
oM object
tho pri art uth pri art
m aB ori m aB
by providingrizead stream av
era that ais
rbo connected to the source ofzethe dc
data
av
era that ayou
rbo want to
co b s s a o b s sa
pie sc . pie s.c .
read or write, such s aas a .FileStream
om or MemoryStream object. sa om
llo llo
we we
d! d!
The following code example shows how to initialize the BinaryReader and
BinaryWriter classes, passing a FileStream object.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 45/62
10/25/2019 20483A - Programming in C# | Skillpipe
After you have created a BinaryReader object, you can use its members to read the
binary data. The following list describes some of the key members:
• The BaseStream property enables you to access the underlying stream that the
BinaryReader object uses.
Th Th
• Theis Close method enables you to close the BinaryReader
d
is
d object and the
oc oc
um um
underlying
m art e nt stream.
b
m art en
tb
a.b elo a.b elo
No arb ng N arb ng
un o sa s to o un o sa st
@ @ oM
• The Readau
tho method
prim
Menables
a rta you to read the number au of remaining
tho p rim art bytes in the
aB
riz av B arb r iz a v arb
ed era ed era
stream from a
co specific
pie bs
s.c
index.
o sa co
pie bs
s.c
os
a.
sa . sa
om om
llo llo
we w
• The ReadByte method d! enables you to read the next byte from ethe d! stream, and
• The ReadBytes method enables you to read a specified number of bytes into a
byte array.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt
a.b tb
.ba l o elo
Similarly,
No the
rbo BinaryWriter
n gs object exposes various No members
a rbo ng to enable you to write
st
un sa t o u na s a oM
au @ Ma u @
data to anthounderlying
riz
p rim
av
stream.
rta
B
The following list describestho
riz
some
p rim
av
ofarthe
ta
Ba
key members.
ed era a rbo ed era rbo
co bs sa co bs sa
pie s.c . pie s.c .
sa om sa om
llo llo
• The BaseStream property we
d! enables you to access the underlying we stream that the
d!
BinaryWiter object uses.
• The Close method enables you to close the BinaryWiter object and the
underlying stream.
T
his Flush method enables you to explicitly flush T
his any data in the current buffer to
• The do do
cu cu
m me m me
theaunderlying
rta n tb stream. art
a
nt
be
.ba elo .ba lon
No rbo ng No rbo gs
un s s t un s to
a@ oM a@ Ma
• a
The Seek method enables you to set your positiona uth in the pri current
uth
ori
pri
ma
art
aB ori ma rta stream, thus
ze ve a ze ve Ba
writing to adspecific co rab byte.rbo dc rab rbo
pie ss sa op ss sa
sa .c . i e sa . c .
om om
llo llo
we we
d!
• The Write method enables you to write your data to the stream,d!and advance the
stream. The Write method provides several overloads that enable you to write all
primitive data types to a stream.
Th Th
is is
Readingdo Binary Data
cu
d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 46/62
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to use the BinaryReader and FileStream
classes to read a file that contains a collection of bytes. This example uses the Read
method to advance through the stream of bytes in the file.
BinaryReader Example
Th Th
is is
do d oc
cum um
ma nt e ma en
rta
// Source file
be path. rt a.b tb
.b l on elo
No arb g ng
No arb
sa o
un sourceFilePath st un st os
string @ oM = a @ oM
au p a au p art
tho rim rta tho rim a
riz av B r a
ed era arb
"C:\\fourthcoffee\\applicationdata\\settings.txt ized vera ";Barb
co bs o sa co bs os
pie s.c . pie s.c a.
// Create a FileStream sa om object so that you can interact sa owith
m the file
llo llo
we we
d! d!
// system.
FileStream sourceFile = new FileStream(
sourceFilePath, // Pass in the source file path.
FileMode.Open, // Open an existing file.
FileAccess.Read);// Read an existing file.
Th Th
is i
do
// Create
c a BinaryWriter object passing s in
do the FileStream object.
c
um um
ma e nt ma en
rta
BinaryReader be reader = new BinaryReader(sourceFile); rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa t u s st
// Storeau the @ currento Ma position of the stream.
na a @ oM
tho prim rta u tho p rim art
riz av0; B riz av aB
int position ed = era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
// Store the length s all oof
m the stream. s all o m
ow ow
ed ed
!
int length = (int)reader.BaseStream.Length; !
hisT Th
BinaryWriter
do Example is
d oc
cu um
ma me en ma
rta nt tb rt
.ba belo a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
string destinationFilePath
riz
ed
av
era B arb = r ized
a vera arb
co bs o sa co bs os
p ies s .co . p ies s .co a.
"C:\\fourthcoffee\\applicationdata\\settings.txt";
all m all m
ow ow
// Collection of bytes. ed ed
! !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 48/62
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
o
In addition
au to storing
tho
@
prim data
M a rta
as raw binary data, you can
au alsop storeMdata
tho
@
rim art as plain text.
riz av B r a aB
ed to doerthis ab ized dataeraneedsv arb
You may want co ab in ryour
ss os
a
application if the persisted co bs to
os be human
a.
pie .c . p i e s . c
sa om sa om
readable. llo
we
llo
we
d! d!
The process for reading from and writing plain text to a file is very similar to reading
and writing binary data, except that you use the StreamReader and StreamWriter
classes.
Th Th
is is
do do
When ma
you uminitialize
c
en
the StreamReader or StreamWriter
ma
cu
me classes, you must provide a
rta t r nt
belohandle the interaction with the data.bsource. t a be
stream
No object
.ba
rbo to n gs No a rbo
lon
gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
d r ab
The following code co
pie exampleb s s.c
oshows
s a .
how to initialize the StreamReader
co
pie s s.c and
sa
.
sa om sa om
StreamWriter classes, l l
l o we passing a FileStream object. l o we
d! d!
string
Th
i
destinationFilePath = is
Th
sd do
oc cu
u
"C:\\fourthcoffee\\applicationdata\\settings.txt";
m me
ma en ma nt
rta tb r t a be
. b elo . b lon
FileStream
No arb fileng = new FileStream(destinationFilePath); N arb gs
un o s s t o un o s to
a@ oM a@ Ma
... a uth pri art a uth pri
ori ma aB ori ma rta
ze ve a ze ve Ba
dc rab rbo dc rab rbo
StreamReader op reader ss = new
sa
.
StreamReader(file); op ss sa
.
ies .co ies .co
all m all m
... o we o we
d! d!
StreamWriter writer = new StreamWriter(file);
After you have created a StreamReader object, you can use its members to read the
plain text. The following list describes some of the key members:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 49/62
10/25/2019 20483A - Programming in C# | Skillpipe
• The Close method enables you to close the StreamReader object and the
underlying stream.
• The EndOfStream property enables you to determine whether you have reached
the end of the stream.
• The
T Peek method enables you to get the next
T available character in the stream,
his his
do do
but doescu not consume it.
m
cu
me
ma en ma nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r b gs available character
• TheunReadsamethod @
s t enables you to get and consume
o ou
n
othe
s a @
next to in
au pri M art au pri Ma
tho m a t h o m rta
the stream. riz This
ed
avmethod
era Ba returns an int variable thatrizrepresents
rbo ed
av
era the Ba binary of the
rbo
co b s s a c o b s sa
character, which p ies you .may s p s
m need to explicitly convert.
co . ies .co .
all all m
ow ow
ed ed
! !
• The ReadBlock method enables you to read an entire block of characters from a
specific index from the stream.
• The ReadLine method enables you to read an entire line of characters from the
stream.
Th Th
is is
do d oc
um c um
• Thema ReadToEnden
tb
method enables you to readmaall characters
en
t
from the current
rta elo rta be
.ba .ba lon
position
No rbin
os the stream.
ng
st No rbo
sa to
gs
un a @ oM un @ Ma
au p art au pri
tho rim aB tho m rta
riz av arb riz av Ba
ed era ed era rbo
co b s os co b s sa
pie s.c a. pie s.c .
sa om sa om
llo llo
Similarly, the StreamWriter we
d! object exposes various members to wenable ed
!
you to write
data to an underlying stream. The following list describes some of the key members:
• The AutoFlush property enables you to instruct the StreamWriter object to flush
data to the underlying stream after every write call.
Th Th
is is
do oc d
• The Close cu
me method enables you to close the StreamWriter
um object and the
ma nt ma en
rta be rt a.b tb
underlying
No
.ba
rbo
stream.
lon
gs No arb
elo
ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
• The Flush r i ze method
dc
ve enables
rab
Ba
rbo you to explicitly flush any riz data ain
ed ve the current
r arb buffer to
op sa co ab os
s s . pie ss a.
the underlyingiestream. sa .co
m sa .co
m
llo llo
we we
d! d!
• The NewLine property enables you to get or set the characters that are used for
new line breaks.
• The Write method enables you to write your data to the stream, and to advance
the stream.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 50/62
10/25/2019 20483A - Programming in C# | Skillpipe
• The WriteLine method enables you to write your data to the stream followed by a
new line break, and then advance the stream.
These members provide many options to suit many different requirements. If you do
not want to store the entire file in memory in a single chunk, you can use a
Th Th
is is
combination
do
c of the Peek and Read methods to read do each character, one at a time.
c
um um
m e
nt want to write lines of text to a file aone m e
art if you
Similarly,
a.b be rta at ntime,
tb
el you can use the
l
arb on .b arb on
ou N os st g No os stg
WriteLine
na method.
a@ oM un
au a@ oM
uth pri art tho p rim art
ori mav aB riz av aB
z ed era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
Reading Plain Text sa
llo
we
om sa
llo
we
om
d! d!
The following code example shows how to use the StreamReader and FileStream
classes to read a file that contains plain text. This example uses the Peak method to
advance through the stream of characters in the file.
Th
StreamReader Example Th
is is
do d oc
cum um
ma e nt en ma
rta be a.b tb rt
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
string tsourceFilePath
ho
riz
rim
av
rta
B
= tho
riz
rim
av aB
ed era a rbo ed era arb
c op b s s c o b s os
@"C:\\fourthcoffee\\applicationdata\\settings.txt
ies s.c a . pie s.c"; a.
all o m s all o m
ow ow
ed ed
!
// Create a FileStream object so that you can interact with the file !
// system.
FileStream sourceFile = new FileStream(
sourceFilePath, // Pass in the source file path.
FileMode.Open, // Open an existing file.
Th Th
is is
FileAccess.Read);//
do
cu
Read an existing dofile.
cu
ma m en ma me
StreamReader
rta t b reader = new StreamReader(sourceFile);
r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
StringBuilder
un s a@ t
fileContents
oM = new StringBuilder();
un s a@ to
a uth pri art a M uth pri art
o m a ori ma aB
// Check rizto a
ed seeverif ab
Ba
the rbo end of the file ze
d
ve
r ab
arb
co ss sa co ss os
pie .co . pie .co a.
// has been reached.sa m sa m
llo llo
we we
d! != -1)
while (reader.Peek() d!
{
// Read the next character.
fileContents.Append((char)reader.Read());
}
Th Th
is
// Store is
the file contents in a new string
do do variable.
c um c um
m e m e
i d fil i
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 () 51/62
10/25/2019 20483A - Programming in C# | Skillpipe
string data = fileContents.ToString();
// Always close the underlying streams release any file handles.
reader.Close();
sourceFile.Close();
Th Th
is is
do d oc
cum um
Writing
rta Plain
ma nt
b
Text e
a.b
maen
rttb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
The following
au
tho
code
@
prim
example
M a rta
shows how to use the aStreamWriter
u tho
@
p rim arand FileStream
riz r ta
av B ar iz a v B arb
classes to write ed a string era file on the file system. ed co era
co
pie bs to abonewsa pie bs os
a.
s.c . s.c
sa om sa om
llo llo
we we
d! d!
StreamWriter Example
string destinationFilePath =
Th@"C:\\fourthcoffee\\applicationdata\\settings.txt Th ";
is is
do do
string cdata um = "Hello, this will be writtencumin plain text";
ma en ma en
rta t rta tb
// Create .ba abelFileStream
on
object so that you . b can
a
elo
interact
ng
with the file
No rbo gs No rbo s
un sa to un sa to
// system.
au @ Ma au @ Ma
tho pri rta tho pri rta
riz m av Ba r m a Ba
e e ize ve
FileStream destFile d rab r
= onew
b FileStream( d r ab rbo
co s s a co s sa
pie s.c . pie s.c .
sa om sa om
destinationFilePath, llo
we
// Pass in the destination llo path.
we
d! d!
FileMode.Create, // Always create new file.
FileAccess.Write); // Only perform writing.
// Create a new StreamWriter object.
StreamWriter writer = new StreamWriter(destFile);
// TWrite
his
the string to the file. Th
is
do d oc
cu
writer.WriteLine(data); um
ma m en en ma
rta tb a.b tb rt
.ba
// NAlways elo
close the underlying streams to flush elo the data to the file
r bo n gs No a r bo ng
ou s t un s st
na a@ oM a @ oM
// and utrelease pri anyart file handles. a uth pri art
ho m a o m aB
riz av Ba riz av arb
ed era rb e d e r ab
writer.Close(); co
pie bs os
a. co
pie ss os
a.
s.c .co
sa om sa m
destFile.Close(); llo llo
we we
d! d!
In this demonstration, you will learn about the tasks that you will perform in the lab for
this module.
T Th
Scenario
his
do
is
d oc
cu um
ma me ma en
rta nt rt tb
b a
You Nhavebabeen
.
r
e lasked
on
g
to upgrade the Grades Prototype
N
. ba
r
application
elo
ng to enable users to
ou b os st o b o st
a o u s a o
save a nstudent’s
au
tho
@ grades
pri
m
Ma as an XML file on the local
rta
na disk. @
uth The
pri user
m
Ma should be able to
rta
riz av Ba o riz av Ba
ed era r e e rbthey
click a new button co on bthe
pie s StudentProfile
bo
s a.
view that asks the d c userrawhere
o pie b s os
a.
would
s.c s.c
s om s om
like to save the file,adisplays llo
we a preview of the data to the user, aand llo asks
we the user to
d! d!
confirm that they wish to save the file to disk. If they do, the application should save
the grade data in XML format in the location that the user specified.
Objectives
T Th
After hcompleting
is
do this lab, you will be able to: is
d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
• Serialize
un
au
data
sa
@ to ta o Mmemory stream. un
au a @ oM
tho pri art tho p rim art
riz m av aB riz av aB
ed era arb ed era arb
• Deserialize data c from os co os
s.c memory
a stream.
op b s a. pie b s a.
ies s.c
all o m sa om
ow llo
ed we
! d!
• Save serialized data to a file.
Th Th
is is
do do
• Virtual cuMachine: 20483A-SEA-DEV11-06,
me MSL-TMG1
cu
m
ma nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
• Userun Name s a@ Student
: to un os
a @
st
oM
au pri Ma au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
• Password: Pa$$w0rd co
pie ss
.
sa
.
co
pie bs
s.c
os
a.
sa c om sa om
llo llo
we we
d! d!
Scenario
T Th
his is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 53/62
10/25/2019 20483A - Programming in C# | Skillpipe
In this exercise, you will write code that runs when the user clicks the Save Report
button on the Student Profile view. You will enable a user to specify where to save
the Grade Report, and to serialize the grades data so it is ready to save to a file.
You will use the SaveFileDialog object to ask the user for the file name and location
where they want to save the file. They will only be able to save the file in XML format,
Th Th
i i
so yous will
do need to limit the file types displayed in sthe
cu
do dialog box. You will extract the
cu
ma me ma me
nt nt
grade data
r t a.b from belothe application data source and store r t a.b it in bea list of Grade objects.
lon
No arbo ng N a r b gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho m a t h o m rta
riz av Ba riz av Ba
You will then write e dc the
e rabFormatAsXMLStream
rbo
s
method. This e d c method e rab will
rbo use an
sa
op s s a . o p s s .
ies .co ies .co
XmlWriter object to llcreate a
ow
m an XML document and populate it with
a l l ow grade
m information
ed ed
! !
from the list of Grade objects.
Finally, you will debug the application and view the data held in the memory stream.
Task 1: Prompt the user for a filename and retrieve the grade data
Th Th
1. Start
is
do the MSL-TMG1 virtual machine if it is not
is already running.
do
cu cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
2. l n
NoStart rthebo 20483A-SEA-DEV11-06
ng
s
virtual machine
No rboandolog gs on as Student with
un s a t o u n s a to
@ Ma @ Ma
theaupassword
tho
riz
pri
ma Pa$$w0rd.
r ta
au
t ho
r
p r im rta
ve B a iz a v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
3. Start Visual Studio sa and
om from the E:\Labfiles\Starter\Exercise sa 1
omfolder, open the
llo llo
we we
d! d!
GradesPrototype.sln solution.
4. In the Views folder, open the StudentProfile.xaml user interface, and note that
it has been updated to include a Save Report button that users will click to
generate and save the Grades Report.
Th Th
is is
5. In dStudentProfile.xaml.cs,
oc
um
do
in the SaveReport_Click
cu
m method, add code to
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 54/62
10/25/2019 20483A - Programming in C# | Skillpipe
6. Save the return value from the dialog box in a nullable Boolean variable.
7. Check if the return value from the SaveFileDialog contains data. If it does, do
Ththe following: Th
is is
do do
cu cu
ma. me m me
art
a.b
Get nt the grades for the currently selected
b a r t
student
a.b
nt
be
and store them in a
elo l o
No arbo ng No a rbo ng
un generic
sa slist.
to un sa st
oM
au @ M au @
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
b. Call cthe op FormatAsXMLStream
bs
s
o sa
.
method, passing co the list
p bs of grades
s
os
a. to it,
ies .co ies .co
all m all m
and store othe we returned data in a MemoryStream object. ow
ed
d! !
Th Th
is is
4. Add
do code to enumerate the grades for the student
c
do
c
and add them as child
um um
ma en en m
elements
rta
.b
t b of the root node, using the following
e
art format:
a.b tb
e
arb lon arb lon
No o gs No os gs
un sa to un to a@
au @ Ma au Ma
tho pri rta pri tho rta
riz ma Ba riz ma Ba
ed ve rbo ed ve rbo
<Grade cDate="01/01/2012" rab Subject="Math" Assessment="A-"
co rab
op ss sa pie ss sa
ies .co . sa . c .
all m om
Comments="Good" ow /> llo
ed we
! d!
5. Add code to finish the XML document with the appropriate end elements.
6. Add code to flush the XmlWriter object and then close it to ensure that all the
Th Th
data
is
do
is written to the MemoryStream object.is
d
cu oc
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 55/62
10/25/2019 20483A - Programming in C# | Skillpipe
7. Add code to reset the MemoryStream object so that it can be read from the
start, and then return it to the calling method.
Th Th
is is
do d oc
c
Taskm3: Debug
um
en the application um
ma en
art t b rt tb
a.b elo a.b elo
No arb ng N arb ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
1. Build the riz solution
ed
av
era and B resolve
arb any compilation errors.
r ized
a vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
2. In the SaveReport_Click we
d!
method, add a breakpoint to the closing we
d!
brace of the
if block.
7. When you enter Break Mode, use the Immediate Window to view the contents
Th Th
is is
of the
doc MemoryStream object by using the following
um
do
cu code:
ma en ma me
rta tb rta n tb
.ba elo .ba elo
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
?(new tho StreamReader(ms)).ReadToEnd()
m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa co s os
pie s.c . p ies s.co a.
sa om a m
llo llo
we we
d! d!
8. Review the grade data that is returned.
9. Stop debugging, delete the breakpoint, and then close the solution.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 56/62
10/25/2019 20483A - Programming in C# | Skillpipe
Results: After completing this exercise, users will be able to specify the location
for the Grades Report file.
First, you will add code to the SaveReport_Click method to display the XML
document to the user in a message box.
To display the document, you need to build a string representation of the XML
Th Th
is is
documentdo that is stored in the MemoryStream object.
c
do
c
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No rbo gs No a rbo ng
sa verify s st
Finally,unyou
au will
@
p
t o that
Ma your code functions as uexpected
na
u
a @
p
by running
oM
art
the application
tho rim rta tho rim aB
riz a Ba of a report. riz av
and previewing ed thevecontents
co rab rbo ed
c
era arb
os
pie s s a o pie b s a.
s.c . s.c
sa om sa om
llo llo
we we
d! d!
The main tasks for this exercise are as follows:
MemoryStream object that you created in the previous task, and storing the
return value in a string variable.
3. Add code to preview the string version of the report data in a message box with
a caption of Preview Report, an OK button, and an information image.
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a rt tb
.
TaskN 2: Build
ba e
alostring representation of the XML . bdocument elo
r b ng N arb ng
ou os st o un o sa st
na a@ oM @ oM
uth pri art au p art
ori ma aB t h ori r ima aB
ze ve arb zed vera arb
dc rab o co bs os
op s s sa p s a.
1. In StudentProfile.xaml.cs,ies
all
.co
m
. in the FormatXMLData method,ies
all
add
.co code
m
to create
ow ow
a new StringBuilder ed object used to construct the string. ed
! !
2. Add code to create a new XmlTextReader object used to read the XML data
from the stream.
3. Add code to read the XML data one node at a time, construct a string
Th Th
is
representation
do
c of the node, and append it toisthe
do StringBuilder. The possible
c
um um
ma en ma en
nodes
rta
.ba that
t be can be encountered are XmlDeclaration,
lon
rta
.ba
t b Element, and
elo
No rbo gs No rbo ng
st
EndElement.
un
au
sa
@ tEach
o Ma element may have one or
u na more s a @attributes.oM
tho prim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b c b os
4. Add code to piereset sthe
sa
s
.co MemoryStream
s a . object and return o pie the string
s
s s.c
o
containing
a.
llo m a llo m
the formatted data we to the calling method.
d!
we
d!
Th Th
is is
Task 3: doRun the application and preview the data.
c
do
c
um um
ma en ma en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
un s st un osst
a @ oM a @ oM
1. Builda uth the solution
pri arand resolve any a
compilation uerrors. pri art
ori ma ta tho m aB
ze ve Ba riz av arb
dc rab rbo ed era
op ss sa co bs os
ies .co . pie s.c a.
2. Run the application. all m sa
llo
om
ow we
ed d!
!
3. Log in as vallee with a password of password99.
4. View Kevin Liu’s report, and then click Save Report to generate the XML
document.
Th his T
5. Specify
is
do to save the file in the default location. do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 58/62
10/25/2019 20483A - Programming in C# | Skillpipe
Note: You will write the code to actually save the report to disk in the
next exercise of this lab.
6. Review the XML data displayed in the message box and close the application.
Th Th
is is
do d oc
7. In Visual
ma
um
e
cStudio, close the solution. ma
um
en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b sa co bs os
Results: After pcompleting ies s s .co this . exercise, users will be able pto
ies preview s .co a areport
.
all m all m
before saving it. owe ow
ed
d! !
Then you will run the application, generate and save a report, and then verify that the
report
T has been saved in the correct location in Tthe correct format.
his his
do do
cum cu
ma e me ma
rta nt nt rt
belofor this exercise are as follows: a be
TheNmain.batasks
r b ng N
.ba
r b
lon
gs
ou os s t o un o s to
na a@ oM a@ Ma
uth pri art a uth pri
ori ma aB ori ma rta
ze ve a ze ve Ba
rbo rbo
1. Save thed cXML op
ies
rab
document
ss
.co
sa
.
to disk dc
op
ies
rab
ss
.co
sa
.
all m all m
ow ow
ed ed
2. Run the application ! and verify that the XML document is saved ! correctly
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 59/62
10/25/2019 20483A - Programming in C# | Skillpipe
4. If the user clicks Yes to save the report, open the file that the user specified and
Thcreate a FileStream object to write data toThthis file.
is is
do do
cu cu
m me
5. mWrite
art
a.b
en data from the MemoryStream object
the t be
ma
rta to the nt file.
be
a lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
Task 2: Run the application we
d! and verify that the XML document we is saved
d!
correctly
6. Review the XML data displayed in the message box, and then confirm that you
want to save the file.
7. ThClose the
is
application. Th
is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 60/62
10/25/2019 20483A - Programming in C# | Skillpipe
8. Open the saved report in Internet Explorer and verify that it contains the
expected grade data.
T
his his T
Results: do After completing this exercise, users will
cu
dobe able to save student reports
cu
m me
to the
ma localenhard disk in XML format.
rt tb
ma
rt nt
b
a.b elo a.b elo
No arb ng No arb ng
un o sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
Module Review and Takeaways llo
we
d!
llo
we
d!
Module Review
In this module, you have learned how to work with the file system by using a number
of classes
Th in the System.IO namespace, and how
Th to serialize application data to
is is
do do
different
ma
formats.
u m
c
en ma
cu
me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
Question: @ @
a uth prYou
i
M
areart a developer working on theutFourtha
h priCoffee Ma Windows
rta
ori m a aB ori m a Ba
Presentation ze ve
Foundation arb (WPF) client application.zYou ed have ve been rboasked to store
dc rab os co r ab
op s s.c a pie s s.c sa
ies . .
some settings ain llo
a plain
om text file in the user’s temporary folder sa
llo
on
om the file system.
we we
Briefly explain which d! classes and methods you could use to achieve d! this.
Question: You are a developer working for Fourth Coffee. A bug has been
raised and you have been asked to investigate. To help reproduce the error, you
have decided to add some logic to persist the state of the application to disk,
Twhen
his the application encounters the error. TAll
his the types in the application are
do do
serializable,
c um and it would be advantageous if the cu persisted state was human
me
ma en ma nt
rta
readable. t b What approach will you take? r t a be
.ba elo .ba lo
No rbo ng No rbo ng
un sa st un sa st
@ oM @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
Test Your Knowledge co
pie bs
s.c
os
a. co
pie bs
s.c
os
a.
sa om sa om
llo llo
we we
d! d!
Question
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 61/62
10/25/2019 20483A - Programming in C# | Skillpipe
Question
You are a developer working for Fourth Coffee. You have been asked to write some
code to process a 100 GB video file. Your code needs to transfer the file from one
location on disk, to another location on disk, without reading the entire file into
Th Th
is is
do d oc
cu u
memory. me classes would you use to read and writemthe file?
ma Which me
n
rta tb a n r tb
.ba elo t a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
Select the correct
riz answer.
av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
The MemoryStream, sa om sa om
llo BinaryReader and BinaryWriter classes. llo
we we
d! d!
The FileStream, BinaryReader and BinaryWriter classes.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 62/62
10/25/2019 20483A - Programming in C# | Skillpipe
Contents:
Th Th
is is
do d oc
cum um
ma nt e ma
en
rta b a tb
rt
e elo
rbo Module Overview
.ba lon . ba
No gs No rbo ng
un sa to un sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
Lesson 1: rizeCreating
dc
av
era and B Using
arb Entity Data Models r ized
a vera arb
op bs o sa co bs os
ies s .co . p ies s .co a.
all m all m
Lesson 2: Querying ow Data by Using LINQ
ed
ow
ed
! !
Th Th
is is
do d oc
cum um
ma e ma en
Module
N
rta
.ba Overview
rb
be
lon
g
nt
No
rt a.b elo
arbng
tb
ou os st u o s st
na a @ o Ma na a @ oM
uth pri r t u t h p r i art
ori m av aB ori m av aB
ze era a rbo zed era arb
dc b c b os
Many applications opie require s s.c access s a to data that is stored in a pdatabase. o s s.c Microsoft®
a.
sa . ies
om a o m
ll llo
Visual Studio® 2012 oand we the Microsoft .NET Framework provide
d!
wtools
ed
!
and
functionality that you can use to easily access, query, and update data.
In this module, you will learn how to create and use entity data models (EDMs) and
how to query many types of data by using Language-Integrated Query (LINQ).
Th Th
is is
do d oc
cum um
Objectives
ma
rta nt
b
e ma
rt a.b
en
tb
.ba elo elo
No rbo ng No arb ng
un s st un os st
a oM a oM
After completing
au
tho
@ this
pri module,
art you will be able to: au
tho
@
pri art
riz m av aB riz m av aB
ed era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
• Create, use, and lcustomize low
ed
an EDM. llo
we
! d!
Lesson
Th
1 : Creating and UsingThEntity Data Models
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/33
10/25/2019 20483A - Programming in C# | Skillpipe
Data access applications have traditionally been tedious to develop. They often
contain queries that are written as text strings that cannot be type-checked or syntax-
checked at compile time, and results are returned as untyped data records. The
ADO.NET Entity Framework solves these problems and simplifies the process of
developing data access applications by using EDMs.
Th Th
i i
In this slesson,
do
cu
sd
you will learn how to use the ADO.NEToc Entity Data Tools to create
u
ma me ma me
nt nt
EDMs, howr t a.b to bcustomize
elo the classes that the toolsagenerate,
.b
rt
be
lo and how to access the
No arbo ng No arb ng
s os st
entitiesunainu thesa@ generated
pri
to
Ma model. un
au a@
p
oM
art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
Lesson Objectives llo
we
llo
we
d! d!
• Use
Th the ADO.NET Entity Data Model Tools.
is
Th
is
do d oc
cum um
ma e nt ma en
• Customize
rta bgenerated classes. rt a.b tb
.b elo elo
No arb ng No arb ng
un o
sa st un os st
@ oM a @ oM
au pri art au p art
• t
Read and ori modify t r
av data a Bby using the Entity Framework.
h m h ori im aB
ze arb ze av arb
dc era dc era
op b s os op b s os
ies s.c a. ies s.c a.
all o m all o m
ow ow
ed ed
! !
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Historically when you write code to access data that is stored in a database, you
have to understand the structure of the data in the database and how it all
interrelates. Often it is stored in a normalized fashion, where tables do not logically
map to the real-life objects that they represent. The ADO.NET Entity Framework
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/33
10/25/2019 20483A - Programming in C# | Skillpipe
enables you to develop applications that target a conceptual model instead of the
normalized database structure in the storage layer.
• EDMs.
T
These are models that you can use toT map database tables and queries to
his his
.NETdoFramework
cu
m
objects. do
cu
me
ma en ma nt
rta tb r t a.b be
.ba elo lon
N r b ng N a r b gs independent query
• Entity
o u Structured
na
os
a
s t Query Language (SQL). This
o o uis a storage
na
os
a to
uth @ M uth @ Ma
pri art pri rta
languagerizthat m
enables Byou m
arb to query and manipulateriEDM constructs.
o av a o av Ba
ed era ze e rbo
co b os dc rab
pie s s.c a. o pie s s.c sa
sa sa .
om om
• Object Services. These l are services that enable you to work owith l
l ow
ed
l we the Common
! d!
Language Runtime (CLR) objects in a conceptual model.
• Write standard code that is not dependent on the data storage system.
• Write data access code that supports compile-time type-checking and syntax-
checking.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be model that you work with in the Entity rt
a.b Framework tb
The conceptual
.ba
r
lon a r
elo
ng describes the
No bo gs No bo s
un s t oM un s t oM
semantics au of athe @ business
pri art view of the data. It definesau entities a@
pri and arelationships in a
tho m a tho m rta
riz av B arb r ize a ve B arb
business sense ed anderis ab mapped
co ss os to the logical model of the d cunderlying
o
rab
s
data
os in the data
pie .co a . p ies s.co a.
sa m m
source. For example, llo in a human resources application, entitiesllomay include
we
a
we
d! d!
employees, jobs, and branch locations. An entity is a description of the items and
their properties, and they are linked by relationships, such as an employee being
related to a particular branch location.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/33
10/25/2019 20483A - Programming in C# | Skillpipe
Visual Studio 2012 provides the Entity Data Model Tools that you can use to create
and Tupdate
his EDMs in your applications. It supports
Th both database-first design and
is
do do
u c cu
code-first
ma design:
m en ma me
nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
t pri art pri
• Database-first
h ori
ze
mdesign.
ave
a BIn database-first design, youordesignaand rcreate
ize
m
ve
ta
Ba your
dc rab arb d r rbo
op o sa c op a b sa
database before ies you ss generate
.co . your model. This is commonly ies used
ss
.co when . you are
all m all m
ow ow
developing applications ed
!
against an existing data source; however, ed this can limit the
!
flexibility of the application in the long term.
• Code-first design. In code-first design, you design the entities for your application
and then create the database structure around these entities. Developers prefer
this
T method because it enables you to designT your application around the
his his
do
business cu functionality that you
me require. However,docinumreality, you often have to work
ma nt ma en
rta be rt tb
with an .ba existing
rbo
lon data source. a.b
arb
elo
ng
No gs No os st
un s a@ to un a oM
au Ma au @
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
om om
Using the Entity Data Model Tools llo
we
llo
we
d! d!
Visual Studio 2012 provides the ADO.NET Entity Data Model Tools, which include the
Entity Data Model Designer for graphically creating and relating entities in a model
and three wizards for working with models and data sources. The following table
describes the wizards.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/33
10/25/2019 20483A - Programming in C# | Skillpipe
Wizard Description
Entity Data Model Wizard Enables you to generate a new conceptual model from an existing data
source by using the database-first design method.
Update Model Wizard Enables you to update an existing conceptual model with changes that
are made to the data source on which it is based.
Th Th
is is
do
Generate Database Wizard Enables you to generate a database do
cu cu from a conceptual model that you
ma me m me
rta n tb have designed in the Entity a
Data
r Model nt Designer by using the code- first
.ba elo t a.b be
ng a lon
No rbo st design method. N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
co b s c o b sa
When you createpieas model s s.c by using
om
a. the Entity Data Model Wizard,
pie
sa
s sthe
.co model . opens in
all l l m
ow ow
the Designer pane, displaying ed
!
the entities that the wizard has generated ed
!
and the
relationships between them. You can use this pane to add, modify, and delete entities
and relationships.
By default, when you create a model from a database, the Entity Designer
Th
automatically
is
d
generates the mappings from the Tdata
his
d
source to the conceptual model.
oc oc
me u me u
You can
ma view,
r nt modify, and delete these mappings
ma in the
r nMapping
t Details pane.
ta. be ta. be
ba lon ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba Model
Additional ed
co
Reading:
era arbFor more information aboutzethe
os d co
Entity
ve
r ab Data rbo Tools,
pie b s a pie s sa
s.c . s.c .
see the ADO.NET sa Entity
om Data Model Tools page at sa om
llo llo
we
http://go.microsoft.com/fwlink/?LinkID=267807. we
d! d!
Th T
is
do
c
Note: If necessary, click Switch Userhistododisplay
c
the list of users.
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/33
10/25/2019 20483A - Programming in C# | Skillpipe
6. In Visual Studio, on the File menu, point to Open, and then click File.
Th Th
is is
do oc d
7. In the
ma
umOpen File dialog box, browse to the E:\Democode\Database
e
c
m
um
e
folder, click
r nt ar nt
ta. be ta. be
N
AttachFourthCoffeeDatabaseScript.sql,
ba
rb
lon
g
and
N
then ba click
rb
loOpen.
ng
ou os st ou os st
na a@ oM na a@ oM
uth pri art uth pri art
ori ma aB ori ma aB
8. On the zSQL
ed menu,
v era point
arb to Transact-SQL Editor, z and
ed then
vera click arbExecute.
co b s o s c o b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
9. In the Connect to we Server dialog box, in the Server name box,
d!
we
d! type
(localdb)\v11.0, and then click Connect.
Note: If the query times out, in the Connect to Server dialog box, click
OK, and then in the Connect to Server dialog box, click Connect.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
a ng Close.
10. NoWhen
un
rbothe query
sa
gs
t o
has completed, on the File
No menu,
u
rbo click
s a
st
oM
au @ Ma na @
tho p rim rta u tho p rim art
riz av B riz av aB
ed era a rbo to New, and then click Project. ed era arb
11. On the File co menu,
pie b s point s a c o pie b s os
a.
s.c . s.c
sa om sa om
llo llo
we we
12. In the New Project d! dialog box, expand Templates, click Visual d! C#, and then in
the Template list, click Console Application.
13. In the Name box, type FourthCoffee.Employees, in the Location box, type
E:\Democode\Demo1\Starter, and then click OK.
Th Th
is is
14. In Solution
doc
um
Explorer, right-click FourthCoffee.Employees, do
cu point to Add, and
ma en ma me
t b New Item. n tb
then
rta click
.ba elo rta
.ba elo
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
15. t
In the rAdd New av ItemBa– FourthCoffee.Employees dialog box, click
a B ADO.NET
h o m a o m
ize riz av arb
dc e rab rbo e dc e rab
o s sa o s os
Entity Data iModel, p es s .cin
o
the .Name box, type FourthCoffeeEmployeesModel,p ies s.co a. and
all m all m
ow ow
then click Add. ed! ed
!
16. In the Entity Data Model Wizard, on the Choose Model Contents page, click
Generate from database, and then click Next.
17. On the Choose Your Data Connection page, click New Connection.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/33
10/25/2019 20483A - Programming in C# | Skillpipe
18. In the Choose Data Source dialog box, in the Data source list, click Microsoft
SQL Server, and then click Continue.
19. In the Connection Properties dialog box, in the Server name box, type
(localdb)\v11.0, in the Select or enter a database name list, click FourthCoffee,
and then click OK.
Th Th
is is
do do
20. In the cu Entity Data Model Wizard, on the Choose
me
cu Your Data Connection page,
me
ma n m a nt
rta tb r t be
click .baNext.
rbo
elo
ng
a.b
a r
lon
No st N ou b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
21. On therizChoose m a
av YourBaDatabase Objects and Settings o m
ed page,
riz av expand Ba Tables,
ed era rbo era rbo
co b s s a. c o b s sa.
expand dbo, pie select s.cBranches, Employees, and JobTitles, pie ands.cthen click Finish.
sa om sa om
llo llo
we we
d! d!
22. In the Security Warning dialog box, select Do not show this message again, and
then click OK.
24. ThReview
is
Th
the three entities that have been generated
is and the associations
do do
c
um cu
mbetween
art en them. ma me
nt
a.b t be rta be
a lon .ba lon
No rbo gs No rbo gs
sa sa
25. un
Right-click
au @ thetodesigner M surface, and then un
clicka Mapping
uth @ to
Details.
Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
p s s a p s s sa
26. In the Designer i es
all
pane, .co click Employee.
m
. i es
all
. co
m
.
ow ow
ed ed
! !
27. In the Mapping Details pane, review the mappings between the entity and the
data source.
31. Review the Employee partial class and the properties that have been
generated.
32. Leave the solution open so that you can refer to it in the following topics.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/33
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
When you use thes Entity all oData
m Model Wizard to create a model, s a it automatically
llo
om
ow we
ed d!
generates classes that expose ! the entities in the model to your application code.
These classes contain properties that provide access to the properties in the entities.
The following code example shows an Employee class that the Entity Data Model
Wizard generated.
Th Th
is is
do d oc
cum um
ma e nt ma en
Wizard-Generated
rta be Classes rt a.b tb
.b lo elo
No arb ng No arb ng
un sa o st un os st
@ oM a @ oM
au pri art au p art
tho m aB tho rim aB
riz av arb riz av arb
ed era ed era
co b s os co b s os
pie s.c a. pie s.c a.
s
namespace FourthCoffee.Employees
all o m sa om
ow llo
ed we
! d!
{
using System;
using System.Collections.Generic;
public partial class Employee
{
Th Th
is sd i
dopublic int EmployeeID { get; set; oc}
um c um
ma en ma en
rta public tb r
string FirstName { get; set;ta. }t bel
.ba elo b on
No r bo n gs No a r bo gs
un s t un s to
a public string LastName { get; set; a } a@
a@ oM M
uth pri art uth pri art
ori ma aB ori ma aB
ze
public vNullable<System.DateTime> z
DateOfBirth v
dc e rab a rbo e dc e rab { get; arb
os
set; }
op s s sa o p s s a.
ies .co . ies .co
public Nullable<int>
all m Branch { get; set; } all m
ow ow
ed e
public Nullable<int> JobTitle { get; set; } d!
!
You may find that you want to add custom business logic to the entity classes;
however, if at any time in the future you run the Update Model Wizard, the classes
will be regenerated and your code will be overwritten. However, the generated
classes are defined as partial classes; therefore, you can extend them to add custom
functionality to the classes.
Th Th
is is
do d o
c cu
For example,
m
um if you have a date of birth property in your
en m me model, you could write a
n
art tb art tb
a.b elo a.b elo
GetAge
No method
arbo nings a partial class to enable a run-time
No arbcalculation
o
ng
st
of the employee’s
un sa to un sa oM
@ M @
age. autho pri
ma
art
aB
au
tho pri
ma
art
aB
riz v arb r iz v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
The following code example we
d! shows how you can add business logic we to a generated
d!
class by using a partial class.
Th Th
is is
do do
u c cu
public
ma m
partial
en class Employee ma me
rta t r nt
.ba belo t a .ba be
n lon
{ No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
publictho pri
int art
GetAge() pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
{ pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
DateTime wDOB ed = (DateTime)_DateOfBirth; we
d!
!
TimeSpan difference = DateTime.Now.Subtract(DOB);
int ageInYears = (int)(difference.Days / 365.25);
return ageInYears;
}
} Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
au a
Additional
tho pri Reading:
m
art
a For more information about uth partial
o
pri
m classes,
art
aB see Partial
riz av Ba riz av a
ed era rbo(C# Programming Guide) at d e e rbo
Classes and co
pie
Methodsbs sa co
pie
rab
ss sa
s.c . . c .
sa om
http://go.microsoft.com/fwlink/?LinkID=267808. sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/33
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
The automatically
au
tho prim generated
M a rta code files for a model aalso
u tho contains
p rim aart partial class that
riz av B r a aB
arb iz v arb
inherits from ethe op
era
d c System.Data.Entity.DbContext
bs o sa class. ed
Theco
p
era
DbContextbs os class
a.
ies s .co . ies s .co
a m a m
provides facilities for oquerying l l we and working with entity data as objects. l l ow It contains a
d! ed
!
default constructor which initializes the class by using the connection string that the
wizard generates in the application configuration file. This defines the data
connection and model definition to use. The DbContext class also contains a DbSet
property that exposes a DbSet(TEntity) class for each entity in your model. The
DbSet(TEntity)
T class represents a typed entity Tset that you can use to read, create,
his his
update,dand
oc
um delete data.
do
cu
me
ma en ma nt
rta tb rt a.b be
.ba elo lon
No rbo ng No arb gs
un sa st un os to
@ oM a@
The following
au
tho code
prim example art
aB
shows the class for theutFourthCoffeeEntities
a
ho pri
m
Ma
rta model.
riz av a riz av B a
ed era rbo ed era rbo
co bs sa co bs sa
pie s.c . pie s.c .
sa om sa om
FourthCoffeeEntitiesweClass l l o llo
we
d! d!
To use the typed entity set, you create an instance of the DbContext class and then
Th Th
accessis dthe is
oc properties by using the standard dot notation.
do
c
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/33
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to read and update data by using the
DbSet(TEntity) class.
Reading Data
Th Th
sd i sd i
FourthCoffeeEntities
oc
u
DBContext = new FourthCoffeeEntities();
oc
u
ma en m ma en m
rta
// Print t rta tb
.ba a blist elo of employees. .ba elo
No rbo ng N r b ng
un sa s to o un emp sain o st
foreach (FourthCoffee.Employees.Employee
@ M @ oM
DBContext.Employees)
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
{ ed era
o
ed era
os
co bs sa co bs a.
pie s.c . pie s.c
Console.WriteLine("{0} sa om {1}", emp.FirstName, emp.LastName); sa om
llo llo
we we
d! d !
}
// TUpdate
his the employee with a surname Tof
his "Prescott."
do do
var mempcum=e DBContext.Employees.First(e =>
ma
cu
e.LastName
me == "Prescott");
art nt rta nt
a.b be .ba be
if N(empar!= lon
null) lon
ou b os gs No rbo gs
na a@ to un s a@ to
{ uth pri Ma au pri Ma
ori ma rta tho ma rta
ze ve Ba riz ve Ba
dc rbo
rab= "Forsyth"; ed rab rbo
emp.LastName op ss sa co
pie ss sa
ies .co . sa . c .
all m om
} ow llo
ed we
! d!
After you change the data in the model, you must explicitly apply those changes to
the data in the data source. You can do this by calling the SaveChanges method of
the ObjectContext
Th
is
object. Th
is
do d oc
cum um
ma e
nt ma en
rta be rt a.b tb
.ba lon lon e
TheNfollowing
ou r bos code gs example shows how to use Nthe
o SaveChanges
arb
o gs method.
na a to un sa to
uth @ Ma au @ Ma
pri rta tho pri rta
ori ma Ba riz m av Ba
ze ve rbo ed era rbo
dc rab co b
Persisting Changes o pie To
s s.c ThesaDatabase
. pie s s.c sa
.
sa om sa om
llo llo
we we
d! d!
DBContext.SaveChanges();
Th Th
is is
Demonstration:
do
cu
m
Reading and Modifying
do
cu
m
Data in an EDM
ma en ma en
rta tb rt tb
a.b
.ba elo elo
In this
No demonstration, you will use the a
ObjectSet(TEntity) classs t to read and modify
rbo ng No rbo ng
un sa st un sa
@ oM @ oM
au pri art au pri art
data in anthoEDM.riz ma aB tho
riz m av aB
ed v era arb ed era arb
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
Demonstration Steps we
d!
we
d!
6. In Visual Studio, on the File menu, point to Open, and then click
ThProject/Solution. Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/33
10/25/2019 20483A - Programming in C# | Skillpipe
13. Verify that the employees list is displayed, and then press Enter.
Th Th
is is
do do
14. Verify cu that the employee named “Diane
me Prescott”
cu is now named “Diane
m
ma nt ma en
rta band rt tb
Forsyth,”
.ba
rbo
elo
ng
then press Enter. a.b
arb
elo
ng
No s No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
15. Press iEnterr m toveclose
a Bathe application. riz av aB
ze rbo ed era arb
dc rab co b os
op s s.c sa pie s s.c a.
ies . sa
all om om
ow llo
ed we
! d!
As an alternative to using the Entity Framework for querying data, you can use LINQ.
This Talso
his supports compile-time syntax-checking
Th and type-checking and also uses
is
do do
cu cu
Microsoft
ma IntelliSense®
me
n
in Visual Studio. LINQ defines
ma ma
en range of standard query
rta tb rta tb
.ba lon e .ba lon require in a declarative e
operators
No that
rbo enable
gs you to retrieve exactly theNodata rthat
bo you gs
un sa to un sa to
@ Ma @ Ma
way. author pri
ma rta
Ba
au
tho
riz
pri
ma rta
Ba
ize ve ed ve
dc rab rbo rab rbo
op ss sa co ss sa
ies .co . pie . c .
all m sa om
ow llo
In this lesson, you will elearn d! how to query data and use anonymous we methods
d! and
how to force query execution to override the default deferred query execution
behavior.
Lesson Objectives
Th Th
is is
do d oc
After completing
cu
me this lesson, you will be able to: um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/33
10/25/2019 20483A - Programming in C# | Skillpipe
• Query data.
Th Th
is is
do d
Querying
ma
um Data
en
c
ma
oc
um
en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
You candouse
cu
m
LINQ to query data from a wide rangedoof
cu data sources, including .NET
m
ma en ma en
rta tb rta tb
Framework
.ba collections,
elo Microsoft SQL Server® databases,
.ba eloADO.NET data sets, and
No rbo ng No rbo ng
s s s st
u
XML documents.
na
uth
a @ Intofact, Ma you can use it to query u
any
na data@source
uth
a o M that implements the
pri rta pri art
ori ma Ba ori m av aB
IEnumerable ze interface. ve rbo ze era arb
dc rab dc b os
op s s.c sa op s s.c a.
ies . ies
all om all o m
ow ow
ed ed
! !
The syntax of all LINQ queries has the same basis, as follows:
select
Th <variable names> Th
is is
do d oc
cum um
ma ent ma en
rta be a.brt tb
. elo
However,
No
b ayou
r bo canl on gscustomize this syntax in many
No ways a r bo retrieve
to ng exactly the data
un s t u s st
a @ o M n a @ o Ma
that youaurequire
tho prinim the aformat rta
au
that you want. The following
tho pcode
rim examples
rta all use
riz av B arb r ize a ve Ba
ed era dc rabthe query rbo
LINQ to Entities co to query
pie bs data
s.c
os in an EDM; however, the syntax
a. op of ss sa itself does
.
sa om i e sa . com
l
not change if you usewae different type of data source.
l o l l o we
d! d!
Selecting Data
The following code example shows how to use a simple select clause to return all of
the data in a single entity.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/33
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c u u
The return
ma mdata
en ma me
type from the query is an IQueryable<Employee>, enabling you to
r t r nt
ta. be ta. be
ba lon ba lon
iterate
N o uthrough
r bos the gsdata that is returned.
to
No
un
rbo
sa
gs
to
na a @ Ma au @ Ma
uth pri rta tho pri rta
ori ma Ba riz m av Ba
ze ve rbo ed era rbo
dc rab co b
op sa sa
Filtering Data by Row ies
all
s s .co
m
. pie
sa
s s.c
om
.
ow llo
ed we
! d!
The following code example shows how to use the where keyword to filter the
returned data by row to contain only employees with a last name of Prescott.
}
private void FilteringDataByColumn()
{
IQueryable<FullName> names = from e in DBContext.Employees
select new
FullName { Forename
Th Th
is is
= e.FirstName,
do
cu
Surname = e.LastName }; do
cu
ma me m me
} rta n tb a r nt
. e t a. be
ba lon ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ Ma au @ Ma
tho pri rta tho pri rta
riz m av Ba riz m av Ba
ed era rbo ed era rbo
co b s sa co b s sa
pie s.c . pie s.c .
sa om sa om
Working with the Results llo
we
d!
llo
we
d!
To then work with the data that is returned from any of these queries, you use dot
notation to access the properties of the members of the IQueryable<> type, as the
following code example shows.
Th Th
is
Accessing the Returned Data is
do d oc
c um um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un osst
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
foreach (var r ize a
emp ve in Bemps) arb riz av arb
dc rab ed era
op s os co b s os
ies s.c a. pie s.c a.
{ all o m sa om
ow llo
ed we
Console.WriteLine("{0} ! {1}", emp.FirstName, emp.LastName); d!
Demonstration:
Th
is
Querying Data Th
is
do oc d
c um um
ma e ma en
In this demonstration,
rta
.ba
n tb
elo
you will use LINQ to Entitiesr ta. query
to t b data.
elo
n b a ng
No r bo gs No r bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
m a o m aB
Demonstration Steps riz
ed
co
av
era Ba
rbo
riz
e d co
av
e r ab
arb
os
pie bs sa p s a.
s.c . ies s.co
sa om a m
llo llo
we we
d! d!
1. Start the MSL-TMG1 virtual machine if it is not already running.
9. Th
Review the LINQ code in each of the methods.
T
is his
do do
cum cu
me
10. mOn
art the nBuild
tb menu, click Build Solution.
e ma
rt nt
be
a.b elo a .ba lon
No arbo n gs No rbo gs
un sa to un sa to
@ M @ Ma
11. On uthe
a
tho Debug pri
m
menu,
art
aB
click Start Without Debugging.
a uth
ori
pri
m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
12. In the console s awindow,
llo
om review the output of the QueryingData sa
llo
omethod,
m and
we we
then press Enter. d! d!
a. FilteringDataByRow
Th Th
b.
is
do FilteringDataByColumn is
d
c oc
um um
ma ent ma en
rta be rt a.b tb
14. Press .ba Enter lon to close the application. elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
15. In Visual r i ze Studio, ve on Bthe arb File menu, click riz
Close Solution. av arb
dc rab ed era
op s os co bs os
ies s .co a. pie s.c a.
all m sa om
ow llo
ed we
! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/33
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
In the examples
au
tho p in
rim the M aprevious
rta topic and demonstration,
au
tho the
p rim return art data was always
riz av B r a aB
ed era arb ized vera ar
stored in a strongly co
pie
typed
bs IQueryable<Type>
o sa variable; however,
co
pie bs thebofiltering
in sa by
s.c . s.c .
s om s om
column scenario, it ais llo necessary
we to define the type containing aallosubset we of columns
d! d!
before defining the query. Although this is a perfectly valid way of working, it can
become tedious to explicitly define multiple classes.
You can use anonymous types to store the returned data by declaring the return type
as an
Th implicitly typed local variable, a var, and by
Th using the new keyword in the
is is
oc d d oc
select
m
clause
um
e
to create the instance of the type.m um
en
art nt art tb
a.b be a.b elo
arb lon arb ng
No o gs No os st
un sa to un a oM
@ Ma @
Filtering Data by Column
au
tho
riz
pri
m av
rta
au
tho
riz
p rim
av
art
aB
ed era Ba ed era arb
rbo os
co b s sa co b s a.
pie
The following codes aexample s.c .
om shows how to use the var datapitype es
all ands.c
o mthe new
llo ow
we
keyword in the select clause d! to filter the returned data by column.ed!
Th Th
is
var names = from e in DBContext.Employeesis
do do
cu cu
ma m en ma me
select nt
new
rta
.ba
tb
elo r t a .ba be { e.FirstName,
n lon
No r bo gs No r bo gs
e.LastName
un s a@}; t oM un s a@ to
M
au pri art au pri art
tho m aB tho ma aB
riz av arb riz ve arb
ed e
rab ed r ab
co ss os co ss os
pie .co a. pie .co a.
sa m sa m
llo l
Anonymous types enable we
d! you to perform more complex queriesloin we LINQ.
d!
Grouping Data
The following code example shows how to use a group clause to group the returned
employees by their job title ID.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/33
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is
var emps = from e in DBContext.Employees is
do do
cu cu
ma m en ma me
rta t group e by e.JobTitle r into nt eGroup
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa
@ to
M
select new { Job = eGroup.Key,un sa
@ tCountOfEmployees
oM =
au pri art a uth pri art
tho m m
eGroup.Count() riz av}; a Ba ori
ze av aB
arb
ed era rbo dc era
co b s s o b s os
pie s.c a . pie s.c a.
s
all om s all o m
ow ow
ed ed
! !
Navigating Data
The following code example shows how to use navigation properties to retrieve data
from the Employees entity and the related JobTitles entity.
Th Th
is is
do oc d
cum um
ma e ma en
Using rDot
ta. Notation
n t be to Navigate Related Entitiesr ta. tb
elo
ba lon ba ng
No r bo gs No r bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
p ies e in s . p ies s s a.
var emps = from .co DBContext.Employees .co
all m all m
ow ow
ed select new ed
! !
{
FirstName = e.FirstName, LastName =
e.LastName, Job =
e.JobTitle1.Job
Th Th
is }; is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/33
10/25/2019 20483A - Programming in C# | Skillpipe
a. GroupingData
b. AggregatingData
c. NavigatingData
Th Th
is is
do d oc
14. mPress c
umEnter to close the application. um
eart nt ma en
a.b be rt a.b tb
lon elo
No arb gs No arb ng
os os st
15. InnaVisual
u
uth
a @Studio,
pri
to on the File
Ma menu, click Close
un Solution.
au a @
p
oM
art
ori ma rta tho rim aB
ze ve Ba riz av arb
dc rab rbo ed era
op s sa co bs os
ies s .co . pie s.c a.
all m sa om
ow llo
ed we
d!
Forcing Query Execution !
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we w
By default, when you define d! a LINQ query that returns a sequenceed!of values, it is not
run until you actually try to use some of the returned data. This feature is known as
deferred query execution and ensures that you can create a query to retrieve data in
a multiple-user scenario and know that whenever it is executed you will receive the
latest information.
Th Th
is is
do oc d
cum um
ma e
nt code example, the ma en
In the following
rta
.ba be
lon
query is not actually
rta
.ba
executed
tb
elo until the start of the
No rbo gs No r bo n gs
foreach un block.
au
s a@ to
Ma un
au
sa
@ to
Ma
tho pri rta tho pri rta
riz ma Ba riz ma Ba
ed ve rbo ed ve rbo
co rab co rab
pie ss sa pie ss sa
.c . . c .
Deferred Query Execution sa
llo
om sa
llo
om
we we
d! d!
Conversely, when you define a LINQ query that returns a singleton value, for
example, an Average, Count, or Max function, the query is run immediately. This is
Th as immediate query execution and is necessary
known Th in the singleton result
is is
d oc d oc
me u meto calculate the singleton u
scenario
ma because
r nt the query must produce a sequence
ma
r nt
ta. be ta. be
ba lon ba lon
result.
N ou r bos g st N ou r b os gs
to
na a @ o M na a @ Ma
uth pri art uth pri rta
ori ma aB ori ma Ba
ze ve a r ze ve rbo
dc rab bo dc rab
op s s o s sa
You can overrideiethe s a default
s .co deferred query execution behavior
a . p ies for .queries
s co . that do
llo m a llo m
we we
not produce a singleton d!result by calling one of the following methods d! on the query:
• ToArray
• ToDictionary
Th Th
is is
• ToListdo
cu
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
r m a Ba riz av aB
In the following ize code
dc
ve example,
rab rbo the query is executed immediately
ed era after arb it is
os
defined.
op s sa co b s a.
ies s.c . pie s.c
all om sa om
ow llo
ed we
! d!
Forcing Query Execution
Scenario
You have been asked to upgrade the prototype application to use an existing SQL
Server
T database. You begin by working with a database
T that is stored on your local
his his
machinedocand do
um decide to use the Entity Data Model Wizard
cu
m to generate an EDM to
ma en ma en
tb tb
accessrtathe r
elo You will need to update the data raccess
.ba data.
n
ta.
ba
r
code
elo
n
for the Grades section
No bo gs No bo gs
un sa to un sa to
of the application,
au
tho
@
pri to display
M art grades that are assignedau to a pstudent
t h
@
r
Ma and to enable
rta
m a o im
riz av Ba riz av Ba
users to assign e e
d c new rgrades. boYou also decide to incorporate e e
d c validation rlogic
sa into the
ab r rab bo
op s s s a o p s s
ies .co . ies .co .
EDM to ensure thatalstudents low m cannot be assigned to a full classalland that m the data that
ow
ed ed
! !
users enter when they assign new grades conforms to the required values.
Objectives
After completing this lab, you will be able to:
Th Th
is is
do d oc
cum um
ma e ma en
• Create
rta anntEDM
be from an existing database. rt a.belo
tb
.ba lon arb
No rbo gs No ng
un sa to un stos
@ Ma a @ oM
au au
• Updatethodata pby rim using rta the .NET Entity Framework.tho p rim art
aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
• Extend an EDMs ato llo validateom data. sa
llo
om
we we
d! d!
• Virtual
T
Machine : 20483A-SEA-DEV11-07, MSL-TMG1
T
his his
do do
cum cu
me
• User
ma Name:
rt nt Student
b
e ma
rt nt
be
a.b elo a.b lon
No arb ng No arb gs
un o s st un os to
a @ oM a@ Ma
• Password:
auth
ori
Pa$$w0rd
pri
ma
art
aB
au
tho pri
ma rta
ze ve arb riz ve Ba
dc rab ed rab rbo
op s os co ss sa
ies s .co a. pie . .
sa com
all m llo
ow we
ed d!
!
Exercise 1: Creating an Entity Data Model from The School of Fine
Arts Database
Scenario
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/33
10/25/2019 20483A - Programming in C# | Skillpipe
In this exercise, you will use the Entity Data Model Wizard to generate an EDM from
the SchoolGradesDB SQL Server database and then review the model and the
code that the wizard generates.
Th Th
is is
do do
1. Build cu and generate an EDM
me
by using a table from
cu the SchoolGradesDB
m
ma nt ma en
rta rt tb
database
.ba be
lon a.b
arb
elo
ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
2. Review m
riz the generated
av Ba code riz av aB
ed era rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Task 1: Build and generate an EDM by using a table from the SchoolGradesDB
database
• Subjects
• Teachers
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/33
10/25/2019 20483A - Programming in C# | Skillpipe
• Users
7. If the Security Warning dialog box appears, click Do not show this message
again, and then click OK.
1. In the designer window, review the entities that the wizard generated.
Results: After completing this exercise, the prototype application should include
Th Th
is i
an EDM do that you can use to access The School sofdo Fine Arts database.
c um c um
ma en ma en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
un s st un os st
a @ oM a @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
Exercise 2: Updating Student and Grade Data by Using the Entity
co
pie bs
s.c
os
a. co
pie bs
s.c
os
a.
sa om sa om
Framework llo
we
d!
llo
we
d!
Scenario
In this exercise, you will add functionality to the prototype application to display the
Th for a user. The grade information in the database
grades Th stores the subject ID for a
is is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/33
10/25/2019 20483A - Programming in C# | Skillpipe
grade, so you will add code to the application to convert this to the subject name for
display purposes.
You will also add code to display the Add Grade view to the user and then use the
information that the user enters to add a grade for the current student.
Th Th
is is
d
Finally, you do grade display and grade-adding
o cu will run the application and verify that the cu
ma me m me
r n t a r nt
functionality
t a.b
a
works
belo as expected. t a.b
a
be
lon
No rbo ng N r b gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho m a t h o m rta
riz av Ba riz av Ba
The main tasks e d c for thise rab exercise rbo are as follows: e dc e rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
1. Display grades for the current student
3. Display the GradeDialog view and use the input to add a new grade
Th Th
is is
4. do the application and test the grade-addingdofunctionality
Runcu cu
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un sa to un a@ to
au @ Ma au Ma
tho pri rta tho pri rta
r m a Ba the riz m av Ba
Task 1: Display ize
d c grades
ve
rab for
rbo current student ed era rbo
op s sa co b s sa
ies s.c . pie s.c .
all om sa om
ow llo
ed we
! d!
1. In Visual Studio, from the E:\Labfiles\Starter\Exercise 2 folder, open the
GradesPrototype.sln solution.
7. Click Kevin Liu, and then verify that his grades appear in the list.
8. Note that the subject column uses the subject ID rather than the subject name,
and then close the application.
Th Th
is is
do d oc
cum um
ma nte ma
en
rta b a.b tb
rt
.ba elo elo
No rbo ng N arb ng
s o o st
Task 2:
un Display
au
sa
@ the to subject name in the UI
M un
au
sa
@ oM
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
1. In Visual Studio,owin l l
ed StudentProfile.xaml.cs, in the SubjectConverter class, in
l l ow
ed
! !
the Convert method, add code to the method to:
a. Convert the subject ID that is passed into the method into the subject
name.
2. ThReturn the subject name or, if there is no subject Th name matching the subject ID,
is is
do do
cu cu
mthe
art string
me
nt “N/A”. ma me
nt
a.b be rta be
a lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
Task 3: Display the GradeDialog l view and use the input to add l
l o we l o we a new grade
d! d!
4. Click Kevin Liu, and verify that the list of grades now displays the subject
name, not the subject ID.
Th his T
5. Add
is
do a new grade for Kevin Liu using the following
do information:
cu cu
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un sa to un a@ to
au @ Ma au Ma
tho pri rta tho pri rta
m m
• Subject: rGeography
ize
dc
av
e rab
Ba
rbo
riz
ed
av
era Ba
rbo
op s sa co b s sa
ies s .co . pie s.c .
all m sa om
llo
• Assessment: A+ owed we
d!
!
6. Verify that the new grade is added to the list, and then close the application.
Th Th
is is
do d oc
cum um
7. mIn
art Visual nt Studio, close the solution.
e ma
rt
en
tb
a.b be a.b elo
arb lon arb ng
No o gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co b s os
pie s.c . pie s.c a.
Results: After completing sa
llo
om this exercise, users will be see theagrades s
llo
o m for the
we we
current student and add d! new grades. d!
Then you will add validation code to check that a user enters a valid date and
assessment grade when adding a grade to a student.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/33
10/25/2019 20483A - Programming in C# | Skillpipe
Finally, you will run the application and verify that the data validation works as
expected.
1. Th
Throw the ClassFullException exception Th
is is
do oc d
c
um um
2. mAdd
art validation
e nt logic for the Assessment andm arAssessmentDate
en properties
a.b b t a.b tb
elo elo
No a rbo ng No a rbo ng
un sa st un sa st
@ oM @ oM
3. a
Runththe
u application
p a and test the validation logic a u p art
ori r i ma r taB t h ori r ima aB
ze ve arb zed vera arb
dc rab o co bs os
op s s sa p s a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
Task 1: Throw the ClassFullException exception
9. If the student who is passed to the method is not already enrolled in a class, set
the TeacherID property of the Student object to the UserID of the current
teacher.
Th Th
is is
do oc d
cum um
m
Task 2:
art Addntvalidation
e logic for the m
Assessment
a and en AssessmentDate
a.b be rta tb
l o . b elo
properties
No arbo n gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s s c o b s os
pie s.c a . pie s.c a.
1. Add a new class s all named o m customGrade.cs to the Grades.DataModel s all o m project.
ow ow
ed ed
! !
2. Modify the class declaration to make it a public partial class named Grade.
Th T
5. Inis
dthe
oc
ValidateAssessmentGrade method,hisadd
do code to:
um cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/33
10/25/2019 20483A - Programming in C# | Skillpipe
• Use a regular expression to check that the string passed to the method is in
the range of A+ to E-.
Th Th
is is
do oc d
c
m@"^[A-E][+-]?$"
um um
art e nt m art en
a.b b a.b tb
elo elo
No arb ng N arb ng
o sa s to o o sa st
6. Ifunthe
au string @
p
passed M a
is not in the valid range, uthrow
n au a @new
p
oM
art
tho rim rta tho rim aB
riz av B r i a
ArgumentOutOfRangeException
ed
co
era
bs
arb
o
exception. z ed
co
vera
bs
arb
os
pie s.c sa pie s.c a.
sa . sa
om om
llo llo
7. Otherwise, return we true. we
d! d!
TaskTh3:
i
Run the application and test the validation
Th
i
logic
sd sd
oc oc
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
1. Build
un the s a @
solution,t o M
and then resolve any compilation
u n s a @
errors.st
oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
2. Run the application. co
pie bs
s.c sa
.
co
p ies s s.co
os
a.
sa om a m
llo llo
we we
d! d!
3. Log on as vallee with a password of password99.
4. Attempt to enroll a new student into the class, and then verify that an error
message is displayed explaining that the class is already full.
• Subject: Math
• Assessment:
T F+ Th
his is
do d oc
cum um
ma e ma en
• Comments:
rta nt Well done!
be a rt tb
elo
.ba lon . ba
No rbo gs No rbo ng
un sa to un sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
6. Verify that ans error all message
om is displayed explaining that sathe assessment
om date
ow l l ow
ed ed
must be on or before ! the current date. !
• Date:
Th
is 8/19/2012
Th
is
do d oc
cum um
ma e nt ma en
rta
• Subject: rt tb
.ba Math
be
lo a.b
arb
elo
No rbo ng No ng
un sa st un os st
@ oM a @ oM
au pri a au p art
tho tho rim
• Assessment:riz F+av rta Ba
m riz av aB
arb
ed era rbo ed era
co bs sa co b s os
pie s.c . pie s.c a.
sa om sa om
• Comments: Well ldone! low
ed
llo
we
! d!
8. Verify that an error message is displayed explaining that the assessment grade
must be in the range A+ to E-.
Th Th
9. is
Modify the new grade date is
by using the following information:
do do
cu c um
ma m en ma en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
un s st un os st
a @ oM a @ oM
au pri art au pri art
tho m aB tho m aB
• Date: 8/19/2012 riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
• Subject: Math we
d!
we
d!
• Assessment: A+
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/33
10/25/2019 20483A - Programming in C# | Skillpipe
10. Verify that the new grade is added to the list, and then close the application.
Results: After completing this exercise, the application will raise and handle
Th Th
exceptions
is
d when invalid data is entered. is
d
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av
Module Review and Takeaways
ed
co
pie
era
b s s.c
rbo
sa
.
ed
co
pie
era
bs
s.c
arb
os
a.
sa om sa om
llo llo
we we
d! d!
Module Review
In this module, you learned how to create and use EDMs and how to query many
types of data by using LINQ.
Th Th
is is
do d
oc over traditional ways of
Question:
cu
me What advantages does LINQ provideum
ma n ma en
rta
querying t bdata? rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
Test Your Knowledge c op
ies
b s s.c
os
a. co
pie b s s.c
os
a.
all o m sa om
ow llo
ed we
! d!
Question
Fourth Coffee wants you to add custom functionality to an existing EDM in its Coffee Sales
application. You need to write a method for adding a new product to the
T
his his write your code? T
application.
d In which of the following locations should you d
oc oc
um um
ma e nt ma en
rta be a.brt tb
.ba lon elo
No r bo gs No a r bo ng
Select the
un correct s answer. t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
e
In the relevantdc e
generated
rab rclass
bo in the EDM project. e dc e rab
op s sa o s os
ies s .co . p ies s.co a.
all m all m
In a partial class in owthe EDM project. ow
ed ed
! !
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/33
10/25/2019 20483A - Programming in C# | Skillpipe
Contents:
Th Th
is is
do d oc
c um um
ma nt e ma
en
rta b a tb
rt
e elo
rbo Module Overview
.ba lon . ba
No gs No rbo ng
un sa to un sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
Lesson 1: rizeAccessing
dc
av
era Data
B arb Across the Web r ized
a vera arb
op bs o sa co bs os
ies s .co . p ies s .co a.
all m all m
Lesson 2: Accessing ow
ed Data in the Cloud
ow
ed
! !
Th Th
is is
do d oc
c um um
ma e ma en
Module
N
rta
.ba Overview
rb
be
lon
g
nt
No
rt
elo a.b
ng arb
tb
ou os st u o s st
na a @ o Ma na a @ oM
uth pri r t u t h p r i art
ori m av aB ori m av aB
ze era a rbo zed era arb
dc b c b os
Systems often consist opie of
s s
s.c many. components and services; some
a o pie might
s s.c be a. hosted
sa om sa om
llo llo
within your organization’s we
d! infrastructure, whereas others could be ehosted
w
d! in data
centers anywhere in the world. The ability for applications to be able to interact with
such services is a common requirement in modern applications.
In this module, you will learn how to use the request and response classes in the
Th
System.Net namespace to directly manipulate Tremote
his data sources. You will also
is
d oc d oc
u
me use Windows® Communication Foundation
me (WCF) Data Services to u
learnmhow
ar to nt ma
r nt
ta. be ta. be
arb on b l arb on b l
expose
No and
u oconsume
s
gs
t
an entity data model (EDM)
No over
u o the
s web.
gs
t
na a@ oM na a@ oM
uth pri art uth pri art
ori ma aB ori ma aB
ze ve arb ze ve arb
dc rab os dc rab os
op op
Objectives ies
all
s s .co
m
a. ies
all
s s.co
m
a.
ow ow
ed ed
! !
After completing this module, you will be able to:
• Send data to and receive data from web services and other remote data sources.
Data is often exposed over the web through web services or other application
programming interfaces (APIs). To be able to consume such data sources in your
application, you need a way to send and receive messages so that you can establish
Th Th
a connection
is
d and ultimately send and receive data.
is
d
oc oc
um um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
N r b ng N arb ng
In thiso ulesson,
na
os you swill
a@ to learn how to consume remote
o un data
o sa sources st
o M such as web
uth M au @
pri art tho p rim art
services and ori FilemTransfer
av a B Protocol (FTP) sites, which will
r i include
a how
a B to create a
ze era arb zed vera arb
dc bs o co bs os
op sa p a.
request, supply credentials ies
all
s .co for authentication, package data ieinto
m
. sa thes . c request,
om and
ow l l ow
process data that is returned ed in the response. ed
! !
Lesson Objectives
After completing this lesson, you will be able to:
Th Th
is is
do do
c
um cu
• Describe
ma ehow
n the Microsoft® .NET Framework ma uses me requests and responses.
nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
un sa to uncontracts. sa to
• Expose au types
tho
@ from
pri M web
art services by using data a uth @
pri Ma
rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
p s a p s sa
• Create a request i
all
s
es and cprocess. om
. a response. i es
all
s. co
m
.
ow ow
ed ed
! !
• Provide credentials or a security token to enable the remote data source to
perform authentication.
Th Th
is is
do d oc
cum um
ma e ma e
Overview of Web Connectivity in the
rta
.ba
rbo
nt
be
lon a.b .NET
ar
nt
be Framework
lon
rt
No gs No bo gs
un s a@ to un sa to
au Ma au @ Ma
tho pri rta tho pri rta
riz ma Ba riz ma Ba
ed ve rbo ed ve rbo
co rab co rab
pie ss sa pie ss sa
sa .c . sa . c .
om om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/50
10/25/2019 20483A - Programming in C# | Skillpipe
The .NET Framework provides the infrastructure to enable you to integrate your
applications with remote data sources. The remote data source could be anything
from an FTP site to an ASP.NET or WCF Web Service.
When consuming a remote data source in your application, the .NET Framework
uses requests and responses to pass messages between the two (or more) systems.
Th Th
sdi is
This involves
oc
u
the following steps: um
d oc
ma me ma en
rta nt rt tb
.ba belo a.b elo
No rbo ng N arb ng
un sa s to o un o sa st
2. Initiate a @ connection M to the remote data source. This @ might oM include passing a
au p a au p art
tho rim rta tho rim a
riz a Ba riz a Ba
security edtokenveor rab user rbcredentials so that the remote ed datavesource rab rbcan
co s os c o s os
pie s.c a. pie s.c a.
authenticate syou. all
ow
om sa
l l ow
om
ed ed
! !
3. Send a request message to the remote data source. This message may also
include any data that the remote data source requires to satisfy the request,
such as the identifier for the sales record you want to retrieve.
4. ThWait for the remote data source to processThyour request and issue a response.
is is
do do
As
ma
ac udeveloper,
m en
you have no control over how
ma
long
cu
me it might take to receive a
rta t r nt
befrom t a be
Noresponse
.ba
rbo
lon
gs
a web service. No
.ba
rbo
lon
gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
r m a aB o r m a
5. Process ize the response,
dc
ve
rab arb and extract any data that is izeincluded
d
ve in the
r ab
Ba response.
rbo
op s os co s sa
ies s.c a . pie s.c .
all om sa om
ow llo
ed we
! d!
Note: Not all communications have to include both a request and
response message. Depending on the nature of the application, it might
only be applicable to send one message. For example, if your
application wants to let a web service know that it has finished
processing a task, you only need to send a request. This is known as a
Th
is one-way operation. Th
is
do do
cum cu
ma e ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
au pri Ma au pri Ma
tho ma rta tho ma rta
riz ve Ba riz ve Ba
ed rab rbo ed rab rbo
co ss sa co ss sa
Web Connectivity in the .NET Framework
pie
sa .c om
. pie
sa . com
.
llo llo
we we
d! d!
The .NET Framework provides the System.Net namespace, which contains several
request and response classes that enable you to target different data sources. The
following table describes some of these request and response classes.
Th Th
Classis
d Description is
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/50
10/25/2019 20483A - Programming in C# | Skillpipe
Class Description
WebRequest An abstract class that provides the base infrastructure for any request to a
Uniform Resource Identifier (URI).
WebResponse An abstract class that provides the base infrastructure to process any
response from a URI.
Th Th
is is
do
HttpWebRequest A derivative of the WebRequestdoclass that provides functionality for any
cu cu
ma me ma me
rta n tb HTTP web request. rta n tb
.ba elo .ba elo
No rbo ng N r b ng
un sa s to o un o sa st
@ M @ oM
au
HttpWebResponse p a A derivative of the WebResponse au class that p provides art functionality to
tho rim rta tho rim aB
riz av B aprocess r iz a v arb
ed era rbo any HTTP web response. ed era
co bs sa co bs os
pie s.c . pie s.c a.
sa om sa om
FtpWebRequest l l ow A derivative of the WebRequest class that provides l l ow functionality for any
ed ed
! !
FTP request.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e en ma
rta b a.b tb rt
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
A remote au data source
tho
@
prim
M can
a rta
expose any type of data. auFor example,
tho
@
p rim aarta
web service can
riz av B arb r iz a v Ba
expose binary ed streams, era scalar e era
co b s os values, or custom objects.d The c o choice
b s
ofrbothe type of
sa
pie s.c a. pie s.c .
sa om sa om
data that you exposellowis determined by the requirements of yourlloapplication, we but how
ed d
! !
you expose it is controlled by the data contracts that you define in your web services.
If you want to expose a custom object from a web service, you must provide
metadata that describes the structure of the object. The serialization process uses
this metadata
Th to convert your object into a transportable
Th format, such as XML or
is is
d
oc Object Notation (JSON). This metadata oprovides d
JavaScript
um cu
m instructions to the
ma en ma en
ta. r be t ta. be r t
serializer
N
bathat enable
r
lon
g
you to control which typesN and bamembers
r
lon are serialized.
g
ou bo st ou st bo
na sa oM na oM sa
uth @ uth @
pri art pri art
ori m av aB ori m av aB
ze era arb ze era arb
Data Contracts in the .NET Framework
dc
op
ies
b s s.c
os
a.
dc
op
ies
b s s.c
os
a.
all o m all o m
ow ow
ed ed
The .NET Framework provides ! the System.Runtime.Serialization ! namespace,
which includes the DataContract and DataMember attributes. You can use these
attributes to define serializable types and members.
The following code example shows how to define a serializable type by using the
hisT Th
DataContract and DataMember attributes. is
do d oc
c um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
os st
Defining
un a Data
au
s a@ Contractto
Ma un
au a @ oM
tho pri rta tho pri art
riz ma Ba riz m av aB
ed ve rbo ed era arb
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
om om
llo llo
we we
[DataContract()] d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The protocol that your remote data source uses determines the request and
response classes you must use. Irrespective of the classes you use, you can apply
the same pattern to send a request and receive a response.
Th Th
is is
do do
ThemHttpWebRequest
um c and HttpWebResponse
m
cu
m Classes
arten art en
a.b tb a.b tb
elo elo
ar n a r ng
TheNfollowing
ou bo steps
s a@
gs describe how to send an HTTP
t oM
No
un
request
bo
s a
tos tao web service and
na a @ Ma
uth pri art uth pri rta
process the ori response
ze
ma
ve by a Busing the HttpWebRequest
a
oand
r ize
HttpWebResponse
ma
v Ba
dc rab rbo dc e rab rbo
op ss sa op ss sa
classes: ies .co . ies .co .
all m all m
ow ow
ed ed
! !
1. Get a URI to the web service to which you want to send a request. The
following code example shows an HTTP URI that addresses the
GetSalesPerson method in the Fourth Coffee Sales Service.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/50
10/25/2019 20483A - Programming in C# | Skillpipe
var uri =
"http://sales.fourthcoffee.com/SalesService.svc/GetSalesPerson"
;
2. Create a request object to configure the request and access the response. The
Th Th
is is
following
do
cu code example shows how to create dan
oc HttpWebRequest object.
u
ma me ma me
rta nt r nt
.ba belo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au request @ M @ Ma
var tho pri = artWebRequest.Create(uri) auas t h pri
HttpWebRequest; rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
llo llo
we we
d! d!
Note: Regardless of the type of request object you require, you always
use the static Create method that the WebRequest base class exposes
and then cast to the type of request you require.
Th Th
3. Get
is
do the response from the request object. The
is following code example
do shows
cu cu
mhow m enget the response from an HttpWebRequest ma me
art
a.b
to t be rta nt object.
be
a lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
e e arb ze ve rbo
var response d co rab= request.GetResponse()
os d
as HttpWebResponse;
co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
Th Th
is is
do do
c
um cu
4. mAccess and process the response by using me
art e n tb
m art various
the nt
be
members that the
a.b elo a . b l
arb ng arb ong
NoWebResponse os s t object provides. The following No code os example st shows how to use
un a @ o M u n a @ oM
au pri art a uth pri art
and thviewori
ze
the mastatus
ve
a Bof the response by using the orStatusCode
ize
ma
v
a property.
Ba
dc rab a rbo dc e rab rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
var status = response.StatusCode; ! // Returns OK if! a response
is received.
If the remote data source uses a different protocol, such as FTP, you can apply
Th Th
the
is same
do pattern but use the FtpWebRequest
is
d and FtpWebResponse classes
cu oc
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/50
10/25/2019 20483A - Programming in C# | Skillpipe
instead.
Similarly, if you try to access a secure web service with the wrong credentials or
security token, the GetResponse method call will throw a WebException exception
with the following message:
Th Th
is is
do d oc
c um u
me
WebException
ma
r nt – The remote server returned anmerror:
e ar 401
nt unauthorized
ta. be ta. be
ba lon ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
If you do not riz handle
ed
m av these
era
a B exceptions in your code, they
arb
ori will cause
ze
m a ve your
Ba application to
o d r a rbo
co b ss sa c op b ss sa
fail, offering a poor pie user
sa .cexperience.
om
. Therefore, as a minimum, ies you .cshould
om
. enclose
llo a llo
we we
any logic that communicates d! with a remote data source in a try/catch d! statement, with
the catch block handling exceptions of type WebException.
Remote data sources are often protected to prevent unauthorized users from using
the service and gaining access to data. Exposing an unprotected data source over
Th T
the web
is can lead to unauthorized users sending hrequests
d
is
d
and increasing the load on
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/50
10/25/2019 20483A - Programming in C# | Skillpipe
the data source. There are many ways in which you can secure remote data sources.
One approach is to authenticate each user who attempts to connect to the remote
data source.
Type of Authentication
The Tfollowing
his table describes some of the common
Th
is authentication techniques that
do do
um c cu
you can
ma use ento secure remote data sources. ma me
nt
rta tb rta be
.ba elo .ba lon
No rbo ng No rbo gs
un sa st un sa to
@ oM @ Ma
au p art au pri
tho rim aB tho m rta
riz av riz av Ba
Authentication ed
co
era arb
os
Description ed
co
era rbo
pie bs a. pie b s sa
s.c s.c .
mechanism sa
llo
om sa
llo
om
we we
d! d!
Basic Enables users to authenticate by using a user name and password.
Basic authentication does not encrypt the credentials while in transit,
which means that unauthorized users may access the credentials.
The nature of the service and where it is hosted are likely to influence an
organization’s choice of authentication mechanism. For example, a service that is
Th
exposed Th Windows authentication so that
is over an organization’s intranet might useis
d oc d oc
me u me Domain Services (AD DS) u
usersmacan
r
authenticate
nt by using their Active Directory®
ma
r nt
ta. be ta. be
arb on b l arb on b l
credentials.
No
u oUsing
s
gsWindows authentication in this
t
No scenario
u o s will
gs provide the users with
t
na a@ oM na a@ oM
an SSO uexperience
tho
riz
pri
v
art
ma and a not
B
uth
require them to remember pri
ori credentials
z
ma
v
art
afor
B each service
era ed arb ed era arb
co bs os co bs os
they consume. ies
p s .co a. pie
sa
s.c
o
a.
all m llo m
ow we
ed d
! !
The .NET Framework provides a number of classes that you can use to authenticate
with a secure remote data source.
When communicating with a remote data source that requires a user name and
password, you use the Credentials property that is exposed by any class that is
derived from the WebRequest base class to pass the credentials to the data source.
You can set the Credentials property to any object that implements the ICredentials
interface:
Th Th
is is
• d
The NetworkCredential
o do
class implements the ICredentials interface and enables
cu cu
ma me m me
n tb a n tb
you rto
ta. encapsulate
ba elo a user name and password.rtaThe .ba following elo code example
No rbo ng N r b ng
sa s to o o sa s to
shows
un how
au @to instantiate
pri Ma a NetworkCredentialunaobjectuth and
@
pri
pass Ma values for the
tho m r ta o m rta
riz av Ba ri av Ba
user name edand password
era rboto the class constructor. zed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
llo llo
we we
d! d!
var uri =
"http://Sales.FourthCoffee.com/SalesService.svc/GetSalesPerson";
var username = "jespera";
var password = "Pa$$w0rd";
Th
var T
is request = WebRequest.Create(uri) hias
s
HttpWebRequest;
do do
um c um c
request.Credentials
m en = new NetworkCredential(username,
m en password);
art t be a rta tb
a.b lon .ba elo
No arbo gs No rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
• ed
The CredentialCache era class
rbo provides a number of ed
members erthat
a enable you to get
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
credentials in the llform ow of an ICredentials object. These members llo
we include the
ed d!
!
DefaultCredentials property, which returns an ICredentials object containing the
credentials that the user is currently logged on with. The following code example
shows how to use the DefaultCredentials property to get the current user’s
credentials.
Th Th
is is
do oc d
c um um
var
ma uri en =
tb
ma en
tb
rta elo r ta. elo
.ba b a
No r n gs
"http://Sales.FourthCoffee.com/SalesService.svc/GetSalesPerson";
bo No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho
var request m = WebRequest.Create(uri)
a as HttpWebRequest;
o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs s co s os
request.Credentials p ies s .co a
= . CredentialCache.DefaultCredentials; p ies s.co a.
all m all m
ow ow
ed ed
! !
The following code example shows how you can create an HttpWebRequest object
and add an X509 certificate to the request object by using the ClientCertificates
property.
Th Th
is is
do do
HttpWebRequest
cu
m and x509 Certificates cu
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
e e arb ze ve rbo
var uri = co d rab os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
"http://Sales.FourthCoffee.com/SalesService.svc/GetSalesPerson";
llo
we
llo
we
d! d!
var certificate = FourthCoffeeCertificateServices.GetCertificate();
var request = WebRequest.Create(uri) as HttpWebRequest;
request.ClientCertificates.Add(certificate);
T T
Whenhisthec
his
do remote data source receives the request,do it must extract and process the
c
um um
X509mcertificate.
art
a.
en
e
ma
t b If the X509 certificate is invalid, the
.
en
rta remote
t b data source can return a
e
ba lon ba lon
No bo r gs No bo g r
suitable
un response,
sa such
to as a "The remote server ureturned
na sa an serror:
to 401
a uth @ M @ M uth
pri art pri art
ori ma aB ori ma aB
unauthorized" ze message.
d
ve
r arb ze
d
ve
r arb
co ab os co ab os
pie ss a. pie ss a.
sa .co sa .co
llo m llo m
we we
d! d!
Note: The GetCertificate method of the web service that is shown in the
previous example returns an X509Certficate2 object. This type provides
programmatic access to the properties of the X509 certificate.
Sending
Th
is
do and Receiving Data Th
is
d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b rt
a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
You useaurequests
tho prim and M responses
a rta to send data to or auretrieve
tho p data
rim from
art a remote data
riz av B r a aB
ed era arb ize vera arb
source. For example, co
pie byou
ss may os want to add a new recorddto
a co a web
p bs service os or retrieve
a.
.c . i e s . c
sa om sa om
a file from an FTP site. l l ow l l ow
ed ed
! !
• Method. This property enables you to set the type of method that the
WebRequest object will use to send the request. For example, if you are
Th Th
is i
uploading
doc
um
a file by using the FtpWebRequest sclass, do
cu you use the STOR method.
ma en ma me
rta tb r nt
.ba elo t a .ba be
ng This property enables you N lon
• ContentLength.
No
un
rbo
s a@
s t oM
too un
set the
r b o s number
a@
gs
to of bytes that the
au pri art a uth pri Ma
requestthowillriz send. ma
ve
aB
a
ori
z
ma
v
rta
Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
• GetRequestStream. llo
we This method enables you to access and llo write data to the
we
d! d!
underlying data stream in the request object.
1. Get the URI to the remote data source and the data you want to send.
Th Th
is is
do do
2. Create cu the request object.
me
cu
me
ma n m a nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r
3. Configure
un sa thes trequest
o object, which includeso u setting b os thegsrequestto method and the
au @ Ma na a @ Ma
tho pri r t uth pri r t
lengthrizof ma a B the request will send. ori ma aB
ed the datave
r a
that arb ze
d
ve
r a
arb
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
4. Stream the dataowto l l
ed the request object.
l l ow
ed
! !
The following code example shows how to use a POST operation to send a JSON
string to a web service by using the HttpWebRequest class.
Th Th
is is
do d oc
c
Sending
ma Data
um
en to a Web Service ma
um
en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
// Get the URI c op andss theosdata.
b a. co
pie b s s.c
os
a.
ies .co sa om
all m llo
var uri = ow we
ed d!
!
"http://sales.fourthcoffee.com/SalesService.svc/GetSalesPerson";
var rawData =
Encoding.Default.GetBytes("
{\"emailAddress\":\"jesper@fourthcoffee.com\"}");// Create
theThrequest object. Th
is is
do do
var mrequest u c = WebRequest.Create(uri) as cu
HttpWebRequest;
me m me
art n tb art nt
a.b elo a . be
// NConfigure
arb nthe type of data the request b awill lsend.
on
ou os g s N o r b o gs
na a@ t oM un s a@ to
uth
request.Method pri = art
"POST"; a uth pri Ma
ori ma aB ori ma rta
ze ve a ze ve Ba
dc rab rbo dc rab rbo
request.ContentType op ss = "application/json";
sa op ss sa
ies .co . ies .co .
all m all m
request.ContentLength o we = rawData.Length; o we
d! d!
// Stream the data to the request.
var dataStream = request.GetRequestStream();
dataStream.Write(rawData, 0, rawData.Length);
dataStream.Close();
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/50
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to upload a file to an FTP site by using the
FtpWebRequest class.
Th Th
sdi is
// Get octhe URI and the data. d oc
um um
ma e ma en
rta = nt be
var uri elo rt a.b tb
.b l
arb on arb
No g ngNo
un sa o st un st os
oM
"ftp://sales.fourthcoffee.com/FileRepository/SalesForcast.xls";
@ a @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
var rawData ed = era
o
ed era
os
co bs sa co bs a.
pie s.c . pie s.c
sa om
File.ReadAllBytes("C:\\FourthCoffee\\Documents\\SalesForecast.xls"); sa om
llo llo
we we
d! d!
// Create the request object.
var request = WebRequest.Create(uri) as FtpWebRequest;
// Configure the type of data the request will send.
request.Method = WebRequestMethods.Ftp.UploadFile;
request.ContentLength = rawData.Length;
Th Th
sd i is
// Stream
oc the data to the request. oc d
um um
ma ne m a en
rta
var dataStream t be = request.GetRequestStream(); rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa t u s st
dataStream.Write(rawData,
au @ o Ma 0, rawData.Length);
na a @ oM
tho p rim rta u tho p rim art
riz av B riz av aB
dataStream.Close();ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Additional Reading: For more information about LINQ to XML, see the LINQ
to XML page at http://go.microsoft.com/fwlink/?LinkID=267814.
Th Th
is is
do d oc
c um um
Demonstration:
ma
rta n t b
Consuming
e a Web
ma Service
rta
en
tb
.ba elo .ba elo
No rbo ng No rbo ng
u s s t u s st
na a
In this demonstration, @ o Mayou will use the HttpWebRequest na a and
@ oM
HttpWebResponse
uth pri r t u t h p r i art
ori m av aB ori m av aB
ze a z arb
classes to consume dc
op
eraa bweb rservice
bo
s
over HTTP. ed
c o
era
b os
ies s s.c a . pie s s.c a.
all o m s all o m
ow ow
ed ed
! !
The application will use the System.Net classes to get sales people records from the
Fourth Coffee Sale Service. You will send a request that will contain the email
address of the sale person record you want to get in the JSON format, process the
response, and then display the record details in the UI.
Th Th
is is
do d
Demonstration
m
um
e
Steps
c
ma
oc
um
en
art nt rt tb
a.b be a.b elo
arb lon arb ng
No o gs No osst
un s a@ to un a oM
Ma @
1. Startauth the 20483A-SEA-DEV11-08
ori
pri
ma rta virtual machine.
a uth
ori
pri
ma
art
aB
ze ve Ba ze ve arb
dc rab rbo dc rab os
op ss sa op s s a.
ies . . ies .co
2. Log on to Windows all
c o8m as Student with the password Pa$$w0rd. all m
ow ow
ed ed
! !
5. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.
13. Double-click the TODO: 01: Bring the System.Net namespace into scope. task.
14. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No using rbo System.Net;gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
15. In the Task List llowindow,
we
double-click the TODO: 02: Declare llo
we
a global object to
d! d!
encapsulate an HTTP request. task.
16. In the code editor, click in the blank line below the comment, and then type the
following code:
Th Th
is is
do d oc
HttpWebRequest
cu
me
_request; um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 16/50
10/25/2019 20483A - Programming in C# | Skillpipe
17. In the Task List window, double-click the TODO: 03: Instantiate the _request
object. task.
18. In the code editor, click in the blank line below the comment, and then type the
Thfollowing code: Th
is is
do do
cu cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
rbo
No this._request st N
= WebRequest.Create(o u r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m
this._serviceUri.AbsoluteUri)
av a Ba as o riz m av Ba
ed era rbo ed era rbo
co b s s a c o b s sa
p
HttpWebRequest;ies s .co . p ies s.co .
all m all m
ow ow
ed ed
! !
19. In the Task List window, double-click the TODO: 04: Configure the request to
send JSON data. task.
20. In the code editor, click in the blank line below the comment, and then type the
Th Th
is is
following
do
cu code: d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a ng
No rbo gs No rbo st
un sa t o u na s a oM
au @ Ma u @
tho p
this._request.Methodrim rta = "POST"; tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
c
this._request.ContentType
op b s s = "application/json"; c o b s os
ies s.c a . pie s.c a.
all o m s all o m
this._request.ContentLength ow = rawData.Length; owed
ed
! !
21. In the Task List window, double-click the TODO: 05: Write data to the request
stream. task.
T T
22. hInis dthe
o
his the comment, and then type the
code editor, click in the blank line below do
cu cu
mfollowing me m me
art
a.b
n t bcode: art
a
nt
be
elo . b lon
No arb ng N arb gs
un o s s t o un o s to
a@ oM a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
var dataStream e dc rab = rthis._request.GetRequestStream();
bo e dc e rab rbo
op ss sa op ss sa
ies .co . ies .co .
dataStream.Write(data, a llo m 0, data.Length); a llo m
we we
d! d!
dataStream.Close();
23. In the Task List window, double-click the TODO: 06: Create an
HttpWebResponse object. task.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/50
10/25/2019 20483A - Programming in C# | Skillpipe
24. In the code editor, click in the blank line below the comment, and then type the
following code:
if (response.ContentLength == 0)
return null;
Th Th
is is
do oc d
cum um
ma e m en
27. Inrtathe
.ba
Task
n t be List window, double-click the TODO: a rta
.ba
08: t bRead and process the
elo
lon ng
No rbo gs No rbo st
response
un
au
sa data.
@ t o task.
Ma u na s a @ oM
tho p rim rta u tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
28. c
In the codeopieditor, ss click sin the blank line below the c
comment, and os
then
es
b
.co a . o pie b s s.c a. type the
all m s all o m
following code: owed ow
ed
! !
32. In the Fourth Coffee Contract Finder application, in the Search box, type
jesper@fourthcoffee.com, and then click GO.
Th Th
is sd i
33. In dthe
oc Search
um
Successful dialog box, click OK.oc
u
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/50
10/25/2019 20483A - Programming in C# | Skillpipe
34. Verify that the details for Jesper Herp are displayed.
Th Th
is is
do d oc
cum u
Lesson
rta
.b
2:
ma
nt
b Accessing
elo
e
Data in the Cloud
a.b
me
nt
be
lo
ma
rt
No arb ng No arb ng
un os st u os st
a @ o M n a @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
WCF Data Services co
pie
follows
bs
s.c
the
o sa Representational State Transfer co
pie
(REST)
bs
s.c
os architectural
a.
sa . sa
om om
model and uses openowweb l l
ed
standards such as the Open Data Protocol l l ow
ed
(OData) to
! !
expose and consume data over the web. By following these standards, you can build
solutions based on WCF Data Services that a wide variety of client applications can
easily access, regardless of the technology that is used to implement the client
application.
Th Th
is is
do do
In this lesson,
u c you will learn how to create a WCF Data cu Service and how to define
ma m en ma me
rta t r nt
.ba belo t a .ba will be
whichNo entitiesrbo and n gsoperations you want to expose.
No You rbo
lalso
on
gs learn how to create a
un sa t o u na s a to
@ @
au
client librarytho and pri howMto art consume the entities and operations uth pri that Mayou have exposed.
rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
Lesson Objectives we
d!
we
d!
his T Th
• Definedo a WCF Data Service.
is
d oc
cu um
ma me ma en
rta nt rt tb
. be a.b elo
• Expose
No
b ar a
bo data l on model
gs by using a WCF Data Service.
No a r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
• Expose web riz av B riz av
ed methods era byarb using a WCF Data Service. ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
• Create a client library we and reference a WCF Data Service.
d!
we
d!
What
Th Is WCF Data Services?
i
Th
is
sd d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
WCF Data au Services
tho prim enables
M a rta you to create and accessau
tho data p services
rim art over the web.
riz av B r a aB
ed era arb ized vera arb
You expose your co data
pie
as
bs resources
o sa that applications can access
co
pie bs using
by os a URI.
a.
s.c . s.c
sa om sa om
These resources areowexposed as sets of entities that are relatedowby associations, the
l l l l
ed ed
! !
same concepts as in an EDM. However, you can expose data from many types of
storage, including databases and Common Language Runtime (CLR) classes.
WCF Data Services uses URIs to address data and simple, well-known formats to
represent
Th that data, such as XML and Atom. This
Th results in data being served as a
is is
oc d d oc
REST-style
m
um resource collection.
e ma en
um
art nt rt tb
a.b be a.b elo
a l on a ng
No rbo gs No rbo st
un sa t o u na s a oM
au become @ Mpopular @
REST has tho p rim a a rta model for implementing u tho web pservices
rim art that need to
aB
riz av B a riz av arb
ed era rbo ed era
access data (other c op models, b s s.c such
s a .
as those based on the c o pie b s s.c
os
a.
ies o s o
all m all m
WebRequest/WebResponse ow
ed model described in the previous lesson, ow
ed are more
! !
suited to invoking remote methods). REST describes a stateless, hierarchical
scheme for representing resources and business objects over a network. Resources
are accessed through URIs that identify the data to retrieve. For example, Fourth
Coffee might choose to make the data for all of its sales people available through the
following
Th URI: Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
. elo
http://FourthCoffee.com/SalesService.svc/SalesPersons
No
b ar bo
l on gs No a r bo ng
st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
ab oidentifier
The data for a cspecific op
ies
bssales sperson
s .co a . could be fetched by specifying
co
p ies s s the
.co
sa
.
all m all m
(such as a sales person o we number) for that sales person, like this: we o
d! d!
http://FourthCoffee.com/SalesService.svc/SalesPersons/99
Similarly, the details of products that it sells might be available through the following
URI:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/50
10/25/2019 20483A - Programming in C# | Skillpipe
http://FourthCoffee.com/SalesService.svc/Products
The details for a specific product could be retrieved by including the product ID in the
URI:
http://FourthCoffee.com/SalesService.svc/Products/25
T T
his his
do do
cum cu
ma e m me
rta n tb a r nt
.ba elo t a.b be
lonto expose data
No Note: rboThe exact ng
st URI scheme that a web service
N ou
a r b uses
os gs is a
un sa o n a to
decision @ of @
au
tho pri the organization
M art that implements athe
uth webprservice, i
Ma but the
rta
riz m av a Ba o riz m av Ba
examples e d c that rare
e ab shown rbo
s
here illustrate a commondpattern. e
c
e rab rbo
sa
op s s a . o p s s .
ies .co ies .co
all m all m
ow ow
ed ed
! !
The REST model performs HTTP GET queries to retrieve data, but the REST model
also supports insert, update, and delete operations by using HTTP PUT, POST, and
DELETE requests.
Th Th
is
The REST is URIs to support filtering, sorting,
do model enables a web service to extend do
c um c um
ma e ma en
and paging
rta
.ba
of
nt
bdata.
elo For example, the following URI rta sends
.ba
t b a request that fetches
elo the
No rbo n gs No rbo ng
first 10unsales sapeopleto only: u s st
@ Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s s c o b s os
pie s.c a . pie s.c a.
http://FourthCoffee.com/SalesService.svc/SalesPersons?top=10
s all o m s all o m
ow ow
ed ed
! !
The list of filters and other functionality depends on how the web service is
implemented, but features such as these are available with WCF Data Services.
Additionally, WCF Data Services enables you to extend your web services by writing
service operations as methods that perform business logic at the server. These
Th Th
is i
methodsocare
d
um
then accessible as URIs in a similar smanner do
cu to resources. You can also
ma en ma me
n
define rinterceptors,
ta.
ba
tb
elo which are called when you query, rta
.ba insert,
tb
elo update, or delete data
No r bo n gs No r bo ng
and canun validate sa or tmodify
o the data, enforce security,
u n or sarejects tthe o M change.
au @ Ma au @
tho pri rta tho pri art
riz m av Ba riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
pie s.c . p ies s s a.
sa om .co
llo a llo m
Additional Reading: we For more information about WCF Data we Services, see the
d! d!
WCF Data Services page at http://go.microsoft.com/fwlink/?
LinkID=267815.
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
By usingautWCF
ho
Data
prim Services,
M a rta you can expose data aufrom relational
tho p rim art data sources such
riz av B r a aB
arb iz v arb
as Microsoft eSQL dc
op
era
Server®bs through
o sa an EDM conceptual ed
schema
co
p
era
that
bs is created
os
a.
by
ies s .co . ies s.co
m m
using the ADO.NETallEntity ow Framework, and you can enable a client all
ow application to
ed ed
! !
query and maintain data by using this schema.
Note: WCF Data Services can also expose non-relational data, but this
requires building customized classes. WCF Data Services operates most
T naturally with the model that the ADO.NET
his T Entity Framework presents.his
do do
cum cu
ma e ma me
rta nt rt nt
.ba belo a .ba be
n lon
No rbo gs No rbo gs
A WCF un DatasaService
au @ to is based on the System.Data.Services.DataService
M un
a
sa
@ to
Ma generic
tho pri art uth pri r t
m aB ori m aB
class. This rclass
ize av
d c expects era aarbtype
o
parameter that is a collection
ze
dc
avcontaining
era arb at least one
os
op b s s a o pie b s a.
ies s.c . s.c
property that implements all othe
m IQueryable interface, such as the s all DbContext o m class for
ow ow
ed ed
an entity set that is defined ! by using the Entity Framework. The !
DataService type implements the basic functionality to expose the entities in this
collection as a series of REST resources.
Th Th
is is
d
The following do WCF Data Service based on a
um code example shows the definition of a
oc cu
ma en ma me
rta tb r nt
DbContext .ba classelo called FourthCoffee that is generatedt a .ba by be using the ADO.NET Entity
lon
No rbo ng No rbo gs
s s t s to
Framework.
un
au a@
pri
oM
art
un
a uth
a@
pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
Defining a Data Service llo
we
llo
we
d! d!
You can implement methods in a WCF Data Service that specify the entities to
expose from the underlying EDM and that configure the size of datasets that the data
service presents. You can also override methods that are inherited from the
DataService class to customize the way in which the service operates.
Th Th
is is
do d oc
um c um
By default,
ma WCF
en
t
Data Services uses a simple addressing
ma en scheme that exposes the
t
rta be rta be
.b on l on l .b
No setsarthat
entity bo are gs defined within the specified N
EDM.
o
aWhen
rbo you
gs consume a WCF
un s a t o s t
u na a oM
au @ Ma uth @
pri pri art
Data Service,
t h ori you
ze
maaddress
ve
r ta B these entity resources as an ori entity
z
ma set that
v
a B contains
dc rab arb ed era arb
o sa example, suppose that thecofollowing bs URI os
instances of an oentity pie
sa
type.
ss
.c om
For . p i e sa
s . com
a(shown
. in
llo llo
the previous topic) returns we
d! all of the SalesPerson entities that were
we defined in the
d!
EDM that was used to construct a WCF Data Service:
http://FourthCoffee.com/SalesService.svc/SalesPersons
The T"/SalesPersons"
his
d element of the URI points Tto
his the SalesPersons entity set, which
d
oc oc
me u um
is themacontainer
rt nt for SalesPerson instances.
b
ma
rt
en
tb
a.b elo a.b elo
No arbo n gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B riz av
Additional ed
co
Reading:
era
b
a rbFor
o
more information about edefining dc eraa WCF
b
arb Data
os
pie s s.c s a o pie s s.c a.
Service, see s the Exposing . Your Data as a Service (WCF s Data Services)
all o m all o m
ow ow
page at http://go.microsoft.com/fwlink/?LinkID=267816.
ed
!
ed
!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
For security reasons, WCF Data Services does not automatically expose any
resources, such as entity collections, that the EDM implements. You specify a policy
that Tenables
h
or disables access to resources in Tthe
h
InitializeService method of your
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/50
10/25/2019 20483A - Programming in C# | Skillpipe
The following code example shows how to allow access to all resources that the
WCF Data Service exposes.
Th Th
is is
d
Data Service
o Access to all Entities do
cu cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m av Ba
public class ed era
FourthCoffeeDataService
rbo : ed
DataService<FourthCoffee> era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
{ s a o m s a o m
llo llo
we we
d! d!
public static void InitializeService(DataServiceConfiguration
config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
}
Th Th
is is
} do d oc
cum um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim
The parameters riz
ed
to avthe SetEntitySetAccessRule
era B a method riz areavthe name
ed era
aB
arb of a resource
rbo os
co b sa c b
and the access rights pie ss
s a to.cgrant .over that resource. You can ospecify pie
sa
ss a.
a.coresource
om m
llo llo
we we
explicitly, or you can use d! wildcard characters. The * value that is shown d! in the code
example is a shorthand way of specifying all resources that the WCF Data Service
publishes. The EntitySetRights.All value grants unrestricted access to these
resources.
Th Th
is i
Note:
doc
um
Enumerations and partial classes thats dare oc implemented in an EDM do
um
ma en ma en
not
rta propagate
.ba
tb
elo
through WCF Data Services. If
r ta. you want
tb
elo
to expose
n b a n
r
No enumerations gs and extensions to partial classes, r byou
os should to include these
bo No gs
un sa to un a@
au @ M a uth Ma
types tho in apseparate
rim art assembly that you can reference
aB ori
pin
rim the service rta and client
riz av arb ze a ve Ba
ed era d r rb
application co directly.
pie bs
s.c
os
a. co
pie
ab
ss os
a.
sa om sa .co
llo llo m
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
The primary purpose sa of a WCF
om Data Service is to provide accesssa to data.
om However,
llo llo
we we
you can also implementd!custom operations that manipulate data. Ad! WCF Data
Service operation is simply a method of the data service that is visible to the REST
infrastructure and that can be accessed by sending an HTTP GET, PUT, POST, or
DELETE request.
Th Th
is i
do Services operations that are accesseds by
WCF Data do using a GET request should be
c um c um
ma e ma en
annotated
rta withbethe WebGet attribute. These operations
.ba
n t rta
.ba
typically
tb
elo return data, although
lon ng
No rbo gs No rbo s t Operations that are
they may
un runsasome
au @ tobusiness logic that does not return
Ma un
au
asa@value. oM
tho prim rta tho p rim art
aB
accessed by riz usingavPUT, POST,
ed era B a rbo or DELETE requests should
riz
ed be
av annotated
era arb with the
co b s s c o b s os
pie s.c a . pie s.c a .
WebInvoke attribute. s a These
llo
om operations typically modify the data s a that
llo
omthe service uses
we we
in some way. d! d!
Similar to entity sets, you must explicitly enable access to operations that a WCF
Data Service exposes. You can do this by calling the
SetServiceOperationAccessRule method of the DataServiceConfiguration object
Th Th
when iyouoc
is
s d initialize the service. You specify the namedo of the operation and the
c
um um
ma en ma en
appropriate
r ta.
ba
access
tb
elo rights. rt a.b elo
tb
No r bo ng No arb ng
un sa s to un os st
@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz B riz a
A data service ed operation
co
ve
rab can
arb take
os
parameters and returns ed oneveof
co r ab the afollowing
rbo data
pie ss a. pie ss sa
.co . c .
types: s all
ow
m sa
llo
om
ed we
! d!
code to generate this collection, possibly based on information that the client applicat
The following code example shows an operation that retrieves sales people per area
• T (where T represents an entity type in the service). An operation can return a single
an entity. The following code example shows an operation that retrieves a sales pers
has a specific email address. Notice that you should also annotate an operation that
Th value with the SingleResult attribute.
scalar Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th ... Th
is is
do oc d
cum config.SetServiceOperationAccessRule("SalesPersonByEmail",
um
ma en ma en
rta tb rta tb
.ba elo ServiceOperationRights.ReadMultiple); .ba elo
No rbo ng N r b ng
un sa s to o un o sa st
@ M @ oM
}auth pri art au
t h p r art
ori ma aB ori ima aB
ze ve arb zed vera arb
... d co rab
ss o sa co bs os
pie . . p i e s . a.
s c om sa com
[WebGet] allow llo
we
ed d!
!
[SingleResult]
public SalesPerson SalesPersonByEmail(string emailAddress)
{
return (from p in this.CurrentDataSource.SalesPerson
Th where String.Equals(p.Area,
T area)
is his
do do
cum select p).SingleOrDefault();
cu
m
ma nt e ma en
rta be rt a.b tb
}.ba lon elo
No rbo gs No arb ng
sa to os st
} unaut @
pri Ma
rta
un
au
tho
a @
p rim
oM
art
ho m aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
• A primitive value. The dfollowing ! code example shows an operation d! that retrieves a co
the sales people and returns the count value as an int.
Referencing
Th
is a WCF Data Source Th
is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The DataServiceContext class performs a similar role to the DbContext class in the
Entity
T Framework. A client application connectsTto the data source through a
his his
do do
DataServiceContext
cu
m object and fetches the data for cuthe entities that the data service
m
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/50
10/25/2019 20483A - Programming in C# | Skillpipe
The client library also provides definitions of the types that each DataServiceQuery
collection contains. A client application can perform LINQ queries against the
Th Th
sd i i
DataServiceQuery
oc
u
collection properties, and the sclient
do
cu library constructs the
ma me ma me
nt nt
appropriate
r t a.b HTTP belo request to fetch the corresponding r t a.b data. be The WCF Data Service
lon
No arbo ng N a r b gs
s st ou os to collection. The
fetchesnathe
u
uth
matching
a @
pri
o data
M art
and populates the DataServiceQuery
na
uth
a @
pri Ma
ori ma aB ori ma rta
Ba
client application ze
dc canve thenaiterate
rab rbo through this collection zeand retrieve
dc
ve
rab the
rbo data for
op s s s a o p s s sa
ies .co . ies .co .
each item. all
ow
m all
ow
m
ed ed
! !
You can generate the client library for a WCF Data Service by using the Add Service
Reference dialog box in Visual Studio or by using the WCF Data Service client utility,
DataSvcUtil, from the command line.
Th Th
is is
do d
Adding uam Service Reference
c um
oc
ma en ma en
rta t be a.b rt tb
.ba lon elo
a ng application. This
You Ncan
o u use rbo the Add
s a
gs
t o
Service Reference dialog
No box in
u
rbo a client
s a
st
oM
na @ Ma na @
uth pri r u t p r art
dialog box oenables
riz m avyou to
ta B specify the URL of the WCF
a
h ori Data Service
z
imav a Bto connect to.
arb
ed era rbo ed era
co b s s c o b s os
The dialog box sends pie
s a a .metadata
sc
om
a . query to the specified URL, pie and sit
sa .cousesa.the
llo llo m
response to generatewthe ed appropriate DataServiceContext classwethat
! d! contains the
DataServiceQuery properties and the classes for each of the entities that the WCF
Data Service exposes. The returned metadata is stored in the client project as an
.edmx file. This is not the same as an .edmx file that is generated by using the
ADO.NET Entity Data Model Designer (it has a different format), but you can view
Th
this metadata Th text editor.
file by using the XML editor or any
is is
d oc d oc
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
r a r ng
To add
No a data
un
bo service
s a
gs
t o
reference, perform the following
No
u
bosteps:
s a
st
oM
au @ M n a @
tho pri art uth pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
p s p s s a.
1. If the data service ies
all
is
.co not part
m
. of the solution and is not already
ies
all
.crunning,
o m start the
ow ow
data service and enote d! its URI. ed
!
2. In Solution Explorer, right-click the client project, and then select Add Service
Reference.
4. Alternatively, if the data service is not part of the current solution, in the
Address box, type the base URL of the data service, and then click Go.
5. Click OK.
After you have referenced the WCF Data Service, you can then consume the
Th
entities and service operations that it exposes.
T
is his
do do
cum cu
ma e m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
Additional
tho pri Reading:
m
art
a For more information about t h o creating
pri
m a rservice
ta reference
riz av Ba riz av Ba
by usingd cthee e e e
op command
bo line, see the WCF Data Service
op Client Utility
rab r dc rab rbo
ss sa ss sa
ies .co . ies .co .
(DataSvcUtil.exe) all
ow
page
m at http://go.microsoft.com/fwlink/?LinkID=267819. all
ow
m
ed ed
! !
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
After you have referenced the WCF Data Service by generating a client library, you
can then consume the EDM and any service operations that the service exposes.
Th Th
Retrieving
is
do Data is
d oc
cu um
ma me ma en
rta nt rt tb
To retrieve .ba data be from a WCF Data Service by usinga.bthe
ar client
lon elo library, perform the
No rbo gs No n bo gs
un s a@ to un sa to
following au steps:
tho pri Ma
rta
au
tho pri
@ Ma
rta
riz ma Ba riz ma Ba
ed ve rbo ed ve rbo
co rab co rab
pie ss sa pie ss sa
sa .c . sa . c .
om om
1. Create an instance llo
we of the type that is derived from the DataServiceContext
llo
we
d! d!
class in the client library, and then connect to the WCF Data Service. The
constructor for this class expects a Uri object that contains the address of the
service.
the client library constructs an HTTP request that specifies the resource and
any criteria that is required. The query is transmitted to the WCF Data Service,
and the data is returned and used to populate the DataServiceQuery object.
3. Iterate through the items in the DataServiceQuery collection and process the
objects that are returned.
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
TheNfollowing r b code N arb
ng example connects to the FourthCoffeeDataService ng WCF Data
ou os st o un o sa st
na a@ oM @ oM
uth pri art au pri art
Service by ousing
riz mthe
av FourthCoffeeEntities
aB type in the tho client
r iz
malibrary
v
a (this
Ba is the class
ed era arb ed era rbo
o
that is derived cfrom op bs
s.c
om
sa
ies DataServiceContext). . The parametercoto pie the bconstructor
sa
ss
.co
sa
. is the
all l l m
ow ow
address of the service. edThe code then queries the SalesPersons
!
eDataServiceQuery
d!
property to fetch all sales people and reads the email address for each record.
Th Th
is is
do do
um c cu
FourthCoffeeEntities
ma en context = new FourthCoffeeEntities
ma me (new Uri
rta t r nt
.ba belo t a .ba be
ng l on
rbo
No ("http://FourthCoffee.com/FourthCoffeeDataService.svc"));
st No rbo gs
un sa o u na s a to
au @ M uth @ Ma
pri art pri
foreachtho(SalesPerson
riz m av aB person in context.SalesPersons)ori m a
rta
Ba
ed era arb ze ve rbo
co b os d co r ab
{ pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we
var email = product.EmailAddress; we
d! d!
}
You can also modify data by invoking any custom service operations that you may
haveT exposed in the WCF Data Service. You can
T invoke service operations by using
his his
do do
the Execute c um method of the DataServiceContext class. cu
me The value that the Execute
ma en ma nt
rta tb r ta. beoperation returns a single,
method returns
.ba
rbo
elis
ong an enumerable collection. If the service
b arb lon
No s No o gs
s t s to
scalaruvalue,
na
uth
a@
youpri shouldoM
art extract that value from un
the a collection
uth
a@
pri byMusing art a method
ori ma aB ori ma aB
ze ve arb ze ve arb
such as First. dc
op
rab
s os
a
dc
o
rab
s os
a.
ies s .co . p ies s.co
all m all m
ow ow
ed ed
! !
The following code example shows how to invoke the SalesPersonByArea service
operation and iterate the results.
Modifying Data
After you have retrieved data, you can modify the entities as you would when working
with Tan
his EDM and then save your changes backTto
his the WCF Data Service.
do do
cum cu
ma e ma me
rta nt rt nt
.ba belo a .ba be
lon
TheNDataServiceContext
ou r bos
n g st class provides the following
N o r b methods
o gs that enable you to
na a@ oM un sa to
a @ Ma
work withuththe
ori
pri
entities
m a
art your EDM.
in aB
uth
ori
pri
m a
rta
Ba
ze ve arb ze ve rbo
dc rab os d co r ab
op s s.c a pie s s.c sa
ies . sa .
all om om
ow llo
• AddToXXXX. Theseed!methods enable you to add a new entity wto ed the entity
!
collection. The following code example shows how to use the
AddToSalesPersons method to add a new SalesPerson entity.
FirstName = "Roy",
Surname = "Antebi"
};
context.AddToSalesPersons(newSalesPerson);
Th Th
is is
do
context.SaveChanges(); d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/50
10/25/2019 20483A - Programming in C# | Skillpipe
• DeleteObject. This method enables you to remove an existing object from the
entity collection. The following code example shows how to use the DeleteObject
method to delete a sales person with the email address roya@fourthcoffee.com.
Th Th
is
FourthCoffeeEntities is
context = new FourthCoffeeEntities (new Uri
do do
c um c um
ma en ma en
rta ("http://FourthCoffee.com/FourthCoffeeDataService.svc"));
tb
elo r t a.b tb
elo
.ba arb
No rbo ng N ng
...un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz
var salesPerson av = B(from
arb p in context.SalesPersons r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om where sa om
llo llo
we we
d!
p.EmailAddress.Equals("roy@fourthcoffee.com") d!
select p).Single();
context.DeleteObject(salesPerson);
context.SaveChanges();
Th Th
is is
do do
c
um cu
• UpdateObject.
ma en This method enables you to update
ma mean existing object in the entity
rta t r nt
.ba belo t a .ba be
n lon
collection.
No
un
rbo The gfollowing
sa s to
code example showsN o how
un
r to
b o sause gthe
s t UpdateObject
@ M @ oM
au pri art a uth pri art
method otot
riz change av the a Barea to which a sales personor belongs.
h m m aB
a iz av arb
ed era rbo ed era
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
FourthCoffeeEntities context = new FourthCoffeeEntities (new Uri
("http://FourthCoffee.com/FourthCoffeeDataService.svc"));
...
var salesPerson = (from p in context.SalesPersons
where
Th Th
is is
d
p.EmailAddress.Equals("roy@fourthcoffee.com")
oc do
um cu
ma en ma me
rta tb r nt
.ba elo select p).Single(); t a .ba be
lon
No rbo ng No rbo gs
un s s t un s to
salesperson.Area a@ oM = "soft drinks"; a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
context.UpdateObject(salesPerson);
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
context.SaveChanges(); sa om sa om
llo llo
we we
d! d!
When retrieving data by using WCF Data Services, by default only the entity you
requested is returned in the response. For example, the SalesPerson entity in the
FourthCoffeeEntities object is related to the Sales entity. When you request a
SalesPerson entity, the response will not include the related Sales entity. However,
you can use the Expand or LoadProperty methods to get related entities.
Th Th
i i
Using sthe
do eager loading strategy that the Expands method
cu
do
cu implements causes the
ma me ma me
nt nt
data forathe
r t .ba specifiedbelo related entities to be retrieveda.bas part
r t be of the same request that
lon
No rbo ng N a r b gs
s st ou os tif
fetchesnathe
u
uth
primary
a @
pri
data
o M art
for the query. This approachna is useful
uth
a @
pri
o Myou know that you
art
ori ma aB ori ma aB
will always need z ed
co
this
v erarelated
bs
arb data, but it can be wastefuleof
o
z
d co
bandwidth
v era
bs
arfor
bo the cases
pie s.c sa pie s.c sa
. .
where you do not actually sa
llo
omuse these entities. sa
llo
om
we we
d! d!
The following code example shows how to use the Expand method to fetch the sales
associated with each SalesPerson object.
Eager
T
Loading of Entities Th
his is
do d oc
cum um
ma ent ma en
rta be rta.b tb
.ba lon elo
No rbo gs No a rbo ng
u s t u s st
na
FourthCoffeeEntities a @ o Ma na
context = new FourthCoffeeEntities a @ oM (new Uri
uth pri r t u t h p r i art
ori m a aB ori ma aB
ze ve arb
("http://FourthCoffee.com/FourthCoffeeDataService.svc")); ze ve arb
dc rab os dc rab os
op s s.c a . o pie s s.c a.
ies o s o
var salesPersons all = (from m s in context.SalesPersons.Expand("Sales") all m
ow ow
ed ed
! !
select s).ToList();
As an alternative, you can use explicit loading. This strategy sends an additional
query to the WCF Data Service that is requesting the related data for a specific
T
his but it has the advantage that it does not waste
his T
object, do do bandwidth by automatically
cu cu
m me m me
fetching
art data tthat
a.b
n
be
is not used. art
a
nt
be
arb l o . b arb lon
No ng N gs
un o s s t o un o s to
a@ oM a@ Ma
au pri art a uth pri
tho ma a B loading by using the LoadProperty ori ma rta
You can implementriz
ed veexplicit
rab a rbo ze dc
v e method
rab
Ba of the
rbo
co ss sa op ss sa
pie . .
DataServiceContext s a object. .c om You call the LoadProperty method i e s a each . com time you
llo llo
we we
require data that is related d! to a particular entity; you specify the entity d! and the name
The following code example shows how to use the LoadProperty method to fetch
the sales that are associated with each SalesPerson object.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/50
10/25/2019 20483A - Programming in C# | Skillpipe
}
}
Th Th
is
Additional Reading: For more information isabout modifying entities, see the
do do
cu cu
mHow m me
art to:
en Add, Modify, and Delete Entities
t be
ma(WCF
rta ntData Services) page at
be
a.b l . b lon
on
No http://go.microsoft.com/fwlink/?LinkID=267820.
arb
o g s N o
arb
o gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
Demonstration: Retrieving and Modifying Grade Data in the
llo
we
d!
llo
we
d!
Cloud Lab
In this demonstration, you will learn about the tasks that you will perform in the lab for
this module.
Th Th
is is
Lab:
ma
Retrieving
um
en
and
do
Modifying
c Grade
ma
do
cu
me
n
Data in the Cloud
rta tb rta tb
.ba elo .ba elo
No r bo ng No rbong
un s st un sa st
a @ oM @ oM
au pri art au pri art
tho tho
Scenario riz
ed
m av
era
aB
arb riz
ed
m av
era
aB
arb
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
Currently, the application llo
we retrieves data from a local database. However, llo
we you have
d! d!
decided to store the data in the cloud and must configure the application so that it
can retrieve data across the web.
You must create a WCF Data Service for the SchoolGrades database that will be
integrated
Th into the application to enable access Tto
h
the data.
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 35/50
10/25/2019 20483A - Programming in C# | Skillpipe
Finally, you have been asked to write code that displays student images by retrieving
them from across the web.
Objectives
After completing this lab, you will be able to:
Th Th
is is
do d oc
um c um
• Create
ma
rta
a eWCF
nt Data Service. ma
rt
en
tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
• Use aautWCF @ Data Service.
Ma au @
ho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
• Retrieve data over s a theoweb. m sa om
llo llo
we we
d! d!
Scenario
Th Th
is is
do oc d
In this
m
exercise,
um you will create a WCF Data Service
c
m
for
um the SchoolGrades database
ar en ar en
ta. be t ta. be t
so that
N
theba client
rb
lonapplication can connect to the database
g N
ba
rb over
lon the web.
g
ou os st ou os st
na a@ oM na a@ oM
uth pri art uth pri art
ori ma aB ori ma aB
ze ve arb ze ve arb
First, you will add d co a new rab ASP.NET os Web Application d r
projectcopto theabssolution os and
pie ss a. ies s a.
sa .co .co
llo m all m
configure it for the client we application. ow
ed
d! !
You will then expose the entities in the EDM from a data service in the new project.
Next, you will specify the data context for the data service and configure access
rights
Th to the entities that it exposes.
is
Th
is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/50
10/25/2019 20483A - Programming in C# | Skillpipe
You will then add an operation to the data service that returns all of the students in a
specified class.
Finally, you will test the WCF Data Service to ensure that it functions correctly.
Th Th
is is
do do
u c cu
Taskm1:
art
Create
m en the Grades.Web project ma me
nt
a.b t be rta be
a lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
r m a aB o r m a
1. Start the ize MSL-TMG1
dc
ve
rab arvirtual
bo machine if it is not already ize
d c running.
ve
rab
Ba
rbo
op s s.c s a o pie s s.c sa
ies . sa .
all om om
ow llo
2. Start the 20483A-SEA-DEV11-08 ed
!
virtual machine and log on we as Student
d! with
the password Pa$$w0rd.
3. Start Visual Studio, and then open the GradesPrototype.sln solution from the
E:\Labfiles\Starter\Exercise 1 folder.
Th Th
4. Add
is
do a Visual C# ASP.NET Empty Web Application
is
d project called Grades.Web to
cu oc
me um
mthe
art solution.nt ma en
a.b be rt a.b tb
lon elo
No arb gs No arb ng
un o s to un os st
a@ Ma project as follows: a @ oM
5. Configure
auth
ori
pthe
r im new rta
au
tho pri
m
art
aB
ze ave Ba riz av arb
dc rab rbo ed era
op ss sa co bs os
i . . pie s.c a.
a. Start Action: esa
llo
Don’t
c om open a page. sa
llo
om
we we
d! d!
b. Servers: Use Local IIS Web server
d. Add the Grades.Web project to the list of startup projects for the solution.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do do
1. Addcuam new folder named Services to the Grades.Web cu
me project.
ma en ma n
rta tb rta tb
.ba elo .ba elo
No rbo ng N r b ng
2. Add
un a new sa
@
WCFs to Data Service named GradesWebDataService
M
o un o sa
@
st
oM to the Services
au p a au p art
tho rim rta tho rim aB
folder.rized av
era Ba
rbo
riz
ed
av
era arb
co bs sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
3. Add a referencewto ed the Grades.DataModel project in the Grades.Web we
d!
project.
!
Th Th
is is
Task 3: doSpecify the GradesDBEntities data context
c
do
c
for the data service
um um
ma en ma en
rta tb r ta. tb
.ba elo b elo
No r bo n gs No a r bo ng
un s t u s st
a @ o M n a @ oM
1. a
In the uth code pri in thearGrades.WebDataService.svc a uthfile, add pri a using art directive to
ori ma ta o riz m aB
ze ve Ba av a
rbo e e rbo
bring thed cGrades.DataModel
op
rab
ss sa
.
namespace into scope. dc
op
rab
ss sa
.
ies .co ies .co
all m all m
ow ow
ed e
2. Modify the class declaration ! of the GradesWebDataService dto ! use the
Note: The GradesDBEntities class provides the object context for the
Th EDM. The GradesWebDataService data
Th service will retrieve data by
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/50
10/25/2019 20483A - Programming in C# | Skillpipe
using this object context and expose the various entities by using REST
URIs.
3. In the InitializeService method, set the access rules for each of the following
entities to EntitySetRights.All:
Th Th
is is
• dGrades
oc
um
d oc
um
ma en ma en
rta tb rt a.b tb
.ba elo elo
rbo
No• Teachers ng No arb ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
• Students co
pie bs
s.c
os
a. co
pie bs
s.c
os
a.
sa om sa om
llo llo
we we
• Subjects d! d!
• Users
Th Th
is is
do oc d
Taskm4: Add
um an operation to retrieve all of the students
e
c
m
um
e
in a specified class
art nt art nt
a.b be a.b be
a lon a lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
1. In the rGradesWebDataService
ize
m a ve
aB
arb class, add an operation
o r ize
m anamed
ve Ba
dc rab os d r ab rbo
op s a co s sa
StudentsInClass ies sthat
.co takes
m
. a class name as a string pand
ies returns s.c
om an
.
all all
ow ow
IEnumerable<Student> ed
! collection. This operation should beedannotated ! with the
WebGet attribute.
3. Verify that Internet Explorer displays an XML description of the entities that the
data service exposes.
Scenario
Th Th
is is
do oc d
cum um
ma e m en into the Grades Prototype
In this exercise,
rta n t be you will integrate the WCF Data Service
a rta tb
elo
.ba lon .ba
No rbo gs No rbo ng
application.
un sa
@ t o Ma u na s a @
st
oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
co b s s c o b s os
p s.c a . pie s.c a.
First, you will addiesaalservice om reference in the GradesPrototype s project
a llo
o mthat references
low w
the running WCF DataeService. d! ed
!
You will then modify the code that accesses the local EDM to use the WCF Data
Service instead.
Th Th
is is
Next, youd oc will modify the code that saves changes dback
um
oc
um
to the database to do so
ma en ma en
throughrtathe
.ba data
t b service.
elo rta
.ba
tb
elo
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av
Finally, you will e d c test thee rab application
rbo to verify that it runs the e d c same e rabas ifarthe bo data was
op ss sa op ss sa
ies .co . ies .co .
being called locally.allo m all
o
m
we we
d! d!
1. Add a service reference for the WCF Data Service to the GradesPrototype
Thapplication Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/50
10/25/2019 20483A - Programming in C# | Skillpipe
2. Modify the code that accesses the EDM to use the WCF Data Service
3. Modify the code that saves changes back to the database to use the WCF Data
Service
4. Build and test the application to verify that the application still functions correctly
Th Th
is is
do d oc
cum um
ma e
nt ma en
r
Task 1:aAdd
t a eservice
b reference for the WCF Dataa rt tb
Service to the
.ba lon . ba elo
No rbo gs No rbo ng
GradesPrototype
un sa application
to un sa s to
au @ Ma au @ Ma
tho pri r t t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
1. In Visual Studio,owopen l l
ed
the GradesPrototype.sln solution from l l ow the
ed
! !
E:\Labfiles\Starter\Exercise 2 folder.
Note: The Add Service Reference Wizard prepends the namespace that
Th
is
you specify with the namespace of the Th project, so the result in this case
is
do do
cu is GradesPrototype.Grades.DataModel. cuThe existing code in the
ma m en ma me
tb nt
rta
.ba GradesPrototype
elo project expects the various
r t a .ba entity
be
lon classes to be located
No rbo ng No rbo gs
insathe s
@ Grades.DataModel namespace.unaYou can eitherto update every
un to sa
au M uth @ Ma
tho pri art pri rta namespace of
reference
riz
ed
ma throughout
ve
aB
a
the project, or you can ori change
ze
ma the
v Ba
rab rbo dc e rab rbo
the datac
ies service; this
sa lab opts for the latter approach. There.co isa.one
op ss op ss s
.co . ies
all m all m
drawbackowwith ed
this approach; if you regenerate the data ow service
ed
! !
reference (this will be necessary if, for example, you modify the WCF
data service and add a new entity class), you will have to edit the
Reference.cs file and update the namespace again because any manual
changes you make to this file will be lost.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/50
10/25/2019 20483A - Programming in C# | Skillpipe
6. Copy the following code files from the Grades.DataModel project to the
GradesPrototype\DataModel folder:
• Classes.cs
Th Th
•is dcustomGrade.cs
oc
is
do
um cu
ma en ma me
rta tb r nt
.ba elo t a.b be
No• customTeacher.cs
rbo ng N a r b
lon
gs
un sa st ou os to
@ o M n a @ Ma
au pri art au pri
tho m a t h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
Note: s a The Classes.cs,
llo
om Grade.cs, and Teacher.cs s a files ocontain
llo m custom
we we
functionality d! for the Grade and Teacher classes that dyou
!
implemented in an earlier lab. WCF Data Services does not
propagate any custom functionality that is defined for a data model,
so you must manually copy these files to the Grades.DataModel
project. You will also have to make some small changes to this code
to access data through the WCF Data Service rather than by
Th Th You will do this in the next task.
referencing the entities themselves.
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
Task 2: Modify the code we we Data Service
d! that accesses the EDM to use the WCF d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/50
10/25/2019 20483A - Programming in C# | Skillpipe
static SessionContext()
{
DBContext.MergeOption =
System.Data.Services.Client.MergeOption.PreserveChanges;
}
Th Th
is is
do oc d
cum um
ma ent m en
This
rta constructor
.ba belo ensures that any changes made
art
a.b by t b the user are not lost if
elo
No rbo ng N arb ng
multiple
un s
sausers totry and make simultaneous changes o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
3. In the Views co folder, o
bs in StudentsPage.xaml.cs,
sa locate cthe op Refresh bs os
method.
pie s.c . i e s . a.
sa om sa com
llo llo
we we
d! d!
4. Modify the code in the foreach loop that populates the list ItemsControl with
the details of the students for the current teacher.
The user and grades data for a student are held in separate entities and they are not
Th Th
is is
fetcheddautomatically
oc
u
do to save network resources by
by WCF Data Services (this iscu
ma me ma me
r nt r nt
not retrieving
t a.ba data
belo unnecessarily). The code that populates t a .ba be the list of students should
lon
No rbo n gs No rbo gs
retrieveun that sthe a@ related to
M data in the un sa
@ to
Ma
au pri art a uth pri
tho m aB ori m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
sa om sa om
llo llo
User and Grades properties we
d! for each student by using the LoadProperty we
d! method of
the data context (available in SessionContext.DBContext).
11. In the SaveReport_Click method, modify the LINQ query that retrieves the
grades for the report to also fetch the Subject details. Use the Expand method.
T T
12. hInis dthe
o
his
StudentsPage view, in the NewStudent_Click
do method, find the code
cu cu
mthat me me
art uses nt the Add method of the Studentsmcollection a rta nt to add a new student.
a.b be .ba be
a lon lon
NoModify rbo g N r b gthe
un this
sa codes to to use the AddToStudents
o un method o sa of s t DBContext class.
oM
au @ M a u @
tho p rim a rta tho p rim art
riz av B riz av aB
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Task 3: Modify the code that saves changes back to the database to use the
WCF Data Service
T T
Task h4: histhat the application still
is Build and test the application to verify
do do
cu cu
functions
ma mcorrectly
en
t
ma me
nt
rta be rta be
.ba lon .ba lon
No rbo gs No rbo gs
un sa t o u n s a to
au @ M au @ Ma
tho pri art t h pri rta
m
riz solution, av a Ba then resolve any compilation o riz errors. m av Ba
1. Build the ed era and rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
llo llo
2. Log on as valleewewith d! a password of password99. we
d!
3. Perform the following tasks to verify that the application still updates the data
correctly:
e. Verify that his student profile appears, and then log off.
hisT Th
Scenariodo
is
d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 45/50
10/25/2019 20483A - Programming in C# | Skillpipe
In this exercise, you will write code that displays student images by retrieving the
image from across the web. You will modify the StudentsPage window (that displays
the list of students in a class), the StudentProfile window (that displays the details
for an individual student), and the AssignStudentDialog window (that displays a list
of unassigned students) to include the student photographs.
Th Th
sd i sd i
The data
ocfor each student contains an ImageName
u
ocproperty that specifies the
u
ma me ma me
nt nt
filenamea.bof theephotograph
r t b
lon for the student on the web r t a.b server. be
lon These files are located
No arbo gs No a rbo gs
sa
in the uImages\Portraits to folder on the same web server sthat hoststo
na
uth @
pri M art
un
au a @
pri Ma the data service (in
ori ma aB t h ori ma rta
Ba
the Web.Grades ze
dc project.)
ve
rab You
a rbo will build a value converter ze class
dc
vethat generates
rab rbo the
op s s s a o p s s sa
i s .co . ies .co .
URL of an image efrom all the
ow
mImageName property and then use aan
llo Image m control to
ed wed
use the URL to fetch and! render the image in each of the specified !windows.
Finally, you will run the application to verify that the images appear.
3. At the top of the StackPanel control, add an Image control. The contents of the
image should use a data binding that references the ImageNameConverter
Thclass to convert the value in the ImageName Th property into a URL, and then
is is
do do
cu cu
display
ma m en the data retrieved from this URL. Set
ma the mheight
en of the control to 100.
rta tb r t a tb
.b elo .b elo
NoThe amarkup
rbo ngfor the control should look like
s Nothis:arbo ng
st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
pie s.c . p ies s s a.
sa om .co
<Image Height="100" llo Source="{Binding ImageName, a llo Converter=
m
we we
d! d!
{StaticResource
ImageNameConverter}}" />
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 47/50
10/25/2019 20483A - Programming in C# | Skillpipe
Task 3: Add an Image control to the StudentProfile view and bind it to the
ImageName property
1. In the XAML markup for the StudentProfile view, add an instance of the
ImageNameConverter class as a resource to the view. Use the app
namespace (this namespace has already been defined at the top of the XAML
Th Th
is is
d
markup).
o do
cu cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
a lon
2. NoAt the rbotop ofngthe s t StackPanel control, add an o u Image r os control. to Use the
N b gs
un sa o n a
au @ M au @ Ma
tho prim a rta tho p rim rta property into a
ImageNameConverter
riz
ed
av Ba to convert the value in the riz ImageName
ed
av Ba
era rbo era rbo
co b s s c o b s sa
URL and display p ies the
s .co image retrieved from this URL. Set
a . p iesthe height s.co of. the Image
all m all m
o ow
control to 150. wed! ed
!
4. View George Li’s profile and verify that his image appears.
6. Enroll George Li in the class, and then verify that the Assign Student dialog
box now includes images, and new student icons in the main application
Thwindow include images. Th
is is
do d oc
cu um
mClose me ma en
7. art
a.b
thent application.
be rt a.b tb
lon elo
No arbo gs No arb ng
un sa to un os st
@ Ma a @ oM
8. In aVisual
uth
ori Studio,
pri
ma close
rta the solution. au
tho p rim art
aB
ze ve Ba riz av arb
dc rab rbo ed era
op ss sa co bs os
ies .co . pie s.c a.
all m sa om
ow llo
ed we
! d!
Results: After completing this exercise, the students list, student profile, and
unassigned student dialog box will display the images of students that were
retrieved across the web.
Th Th
is is
do d oc
cum um
Module
rta
.ba Review
ma
r
be
lon
and Takeaways
e nt ma
rt a.b
arb
en
tb
elo
ng
No bo gs No os st
un a@ s to un a oM
au Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
ed era rbo ed era arb
Module Review co
pie
sa
b s s.c sa
.
co
pie
sa
b s s.c
os
a.
om om
llo llo
we we
d! d!
In this module, you have learned how to use the request and response classes in the
System.Net namespace to manipulate remote data sources directly and how to use
WCF Data Services to expose and consume an entity data model over the web.
Question
Do nothing. All entity sets in the EDM are automatically available to client applications.
In the InitializeService method of the data service, use the SetEntityAccessRule method of the
Th DataServiceConfiguration object to specify which entity Th sets should be made available to client
is is
do do
applications.
cu
m
cu
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No Create n
rbo a certificate
gs for each client that can connectNto the service.
r b Configure
gs the service to only
un sa to o un o sa to
a
allow @
uth authenticated M a @ M
pri aclients
rta to connect and retrieve data. uth pri art
ori ma Ba ori ma aB
ze ve rbo zed vera arb
dc rab c b os
Define a data opiecontract s s.cfor eachs a o pie s a.
sa . entity set. sa
s.c
om om
llo llo
we we
d !
Configure the service to enable HTTP GET requests for each entity set. d!
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 50/50
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
Contents:
is
do
cu
is
d oc
um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho Module pri tho p rim art
av Overview
m rta aB
riz Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
Lesson 1: Using XAML llo
we
to Design a User Interface llo
we
d! d!
Lesson 3: Styling a UI
d! d!
An effective and easy-to-use user interface (UI) is essential for graphical applications.
In this module, you will learn how to use Extensible Application Markup Language
(XAML) and Windows Presentation Foundation (WPF) to create engaging UIs.
Th Th
is is
do d oc
c
Objectives
ma n
um
e ma
um
en
rta tb rt a.b tb
.ba elo elo
No r bo ng No arb ng
st os st
After completing
un
au
s a @ this oM module, you will be able to: un
au a @ oM
tho pri art tho pri art
riz m av aB riz m av aB
ed era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
• Use XAML to design s all a o UI.
m sa om
ow llo
ed we
! d!
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/64
10/25/2019 20483A - Programming in C# | Skillpipe
XAML is a declarative, XML-based markup language that you can use to create UIs
for .NET Framework applications. Defining a UI in declarative markup, rather than
imperative code, makes your UI more flexible and portable. Using XAML also helps
Th
to separate
is
d your application UI from its runtime Tlogic.
his
d
oc oc
um um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
N r N arb ng
In thiso ulesson, bos yougswill to learn how to use XAML too ucreate ossimple s t graphical UIs.
oM
na a @ Ma na a@
uth pri rta uth pri art
ori ma Ba ori ma aB
ze ve rbo ze ve arb
dc rab dc rab os
op s s sa op s s a.
Lesson Objectives ies
all
ow
.co
m
. ies
all
ow
.co
m
ed ed
! !
After completing this lesson, you will be able to:
• Describe
T
some of the common controls usedTby WPF applications.
his his
do do
cum cu
ma ma me
• Create
rta controls
nt
b
and set properties in XAML.
e
rt a.b
nt
be
.ba elo lon
No rbo ng No arb gs
un sa st un os to
@ oM a@ Ma
• Handle au events p for XAML
art controls. au pri
tho rim aB tho m rta
riz av a riz av Ba
ed era rbo ed era rbo
co bs sa co b s sa
pie s.c . pie s.c .
• Use layout controls sa
llo in oXAML.
m sa
llo
om
we we
d! d!
• Create user controls in XAML.
Introducing XAML
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
represent controls and their properties. You can use a variety of tools to create XAML
files, such as Visual Studio, the Microsoft Expression® suite, and text editors. When
you build a WPF application, the build engine converts the declarative markup in your
XAML file into classes and objects.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Order Your Coffee Here" Height="350"
Th Th
is is
do
Width="525"> d oc
cu um
ma me ma e
rta nt rtnt
<Grid>.ba be a.b be
lon a lon
No rbo gs No rbo gs
un <Button sa to
Content="Get Me a Coffee!"un /> sa@ to
au @ M a uth Ma
tho pri art pri rta
riz m av aB ori m a Ba
</Grid>ed c era arb ze ve rbo
bs os d co r ab
op s.c a pie s s.c sa
ies . sa .
</Window> all om om
ow llo
e we
d! d!
XAML uses a hierarchical approach to define a UI. The most common top-level
element in a WPF XAML file is the Window element. The Window element can
include
Th several attributes. In the previous example,
Th the Window element identifies
is is
oc d o d
various
m
XMLum namespaces that make built-in controlscuavailable
e m me for use. It defines a
ar nt ar nt
ta. be ta. be
title,Nwhich ba is displayed
rb
lon
g
in the title bar of the application,
N
ba
rb and
lon defines the initial height
g
ou os st ou os st
na a@ oM na a@ oM
and width
uthof thepriwindow.
ma
art
aB
uth pri
ma
art
aB
ori ori
ze ve arb ze ve arb
dc rab os d
co r ab os
op s s a. pie ss a.
ies .co sa .co
all m llo m
A Window element can ow contain
ed a single child element that defines we the content of the
! d!
UI. In most applications, a UI requires more than a single control, so WPF defines
container controls that you can use to combine other lower-level controls together
and lay them out. The most commonly used container control is the Grid control, and
when you add a new Window to a WPF project in Visual Studio, the Window
template
Th automatically adds a Grid control to the
Th Window.
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/64
10/25/2019 20483A - Programming in C# | Skillpipe
The Grid control can contain multiple child controls that it lays out in a grid style. In
the example shown above, the Grid control contains a single Button control. The
Grid control defines a default layout that consists of a single row and a single
column, but you can customize this layout by defining additional rows and columns
as attributes of the Grid. This mechanism enables you to define cells in the Grid, and
you can then place controls in specific cells. You can also nest a grid control inside a
Th Th
is is
cell if youdo need to provide finer control over the layout
cu
do of certain parts of a window.
cu
ma me ma me
rta nt r nt
.ba belo t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
@ M @ Ma the XAML
Additional
au
tho pri Reading:
m
art
a
For more information about
au
t h o
XAML,
pri
m
see rta
riz av Ba riz av Ba
Overview e d c (WPF)
op
e rab page rboat http://go.microsoft.com/fwlink/?LinkID=267821.
s
e dc
o
e rab rbo
sa
ies s s a . p ies s s .
.co .co
all m all m
ow ow
ed ed
! !
Common Controls
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The .NET Framework provides a comprehensive collection of controls that you can
use to implement a UI. You can find the complete set in the Toolbox that is available
when you design a window. You can also define your own custom user controls, as
described in this lesson. The following table summarizes some of the most commonly
T Th
used hcontrols:
is
do
is
d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arbng
No rbo gs No osst
un s a@ to un a oM
Control au
tho pri Ma
rta
Description auth @
pri art
riz ma Ba ori ma aB
ed ve rbo ze ve arb
co rab dc rab os
pie ss sa op s s a. an action.
Button sa .c . Displays a button that a user can iesclick to.cperform
om all o m
llo ow
we ed
d! ! should be selected
CheckBox Enables a user to indicate whether an item
(checked) or not (blank).
ComboBox Displays a drop-down list of items from which the user can
make a selection.
Label
T Displays a pieceT of static text.
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 4/64
10/25/2019 20483A - Programming in C# | Skillpipe
Control Description
ListBox Displays a scrollable list of items from which the user can
make a selection.
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
When you add controls we to a XAML
d! window, you can define control we properties
d! in
various ways. Most controls enable you to set simple property values by using
attributes.
The following example shows how to set the properties of a button control by using
attributes:
Th
is
Th
is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
arb ng
Using
No Attributes
un
rbo
s
gto
s t Set Control Properties No
un os st
a@ oM a @ oM
au pri art au pri art
tho m aB tho m aB
riz av arb riz av arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
<Button Content="Get we we
d! Me a Coffee!" d!
Margin="150, 130, 150, 130"
Background="Yellow"
Foreground="Blue" />
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/64
10/25/2019 20483A - Programming in C# | Skillpipe
This attribute syntax is easy to use and intuitive for developers with XML experience.
However, this syntax does not provide the flexibility that you need to define more
complex property values. Suppose that instead of setting the button background to a
simple text value such as Yellow, you want to apply a more complex gradient effect
to the button. You cannot define all the nuances of a gradient effect within an attribute
value. Instead, XAML supports an alternative way of setting control properties called
Th Th
is is
propertydoelement syntax. Rather than specifying the
cu
do Background property as an
cu
m me m me
art nt nt
art an element
inline attribute
a.b bof
el the Button element, you can add a.b be
l
named
arb on arb on
No os gs No os gs
Button.Background
una a @ t o Mas a child element of the Button u na element,
a @ to and then in the
Ma
uth pri art uth pri rta
ori ma aB ori ma Ba
Button.Backgroundze
dc
ve element,
rab a rbo you can add further child ze elements
dc
ve
rab to definerbo your
op s s s a o p s s sa
. .
gradient effect. ies all .com ies
all
.co
m
ow ow
ed ed
! !
The following example shows how to set the properties of a button control by using
property element syntax:
Many WPF controls include a Content property. The previous examples used an
attribute to set the Content property of a button to a simple text value. However, the
content of a control is rarely limited to text. Instead of specifying the Content property
Th
as an iattribute,
sd you can add the desired contentThbetween
is
d
the opening and closing
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 6/64
10/25/2019 20483A - Programming in C# | Skillpipe
tags of the control. For example, you might want to replace the contents of the
Button element with a picture of a cup of coffee.
Adding
T
Content to a WPF Control Th
his is
do d oc
cum um
ma nt e maen
rta b a.b rttb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
<Button Margin="150,
@ M 130, 150, 130"> @ oM
au p a au p art
tho rim rta tho rim a
riz av B r a
<Image eSource="Images/coffee.jpg"
dc era arb Stretch="Fill" ized vera /> Barb
op bs o sa co bs os
ies s.c . pie s.c a.
</Button> all om sa om
ow l l ow
ed ed
! !
Handling Events
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
When you create a WPF application in Visual Studio, each XAML page has a
corresponding code-behind file. For example, the MainWindow.xaml file that Visual
Studio
Th creates by default has a code-behind fileThnamed MainWindow.xaml.cs. You
is is
oc d oc d
subscribe
m
uto
me event handlers in your XAML markup
m
andum then define your event
e
art nt art nt
a.b be a.b be
handler
No logic
arb in the l ong code-behind file. N arb lon
gs
un o s s t o un o s to
a@ oM a@ Ma
au pri art a uth pri
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss includes sa op ss to create sa
Note: Visual pie Studio
sa .c om
. many features that make i it
e saeasy . com
.
llo llo
handlers for events. we
d! For example, if you double-click a Button
we
d! control at
design time, Visual Studio will automatically create an event handler stub
method in the code- behind file. It also automatically binds the Click event of
the button to the event handler method.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/64
10/25/2019 20483A - Programming in C# | Skillpipe
Suppose you create a simple application that consists of a button and a label. When
you click the button, you want an event handler to add some text to the label. To do
this, you need to do three things:
1. Make sure the button and the label include a Name property, so that you can
reference the controls in your code.
Th Th
is is
do oc d
umc um
2. mSet
art thenClick
e
t b
attribute of the button to the name m art ofentan be
event handler method.
a.b elo a.b l
arbo ng a rbo ong
NoThis method sruns when the Click event occurs. No st
un sa to un sa oM
au @ M au @
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
Note: The llo name
we of a control should be unique within llo the window
we that
d! d!
holds the control; no two controls in the same window should have the
same name.
Th Th
sd i i
The following
oc
u
code example shows how to set thes devent
oc
u
handler method for the Click
m me ma me
nt nt
event aof
rta a Button
.b be
lo control:
rt a.b be
lon
No arb ng No arb gs
un sa o st un os to
@ oM a@ Ma
au pri art au pri
tho m aB tho m rta
riz av arb riz av Ba
Handling Events ed
co inraXAML
e
b os
ed
co
era
b
rbo
sa
pie s s.c a. pie s s.c .
sa om sa om
llo llo
we we
d! d!
<Button x:Name="btnMakeCoffee"
Margin="150, 130, 150, 130"
Content="Make Me a Coffee!"
Click="btnMakeCoffee_Click" />
Th Th
is is
d
<Labelocx:Name="lblResult" do
um cu
ma en ma me
rta t b Content="" r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s t oM
a@ Margin="150, 186, 150, 75" un
/> s a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
we we
In the code-behind file, dyou
! can add logic to the btnMakeCoffee_Click d! method to
define what should happen when a user clicks the button.
The following example shows how to create an event handler method for a WPF
control:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th T
Additional
is
do Reading: For more informationhisabout
do how routed events work in
cu cu
mWPF, m esee m
art nt the Routed Events Overview page ma at en
rta tb
a.b be .ba elo
a l o
http://go.microsoft.com/fwlink/?LinkID=267821.
n ng
No r bo gs No r bo st
un s a t o u n s a oM
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
pie s.c . p ies s s a.
sa om .co
Using Layout Controls llo
we
d!
a llo
we
d!
m
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
oM
Supportaufor tho relative
@
prim positioning
M a rta
is one of the core principles
au
tho
@
p rim WPF.
of art The idea is that
riz av B r a aB
ed should era render arb ized the user vera arb
your application co bs o sa correctly regardless of how co bs positions
os
a.
or
pie s.c . pie s.c
sa om sa om
resizes the application llo window.
we WPF includes several layout, or llocontainer,
we controls
d! d!
that enable you to position and size your child controls in different ways. The
following table shows the most common layout controls:
Control Description
Th Th
is is
do d oc
cum um
ma ent ma en
t
Canvasrta.ba be
lon
rt
a.b
Child controls be their own layout by specifying
a define
lo
No rbo gs No rbo gs n
un sa to canvas sa
uncoordinates. to
au @ Ma au @ Ma
tho pri rta p
tho
rim rta
riz m av Ba riz
av Ba
ed era rbo ed
era
DockPanel co b s sa Child controls arecattached
op bto
s therbedges
os of the
pie s.c . ies s.c a.
sa om all o m
llo ow
we ed
d! !
Control Description
DockPanel.
The following example shows how to define a grid with two rows and two columns:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/64
10/25/2019 20483A - Programming in C# | Skillpipe
<Grid>
<Grid.RowDefinitions>
<RowDefinition MinHeight="100" MaxHeight="200" />
Th Th
is is
do<RowDefinition Height="Auto" /> d oc
cu um
ma me ma en
nt
</Grid.RowDefinitions>
rta rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa
<Grid.ColumnDefinitions> to un a oM
au @ Ma au @
tho pri rta tho p rim art
riz m av Ba riz av aB
<ColumnDefinition
ed era rbo Width="3*" /> ed era arb
co b s sa co bs os
pie s.c . pie s.c a.
<ColumnDefinition sa om Width="7*" /> sa om
llo llo
we we
</Grid.ColumnDefinitions> d! d!
In the previous example, notice that you use RowDefinition and ColumnDefinition
elements to define rows and columns respectively. For each row or column, you can
specify a minimum and maximum height or width, or a fixed height or width. You can
specify
Th heights and widths in three ways:
is
Th
is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
a ng 200 units (where 1 unit
• As
No numerical
un
r bo
s a
units.
gs
t o
For example, Width="200"
No represents
u
r bo
s a
st
oM
au @ M n a @
t pri art uth pri art
equals 1/96th
h o riz ofavan inch).
m a Ba o riz m av aB
arb
ed era rbo e d e r ab
co bs sa co s os
pie s.c . p ies s.co a.
sa om a m
• As Auto. For example, llo
we Width="Auto" will set the column tollthe ow minimum width
d! ed
!
required to render all the child controls in the column.
• As a star value. For example, Width="*" will make the column use up any
available space after fixed-width columns and auto-width columns are allocated. If
you create two columns with widths of 3* and 7*, the available space will be
This hi T
divideddo between the columns in the ratio 3:7. s do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/64
10/25/2019 20483A - Programming in C# | Skillpipe
To put a child control in a particular row or column, you add the Grid.Row and
Grid.Column attributes to the child control element. Note that these properties are
defined by the parent Grid element, rather than the child Label element. Properties
such as Grid.Row and Grid.Column are known as attached properties—they are
Th by a parent element to be specified by its
defined Th child elements. Attached properties
is is
do do
um c um c
enable
ma childenelements to tell a parent element how
t
ma they enshould be rendered.
t
rta be rta be
.ba lon .ba lon
No rbo gs No rbo gs
un sa t o u n s a to
au @ M au @ Ma
tho pri art t h pri rta
riz m av a o m
riz layoutavcontrols,
Additional ed Reading:
era Ba For more information about
rbo ed era Ba see:
rbo
co b s s a c o b s sa
• The Canvas p ies Classs .co page at http://go.microsoft.com/fwlink/?
. p ies s.co .
all m all m
ow ow
LinkID=267823. ed
!
ed
!
surface by double-clicking a control in the toolbox. It shows how you can configure
controls through a combination of using designer tools and editing XAML markup
directly. It also illustrates how Visual Studio can automatically connect event handlers
to your controls.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/64
10/25/2019 20483A - Programming in C# | Skillpipe
Demonstration Steps
6. In Visual Studio, on the File menu, point to New, and then click Project.
11. Add the following markup between the opening and closing Grid tags:
Th Th
is is
do d oc
cu
<Grid.RowDefinitions> um
ma me ma en
rta nt rt tb
be
.ba<RowDefinition a.b elo
rbo
lon Height="Auto" /> arb ng
No gs No os st
un s a@ t oM un a oM
au <RowDefinition Height="*" /> au @
tho pri art tho pri art
riz m av aB riz m av aB
ed era arb ed era arb
</Grid.RowDefinitions>
co bs os
a. co bs os
a.
pie s.c pie s.c
sa om sa om
llo llo
we we
d! d!
12. Open the Toolbox pane, expand Common WPF Controls, and then double-
click Button.
13. On the design surface, drag the button towards the top of the screen until a
Thmessage Th
displays Press Tab to place inside
is is row 0. Press Tab, and then
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/64
10/25/2019 20483A - Programming in C# | Skillpipe
14. In the XAML pane, in the Button element, change the value of the Content
attribute to Make Me a Coffee!
20. In the XAML pane, in the Label element, change the value of the Content
attribute to an empty string.
T T
21. hChange
is
do
his
the value of the HorizontalAlignment do attribute to Center.
cu cu
ma me ma me
rta nt rt nt
b elo
.ba Properties a .ba be
22. In
No the rbo n gs window, ensure the label
No is selected,
rbo
lon and then in the
gs Name
un sa to un sa to
a @ M a @ Ma
textutbox,
ho type
pri
m lblResult.
art
aB
uth
ori
pri
m rta
riz av arb ze a ve Ba
ed era d r ab rbo
co b s os co s sa
pie s.c a . pie s.c .
23. On the design s asurface,
llo
om double-click Make Me a Coffee!s a
llo
om
we we
d! d!
24. Notice that Visual Studio automatically creates an event handler method and
switches to the code-behind page.
29. Close the Order Your Coffee Here window, and then close Visual Studio.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
When you work with s a WPF,
llo
omyou can create your own self-contained, sa
llo
reusable
om user
we we
controls in XAML. Userdcontrols ! are sometimes called composite controls, d! because
they are a composite of other controls. For example, if you use the same combination
of a text box and a button multiple times in a UI, it might be more convenient to
create and use a user control that consists of the text box and the button.
Alternatively, you might create a user control to enable multiple developers to share
T
his his T
the same do custom control across multiple assemblies.
c
do
c
um um
ma ent ma en
rta be rt
a.b tb
.ba lon elo
No rbo gs No a rbo ng
st
Like auregular
na s a XAML
@ t o window,
Ma user controls consist u naof a XAML
s a @ file
o M and a
uth pri r t u t h p r i art
ori m av aB ori m avdifferenceaB
corresponding ze code-behind
dc era a file.
rbo In the XAML file, the principal
zed era arb is that the
op b s s c o b s os
ies s.c a . pie s.c a.
top-level element isalal UserControl o m element rather than a Window s all element.
o m
ow ow
ed ed
! !
The following example shows a user control that enables people to select and order
beverages:
xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Th Th
is is
do mc:Ignorable="d" d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/64
10/25/2019 20483A - Programming in C# | Skillpipe
d:DesignHeight="300" d:DesignWidth="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="2*"/>
Th Th
is is
do
c
<RowDefinition Height="1*"/> do
cu
um me
ma en ma nt
tb
rta </Grid.RowDefinitions> r t a.b be
.ba elo lon
No rbo ng N a r b gs
sa st ou os to
un
au
<StackPanel
@ o M Grid.Row="0"> n au a @ Ma
tho pri art t h pri rta
riz m av a Ba o riz m a Ba
ed <Label era Content="Do
rb you want coffee ed or vtea?"/>
era rb
co bs os co bs os
pie s.c a. pie s.c a.
sa
<RadioButton om x:Name="radCoffee" sa
Content="Coffee" om
llo llo
we we
HorizontalAlignment="Left"d! d!
VerticalAlignment="Top" Margin="5,5,5,5"
GroupName="Beverage"
IsChecked="True" Checked="radCoffee_Checked" />
<RadioButton x:Name="radTea" Content="Tea"
Th Th
is
HorizontalAlignment="Left" is
do do
cu cu
ma m en ma me
rta t VerticalAlignment="Top"r nt
Margin="5,5,5,5"
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa
GroupName="Beverage" to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era Checked="radTea_Checked"/>
arb ze
d
ve
r rbo
co b os co ab sa
pie s s.c a . pie s s.c .
</StackPanel> sa om sa om
llo llo
we we
<StackPanel d! Grid.Row="1"> d!
Checked="radNoMilk_Checked"/>
</StackPanel>
<StackPanel Grid.Row="2">
<Label Content="Do you want sugar?"/>
Th his T
is <RadioButton x:Name="radSugar"
do do Content="Sugar"
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 16/64
10/25/2019 20483A - Programming in C# | Skillpipe
HorizontalAlignment="Left"
VerticalAlignment="Top" Margin="5,5,5,5"
GroupName="Sugar"
IsChecked="True" Checked="radSugar_Checked" />
<RadioButton x:Name="radNoSugar" Content="No Sugar"
HorizontalAlignment="Left"
Th Th
is is
do
c
VerticalAlignment="Top"
do
c
Margin="5,5,5,5"
um um
m
art nt e ma en
GroupName="Sugar"
a. be rt a.b tb
ba lon elo
No rbo gs No ng arb
sa to o sa st
un
au @ M Checked="radNoSugar_Checked"/>
un
au @ oM
tho prim a rta tho p rim art
r a B r a aB
i z
</StackPanel>
ed v era arb ized vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
<Button s a x:Name="btnOrder"
om Content="Place sOrder" all om
llo ow
we ed
Margin="5,5,5,5" Grid.Row="3" d! !
Click="btnOrder_Click"/>
</Grid>
</UserControl>
Th Th
is is
do do
um c cu
As the
ma previous en
t
example shows, creating the XAML ma for
me a user control is very similar
nt
rta belo r t a be
.ba .ba lon
to creating
No rbthe
o sa
XAML
n g s to
for a window. In the code-behind
N o r b ofile
sa
for gsthe user control, you
to
un @ M un @ Ma
au pri art a uth pri
can create thoevent
riz mhandler
av aB methods in the same way that
ori
ze
you m would
a ve
rtafor regular XAML
Ba
ed era arb d r rbo
co b os co ab sa
windows. When pyou ies edit s s.c the code-behind
om
a . file, you should also:
pie
sa
s s.c
om
.
all llo
ow we
ed d!
!
• Define any required public properties. Creating public properties enables the
consumers of your user control to get or set property values, either in XAML or in
code.
• Define
Th any required public events. Raising events
Th enables consumers of your user
is is
d
oc to respond in the same way that they would
oc respond to other control d
control um um
ma en ma en
ta.r b t rt a.b tb
events,
N
ba sucheloas
r ng the Click event of a button. N arb
elo
ng
ou bo st ou os st
na sa oM na a@ oM
uth @ uth
pri art pri art
ori ma aB ori ma aB
ze ve arb ze ve arb
dc rab os dc rab os
op s s a. op s s a.
ies .co ies .co
a m a m
The following example llo shows the
we code-behind class for a user lcontrol: low
d! ed
!
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/64
10/25/2019 20483A - Programming in C# | Skillpipe
T}h Th
is is
do d oc
private cu
ma me string beverage; ma
um
en
rta nt rt tb
.ba
private bstring
elo milk; a.b elo
No rbo ng No arb ng
un sa st un os st
@ o Ma sugar; a @ oM
au
private string
pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
public string e dc e rabOrder rbo ed era
op s sa co bs os
ies s .co . pie s.c a.
a m sa om
{ llo
we
llo
we
d! d!
get
{
return String.Format("{0}, {1}, {2}", beverage, milk,
sugar);
Th } Th
is is
do d oc
} c um um
ma ent nt ma e
rta be a.b be rt
public.ba event
lon EventHandler<EventArgs> OrderPlaced;
a lon
No rbo gs No rbo gs
un sa to un sa to
private
au @void M
btnOrder_Click(object sender,
a uth @ Ma
RoutedEventArgs e)
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
{ co b os dc rab
pie s s.c a o pie s s.c sa
sa . sa .
om om
if(OrderPlaced!=null) llo
w
llo
w
ed ed
! !
OrderPlaced(this, EventArgs.Empty);
}
private void radCoffee_Checked(object sender, RoutedEventArgs e)
{ beverage =
"Coffee";
T
} Th
his is
do do
private cu
m
void radTea_Checked(object sender, cu
me
RoutedEventArgs e) {
ma en ma n
rta t rta tb
beverage .ba = b"Tea"; elo } .ba elo
No r bo n gs No r bo ng
u s t u s st
n
private a @
void o radMilk_Checked(object
M n
sender, a @ oM
RoutedEventArgs e) {
au pri art a uth pri art
tho m a o m aB
riz av B arb r ize a ve arb
milk = "Milk"; ed }era dc rab
co bs os op s os
pie s.c a. ies s.co a.
sa om all m
private void lloradNoMilk_Checked(object
we
sender, RoutedEventArgs
ow e)
d! ed
!
{ milk = "No Milk"; }
private void radSugar_Checked(object sender, RoutedEventArgs e) {
sugar = "Sugar"; }
private void radNoSugar_Checked(object sender, RoutedEventArgs e)
{ sugar = "No
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/64
10/25/2019 20483A - Programming in C# | Skillpipe
Sugar"; }
}
In the previous code example, the user control raises an OrderPlaced event when
the user clicks the Place Order button. Applications that include the user control can
Th
subscribe Th
to this event and take appropriate action.
is is
d oc d oc
um um
ma e nt ma en
rta b rt
a.b tb
.ba elo elo
r ng arb ng
To use
N o u yourouser
b
sa control
s to in a WPF application, you
N o un
need o sato do s ttwo things:
oM
na @ M au @
uth pri art t h p r i art
ori ma aB ori ma aB
ze ve arb zed v era arb
dc rab o co bs os
op s s sa p s a.
1. Add a namespace ies
all
.prefix
co
m for
. your user control namespace ies and.cassembly
all om to the
ow ow
Window element.edThis ! should take the following form: ed
!
Note: If your application and your user control are in the same assembly,
Th Th
is
do
you can omit the assembly name from isthe namespace prefix declaration.
d
c oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au au
2. Addththe ori control
pri
m a
tortyour
aB application in the same tway
ho
riz
that
p rim youawould
av
rta
Ba
add a built-in
ze ve arb ed era rbo
dc rab os
control, with op the namespace
ies ss
.co a. prefix you defined. co
pie bs
s.c sa
.
all m sa om
ow llo
ed we
! d!
The following example shows how to interact with a user control in a code-behind
class:
Th Th
is is
do d oc
um c um
Programming
ma en with User Controls
tb
ma en
tb
rta elo rt a.b elo
.ba arb
No rbo ng No ng
un sa st un os st
@ oM a @ oM
au p art au p art
tho rim aB tho rim aB
riz av arb riz av arb
ed era ed era
c op class b s os c op b s os
public partial ies s.c MainWindow
a. : Window ies s.c a.
all o m all o m
ow ow
{ ed ed
! !
public MainWindow()
{
InitializeComponent();
}
Tprivate
his void coffeeSelector1_OrderPlaced(object Th sender, EventArgs
is
do do
cu cu
e) ma me ma me
rta nt r nt
.ba belo t a .ba be
ng lon
N{ou r b os s N o r b o gs
na a@ t oM un s a@ to
u p a a u p Ma
t
lblResult.Content
ho r im r ta = coffeeSelector1.Order; t ho r im rta
riz av B arb r ize a ve Ba
ed era dc rab rbo
} c op b ss o sa op ss sa
ies .co . ies .co .
all m all m
} o we o we
d! d!
Most applications work with data in one form or another. The data that drives your
application can come from a wide variety of sources, such as files, databases, or web
services. Almost every graphical application needs to connect UI controls to an
Th Th
underlying
is
d data source so that users can retrieve, is enter, or edit information.
d
oc oc
um um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
N r N arb ng
In thiso ulesson, bos yougswill to learn how to bind controlso to
un data o sa WPF
in s t applications.
oM
na a @ Ma au @
uth pri rta tho p rim art
ori ma Ba riz av aB
ze ve rbo ed era arb
dc rab co bs os
op s s sa pie s.c a.
Lesson Objectives ies
all
ow
.co
m
. sa
llo
om
ed we
! d!
After completing this lesson, you will be able to:
• Use
T
XAML to bind controls to data. Th
his is
do d oc
cum um
• ma code nto bind controls to data.
Use e ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
@ oM a @ oM
• Bind acontrols
uth
ori
prto
i m collections
art
aB
of data. au
tho p rim art
aB
ze av a riz av arb
dc era rbo ed era
op bs sa co b s os
ies s.c . pie s.c a.
• Create data templates all oto
m specify how data is rendered. s all o m
ow ow
ed ed
! !
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
co ss sa co bs os
pie . . pie s.c a.
sa c om sa om
llo llo
we we
d! d!
Data binding is the act of connecting a data source to a UI element in such a way that
if one changes, the other must also change. Conceptually, data binding consists of
three components:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/64
10/25/2019 20483A - Programming in C# | Skillpipe
• The binding source. This is the source of your data, and is typically a property of a
custom .NET object. For example, you might bind a control to the
CountryOfOrigin property of a Coffee object.
• The binding target. This is the XAML element you want to bind to your data
source, and is typically a UI control. You must bind your data source to a property
ofThyour
is target object, and that property must Tbe
his a dependency property. For
do do
um c um c
example,
ma enyou might bind data to the Contentmproperty
t a en of a TextBox element.
t
rta be rta be
.ba lon .ba lon
No rbo gs No rbo gs
un sa t o u s a to
• The binding
au
tho
@ object.
pri M aThis
r
is the object that connects n au the source
t h
@
pri Mato the target. The
rta
riz m ta o riz m
av Ba av Ba
Binding object e dc e
can rab also bspecify
r a converter, if the source e d c propertye rab and
rbo the target
op s os o s sa
ies s .co a . p ies s.co .
property are of different a llo mdata types. a llo m
we we
d! d!
• The Binding expression is enclosed in braces. This enables you to set properties
onThthe
i
Binding object before it is evaluated by
Th the TextBlock.
i
sd sd
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/64
10/25/2019 20483A - Programming in C# | Skillpipe
• The Path property of the Binding object is set to Bean. This indicates that you
want to bind to the Bean property of the coffee1 object.
Th Th
is is
do d oc
um c um
As a mresult
a of
en this expression, the TextBlock willmaalways
t
en display the value of the
t
rta be rta be
arb .b
on l on
arb Bean .b l
Bean
No property
os of gthe
s t coffee1 object. If the value
No of the os gsproperty changes, the
t
un a@ oM un a@ oM
au pri art au pri art
TextBlockorwill
t h
ize
update
ma
ve
automatically.
aB In terms of the tconcepts
ho
riz madescribed
v
aB at the start of
dc rab arb ed era arb
os co bs o sa
this topic: op
ies s s .co a. pie
sa
s.c
om
.
all m llo
ow we
ed d!
!
• The binding source is the Bean property of the coffee1 object.
The following example shows how to configure a text box to use two-way data
binding:
Th
is
Th
is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do ocd
cum um
ma e m en
Additional
rta
.ba
nt
belo Reading: For more information aabout
r t a.b the
t b concepts of data
elo
No binding, rbo see ng N arb ng
un sa sthe
to Data Binding Overview page
o un at o sa st
oM
au @ M au @
h pr i a
http://go.microsoft.com/fwlink/?LinkID=267830.
t r t t h p r i art
ori ma aB ori ma aB
ze ve arb zed vera arb
dc rab o co bs os
op s s sa p s a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
Binding Controls to Data in XAML
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
You can bind controls to data in various ways. If your source data will not change
during the execution of your application, you can create a static resource to represent
your data in XAML. A static resource enables you to create instances of classes. For
example, if your assembly contains a class named Coffee, you can define a static
resource
T
to create an instance of Coffee and set
T
properties on it. To create a static
his his
do do
resource, cuyou must:
m me
cu
ma en ma nt
rta tb a rt be
.ba elo .ba lon
No rbo ng No rbo gs
u s s t un s to
a@ oM a@
• Add nan au element
tho pri
ma
to the
art Resources property of a acontainer
uth pri control,
ma
Ma
rta such as the top-
riz aB ori Ba
ed ve arb ze ve rbo
level Window. co
pie
rab
ss o sa
dc
op
rab
ss sa
sa .c . i e sa . c .
om om
llo llo
w w
• Set the name of theeelement d! to the name of the class you wantedto ! instantiate. For
example, if you want to create an instance of the Coffee class, create an element
named Coffee. Use a namespace prefix declaration to identify the namespace
and assembly that contains your class.
• Add
Th an x:Key attribute to the element. This is
is
Ththe identifier by which you will
is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 24/64
10/25/2019 20483A - Programming in C# | Skillpipe
specify the static resource in data binding expressions. You can create multiple
instances of a resource in a window, but each instance should have a unique
x:Key value.
The following example shows how to create a static resource for data binding:
Th Th
is is
do d oc
c um um
ma e
nt en ma
Creating a.b a Static tb
r t belo Resource a.b elo rt
No arb ng N arb ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa
<Window x:Class="DataBinding.MainWindow" om sa om
llo llo
we we
d! d!
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:DataBinding"
Th Th
is sd i
do Title="Data Binding Example"
oc Height="350"
c um um
ma n e ma en
rta
Width="525"> t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa t u s st
<Window.Resources>
au @ o Ma na a @ oM
tho p rim rta u tho p rim art
riz av B riz av aB
<loc:Coffee
ed era x:Key="coffee1"
a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
sa om Name="Fourth Coffee Quencher" s a o m
llo llo
we we
d! d!
Bean="Arabica"
CountryOfOrigin="Brazil"
Strength="3" />
…
</Window.Resources>
Th Th
is is
… doc d oc
um um
ma en ma en
</Window>
r ta. tb rt a.b tb
ba e lon elo
No rbo gs No arb
ng
un sa to u st
os
@ M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs s co os
If you want to bind p ies an individual
s .co a . UI element to this static resource, p ies s syou
.co can a. use a
all m all m
ow ow
binding statement that especifies
d! both a source and a path. You set edthe Source
!
property to the static resource, and set the Path property to the specific property in
the source object to which you want to bind.
The following example shows how to bind an individual item to a static resource:
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
c u u
me
Moremcommonly, me
you will want to bind multiple UImaelements to different properties of a
ar nt r nt
ta. be ta. be
ba lon ba lon
data osource.
N
un
r b osIn thiss tcase,
g you can set the DataContext
N ou r b osproperty gs
to
on a container
a @ o M n a @ Ma
au p a au p
object, suchtho as a rimGrid or rta a StackPanel. Setting a DataContext tho rim
av property is similar to
rta
riz av Ba riz Ba
ed era rbo ed era rbo
co bs sa expression. It specifies thecosource bs sa but does
providing a partial pie data
sa
sbinding
.co . pie
sa
sobject,
.co .
llo m llo m
not identify specific properties. we Any child controls within the container we
d! d! object will
inherit this data context, unless you override it. This means that when you create data
binding expressions for child controls, you can omit the source and simply specify the
path to the property of interest.
The Tfollowing
his
d
example shows how to set a dataTcontext
his
d
for a set of child controls:
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
N r No arb ng
Specifying
ou boa sa Data gs Context
to un os
a
st
oM
na @ Ma au @
uth pri rta tho p rim art
ori m a Ba riz av aB
ze ve rbo ed era arb
dc rab co b os
op s s.c sa pie s s.c a.
ies . sa
all om om
ow llo
ed we
<StackPanel> ! d!
<StackPanel.DataContext>
<Binding Source="{StaticResource coffee1}" />
</StackPanel.DataContext>
<TextBlock Text="{Binding Path=Name}" />
Th Th
<TextBlock
is
do
Text="{Binding Path=Bean}" is />
d
cu oc
me me u
ma
<TextBlock nt Text="{Binding ma
Path=CountryOfOrigin}"
nt />
rta be r ta be
.ba lon .ba l
N<TextBlock
ou rbo gText="{Binding
st No
Path=Strength}" rbo /> ongs
na sa oM un s a@ to
uth @ au Ma
pri art p tho rim rta
</StackPanel> oriz m av aB riz av Ba
ed era arb ed era rbo
co bs os co b ss sa
pie s.c a. pie . .
sa om sa com
llo llo
we we
d! d!
While you could specify a full data binding expression for each individual UI element,
specifying a DataContext property typically makes your XAML easier to write, easier
to read, and easier to maintain.
Binding
Th
is
d
Controls to Data in CodeThis d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b rt
a.b tb
.ba elo elo
No rbo ng N arb ng
un sa s to o un o sa st
@ @ oM
In real-world
au
tho applications,
prim
M a rta it is unlikely that your source
au
tho data p rimwill be
art static. It is far
riz av B r a aB
ed era arb ized vera arb
more likely that coyou
pie
willbs retrieveo sa data at runtime from a database
co
pie bs a web
or os service.
a.
In
s.c . s.c
sa om sa om
these scenarios, youowcannot use a static resource to represent your
l l l l ow data. Instead,
ed ed
! !
you must use code to specify the data source for any UI bindings at runtime.
The following example shows how to create data binding programmatically for a
TextBlock element named textblock1:
Th Th
is is
do do
Creating a
u c
Data Binding in Code cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
private void co mainWindow_Loaded(object
b os sender, d r ab
RoutedEventArgs
co e)
pie s s.c a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
{
// Create a Coffee instance to use as a data source.
Coffee coffee1 = new Coffee();
coffee1.Name = "Fourth Coffee Quencher";
Tcoffee1.Bean
his
= "Arabica"; Th
is
do do
cu
coffee1.CountryOfOrigin = "Venezuela"; cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
coffee1.Strength
No rbo ng = 3; No rbo
lon
gs
un s s t un s to
a@ oM a@ Ma
a
// Create
uth pri a Binding art object that references a uth the
pri Coffee instance.
ori ma aB ori ma rta
ze ve a ze ve Ba
Binding d coffeeBinding rab rbo dc rab rbo
co
pie ss sa = new Binding(); op ss sa
sa .c . i e sa . c .
om om
coffeeBinding.Source llo = coffee1; llo
we we
d! d!
coffeeBinding.Path = new PropertyPath("Name");
// Add the binding to the Text property of the TextBlock.
textblock1.SetBinding(TextBlock.TextProperty, coffeeBinding);
}
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/64
10/25/2019 20483A - Programming in C# | Skillpipe
In many cases you can use a mixture of XAML binding and code binding. For
example, you might know that your UI elements will be bound to a Coffee instance at
design time. In this case, you can specify the binding paths in XAML, and then set a
DataContext property in code.
Th Th
is is
do oc d
cum um
m
// Create
art e
n a Coffee instance. ma en
a.b t be r ta. tb
l o b elo
No ar bo n gs = new Coffee(); No a r bo ng
Coffee
un coffee1s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
coffee1.Name riz
ed =av"Fourth
era Ba
rbo
Coffee Quencher"; riz
e
av
e arb
co bs d co r ab os
p s sa p s s a.
coffee1.Bean = ies "Arabica"; .co . ies .co
all m all m
ow ow
coffee1.CountryOfOrigin ed = "Venezuela"; ed
! !
coffee1.Strength = 3;
// Set the DataContext property of the StackPanel.
stackCoffee.DataContext = coffee1;
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do d oc
cum um
ma nte ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb
ng
un sa to un st
os
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co bs os
pie s.c . pie s.c a.
In many scenarios,s ayou will om want to data bind a control to a collection sa om objects.
of WPF
llo llo
we w
includes controls that are d! designed to render collections, such as ethe d! ListBox
control, the ListView control, the ComboBox control, and the TreeView control.
These controls all inherit from the ItemsControl class and, as such, support a
common approach to data binding.
Th Th
is a collection to an ItemsControl instance,isyou need to:
To bind do do
c um c um
ma ent ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
sa source os st
• Specify
un
au the @
pri
to data collection in the
Ma ItemsSource
un
au a property
@
p
o M of the
art
tho m rta tho rim aB
riz av Ba riz av
ItemsControl ed
co
instance.
era rbo ed
co
era arb
os
pie b s sa pie b s a.
s.c . s.c
sa om sa om
llo llo
• Specify the sourcewproperty ed
!
you want to display in the DisplayMemberPath we
d!
property of the ItemsControl instance.
You can bind an ItemsControl instance to any collection that implements the
Th
IEnumerable Th
interface. You can set the ItemsSource and DisplayMemberPath
is is
do do
um c cu
properties
ma inenXAML
tb
or in code. One common approach
ma meis to define the
nt
rta elo r t a be
.ba .ba lon
DisplayMemberPath
No rbo
s
ng
s t
property (or a data template)
No in rbXAML,
o s
gsand then to set the
to
un a@ oM un a@ Ma
au p a a u p
ItemsSource t ho
riz programmatically
r im
av
r ta
B at runtime. t ho
r ize
r im
a ve
rta
Ba
ed era arb dc rab rbo
co b ss o sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
The following code example we shows how to set the DisplayMemberPath we property in
d! d!
XAML:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/64
10/25/2019 20483A - Programming in C# | Skillpipe
Having set the DisplayMemberPath property in XAML, you can now set the
ItemsSource property in code to complete the data binding.
Th Th
is is
The following
do
cu example shows how to set the ItemsSource
do
cu property in code:
ma me ma me
rta nt rt nt
.ba be a.b be
lon arb lon
No rbo gs No os gs
Settingnathe
u s
ItemsSource
a to Property un a@ to
uth @ Ma au Ma
pri rta tho pri rta
ori ma Ba riz m av Ba
ze ve rbo ed era rbo
dc rab co b
op s s sa pie s s.c sa
ies .co . sa .
all m om
ow llo
ed we
! d!
// Create some Coffee instances.
var coffee1 = new Coffee("Fourth Coffee Quencher");
var coffee2 = new Coffee("Espresso Number Four");
var coffee3 = new Coffee("Fourth Refresher");
var coffee3 = new Coffee("Fourth Frenetic");
Th Th
sdi sd i
// Add octhe items to an observable collection. oc
um um
ma en ma en
rta
var coffees t be = new ObservableCollection<Coffee>(); rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa t u s st
coffees.Add(coffee1);
au @ o Ma na a @ oM
tho prim rta u tho p rim art
riz av B riz av aB
coffees.Add(coffee2);
ed era a rbo ed era arb
co b s s c o b s os
pie s.c a . pie s.c a.
coffees.Add(coffee3); s all o m s all o m
ow ow
ed ed
!
coffees.Add(coffee4); !
Th Th
is is
do oc d
cum um
ma e ma en
Note:
rta
.ba
If
n t byou want a control displaying data in
elo r ta. collection
a tb
elo to be updated
n b a n
r
No automatically
bo gs when items are added or removed, No r bothe collection
gs must
un sa to un sa to
au @ M a u @ Ma
implement p ithe a p
t ho
riz
r ma INotifyPropertyChanged
r ta
Ba
interface. t ho
riz This
r im interface
av
r ta
Ba
defines an
ed ve r e e r
event called r
co PropertyChanged
ab b os that the collection can d co raise r b
ab after omaking a
pie ss a. pie ss sa
sa .co s .co .
change. The .NET llo m
Framework includes a class named a llo m
we we
d! d!
ObservableCollection<T> that provides a generic implementation of
INotifyPropertyChanged. The control that binds to the collection receives the
event, and can use it to refresh the data that it is displaying. Many of the WPF
container controls catch and handle this event automatically.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th Th
is is
do oc d
cum um
ma ne m a en
When yourta usebecontrols that derive from the ItemsControl
.ba
t
lon
rta
.ba
t b or ContentControl control,
elo
No rbo gs No rbo ng
st
you canun create
au
sa a data
@ t o Matemplate to specify how your
u na items s a @are rendered.
oM For example,
tho prim rta u tho p rim art
riz wantavto useBa riz collection av a
suppose you ed era arbListBox control to display a ed era ofBCoffee
arb
co b s o s c o b s os
pie s.c a . pie s.c a.
instances. Each Coffee s all instance
o m includes several properties toallrepresent s o m the name of
ow ow
ed ed
the coffee, the type of coffee ! bean, the country of origin, and the strength ! of the
coffee. The data template specifies how each Coffee instance should be rendered,
by mapping properties of the Coffee instance to child controls within the data
template. Creating a data template gives you precise control over how your items are
rendered and styled.
Th Th
is is
do oc d
cum um
ma e nt ma en
The following
rta
.b example
be
lo
shows how to define a datatatemplate
r
.ba
tb
elo for a ListBox control:
No arb ng No r bo ng
un sa o st un sa st
@ oM @ oM
au pri art au pri art
tho m aB tho m aB
riz av riz av
Creating a Data e d c Templatee rab arb
os
ed
co
era
bs
arb
os
op s s a. pie s.c a.
ies .co sa om
all m llo
ow we
ed d!
!
Additional Reading: For more information about data templates in WPF, see
Th Th
the
is
do Data Templating Overviewpage at http://go.microsoft.com/fwlink/?
is
d
cu oc
um
mLinkID=267833.
art
me
nt ma en
a.b be rt a.b tb
lon elo
No arb gs No arb ng
un o s to un os st
a@ Ma a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed ed era
Lesson 3: Styling a UI co
pie
sa
rab
ss
.c om
rbo
sa
.
co
pie
sa
bs
s.c
om
os
a.
llo llo
we we
d! d!
In this lesson, you will learn how to use styles and animations.
Lesson Objectives
After completing this lesson, you will be able to:
his T Th
• Createdo reusable resources in XAML.
is
d oc
cu um
ma me ma en
rta nt rt tb
. be a . elo
• Define
No
bastyleslothat
rbo ng apply to multiple controls. N
s
ba
r b o
ng
st
un sa to o un sa oM
au @ M au @
tho prim a rta tho p rim art
riz av B r a aB
• Use property ed triggers era toarapply styles when conditionseare iz met.vera arb
co bs b o d co bs os
pie s.c sa pie s.c a.
sa . sa
om om
llo llo
• Use animations to wcreate ed
!
dynamic effects and transformations.wed!
XAML enables you to create certain elements, such as data templates, styles, and
brushes, as reusable resources. This has various advantages when you are
developing
Th
is a graphical application: Th
is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
• You
No canbdefine
r ga resource once and use it inNomultiple a r bo places. ng
un o s s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av a
• You can edit e e
d c a resourcerab rwithout
bo editing every element e dthat e
usesr ab therbresource.
op s sa co s os
ies s .co . p ies s .co a.
all m all m
ow ow
• Your XAML files areedshorter ! and easier to read. ed
!
Every WPF control has a Resources property to which you can add resources. This
is because the Resources property is defined by the FrameworkElement class from
T T
whichhisall hi
do WPF elements ultimately derive. In mosts dcases,
o
you define resources on the
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/64
10/25/2019 20483A - Programming in C# | Skillpipe
root element in a file, such as the Window element or the UserControl element. The
resources are then available to the root element and all of its descendants. You can
also create resources for use across the entire application by defining them in the
App.xaml file.
ThNote: Every WPF application has an App.xaml Th file. It is a XAML file that can
is is
do do
containcu
me
global resources used by all windows and cu
me
controls in a WPF
ma n ma n
application.
rta
.ba
tb
elo It is also the entry point for the application,
rta
.ba
tb
elo and defines which
No rbo ng N r b ng
window
un sa should
@
s t appear when an application
oM o ustarts.
n
os
a @
st
oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
Resources are storedwin ed a dictionary collection of type ResourceDictionary.
!
we
d! When
you create a reusable resource, you must give it a unique key by providing a value
for the x:Key attribute.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Th his T
is Title="Reusable Resources"
do do Height="350" Width="525">
c
um cu
m e m me
art n
<Window.Resources>tb art nt
a.b elo a . be
arb ng b arb lon
No o s N o o gs
un <SolidColorBrush
s a@ t oM x:Key="MyBrush" unColor="Coral" s a@ to />
au pri art a uth pri Ma
tho ma aB ori ma r ta
… rize ve arb ze ve Ba
rbo
dc rab o d c r a b
op ss sa op ss sa
</Window.Resources> i esa .c . i e sa . c .
om om
llo llo
we we
… d! d!
</Window>
To reference a resource, you use the format {StaticResource [resource key]}. You
Th Th
is i
can usedothe
cu resource in any property that acceptss values
do
cu of the same type as the
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/64
10/25/2019 20483A - Programming in C# | Skillpipe
resource, provided that the resource is in scope. For example, if you create a brush
as a resource, you can reference the brush in any property that accepts brush types,
such as Foreground, Background, or Fill.
<Application x:Class="ReusableResources.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Th StartupUri="MainWindow.xaml">
T
is his
ocd do
<Application.Resources>
um cu
ma en ma me
rta tb r nt
elo
.ba <ResourceDictionary> t a.b be
ng a lon
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
tho p<ResourceDictionary.MergedDictionaries>
rim art t h pri rta
riz av a Ba o riz m av Ba
ed er<ResourceDictionary
ab rbo e dc e rab rbo
co s s a. o s sa
pie s.c pie s.c .
sa om sa om
Source="FourthCoffeeResources.xaml"
llo
we /> llo
we
d! d!
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
Defining Styles as Resources
No
un
rbo
sa
@
gs
to
Ma
No
un
arb
os
a @
ng
st
oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba l elo
In many
No cases,
r bo you
on gs will want to apply the sameNopropertya r bo values ng
s t to multiple controls of
un s a t o u n s a oM
au @ Ma a @
the same thtype
ori within
pri
ma an rtaapplication. For example, ifua thopagepricontains
riz m av
art five textboxes,
aB
ze ve Ba e e arb
dc rab rbo dc rab osbackground
you will probably op want seach
ies s .co
textbox
sa
. to have the same foreground
o p ies scolor,
s.co a.
all m all m
color, font size, and so ow on. To make this consistency easier to manage, ow you can
ed ed
! !
create Style elements as resources in XAML. Style elements enable you to apply a
collection of property values to some or all controls of a particular type. To create a
style, perform the following steps:
1. ThAdd a Style
is element to a resource collection
Th within your application (for
is
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 36/64
10/25/2019 20483A - Programming in C# | Skillpipe
2. Use the TargetType attribute of the Style element to specify the type of control
you want the style to target (for example, TextBox or Button).
3. Use the x:Key attribute of the Style element to enable controls to specify this
Thstyle. Alternatively, you can omit the x:KeyThattribute and your style will apply to
is is
alldcontrols
oc
um of the specified type. do
cu
me
ma en ma nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r b gspecific
4. Within
un the
sa Style
@
s t element, use Setter elements
o ou
n
to oapply
s a @
st
oM values to
au p M a au p art
tho rim rta tho rim aB
specific riz properties.
ed
av
era Ba
rbo
riz
ed
av
era arb
co bs sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
The following example shows how to create a style that targets TextBlock controls:
Creating Styles
Th Th
is is
do oc d
cum um
m
<Window.Resources>
art e
nt m a en
a.b be rta tb
l o . b elo
No arbo n gs No a rbo ng
<Style
un sa TargetType="TextBlock"
t x:Key="BlockStyle1">
u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
<Setter
riz
ed
av Property="FontSize"
era B a rbo
Value="20" riz
ed /> av
era arb
co b s s c o b s os
pie s.c a . pie s a.
<Setter s a Property="Background"
om Value="Black" s a />.com
llo llo
we we
d!
<Setter Property="Foreground"> d!
<Setter.Value>
<LinearGradientBrush StartPoint="0.5,0"
EndPoint="0.5,1">
Th Th
is
do <LinearGradientBrush.GradientStops>
is
d
c oc
um me u
ma ent ma
<GradientStop Offset="0.0"
nt Color="Orange" />
rta be r ta. be
.ba lon ba lon
No rbo gs <GradientStop o r
NOffset="1.0"b o gs Color="Red" />
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma a B</LinearGradientBrush.GradientStops> ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie </LinearGradientBrush>
.c . i e . c .
sa om sa om
llo llo
we we
</Setter.Value> d! d!
</Setter>
</Style>
…
</Window.Resources>
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/64
10/25/2019 20483A - Programming in C# | Skillpipe
To apply this style to a TextBlock control, you need to set the Style attribute of the
TextBlock to the x:Key value of the style resource.
hisT Th
Applyingdo a Style
is
d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
tho pri rta tho p rim art
<TextBlock m
riz Text="Drink
av Ba More Coffee" Style="{StaticResource
riz av aB
ed era rbo ed era arb
co b s s co bs os
a. a.
BlockStyle1}"pies/> all
s.c
om
pie
sa
s.c
om
ow llo
ed we
! d!
Additional Reading: For more information about defining styles, see the
Styling and Templating page at http://go.microsoft.com/fwlink/?
LinkID=267834.
Th Th
is is
do d oc
cum um
ma ent ma en
tb
Using
N
rta
.bProperty
arb
be
lon
g
Triggers No
rt a.b
arb
elo
ng
ou os st un os st
na a@ oM a @ oM
uth pri art au p art
ori m aB tho rim aB
ze av arb riz av arb
dc era ed era
op b s os co b s os
ies s.c a. pie s.c a.
all o m sa om
ow llo
ed we
! d!
Th Th
is is
do oc d
cum um
ma ent ma en
When your ta. create
ba
be a style in XAML, you can specifytaproperty
lon
r
.ba
t b values that are only
elo
No r bo gs No r bo ng
s s st
appliedun whena@
au certain
pri
t o Mconditions are true. For example,
art
un
a uth
youa @ might
pri
o M want to change
art
the
tho m a o m aB
font style ofrizaedbutton
co
av
erawhen Ba the user hovers over it, or you
rbo
riz
e d might
co
av
e r want
ab
ato
rboapply a
pie bs sa p s sa
s.c . ies s.co .
highlighting effect stoalloselected om items in a list box. all
o
m
we we
d! d!
To apply style properties based on conditions, you add Trigger elements to your
styles. The Trigger element identifies the property of interest and the value that
should trigger the change. Within the Trigger element, you use Setter elements to
apply changes to property values.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/64
10/25/2019 20483A - Programming in C# | Skillpipe
The following example shows how to make the text on a button bold while the user is
hovering over the button:
Th Th
sd i is
<Window.Resources>
oc d oc
u me um
ma nt ma en
rta
<Style bTargetType="Button"> rt a.b tb
.b el on elo
No arb g No arb
ng
un o sa st un st
os
<Style.Triggers>
@ oM a @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arProperty="IsMouseOver" r iz a v arb
ed <Trigger era b Value="True">
ed era
co bs o sa co bs os
pie s.c . pie s.c a.
s a <Setter om Property="FontWeight" Value="Bold" sa om />
llo llo
we we
d! d!
</Trigger>
</Style.Triggers>
</Style>
…
</Window.Resources>
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
Creating Dynamic Transformations
au
tho
riz
pri
m av
rta
Ba
au
tho
riz
p rim
av
art
aB
ed era rbo ed era arb
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
a @ o n a @ oM
Sophisticated
au
tho graphical
pri
m
M art applications often use animations
a uth to
pri
m
make art the user
riz av a B o r a aB
ed era arb ize ve arb
experience more co engaging.
pie bs oAnimations
sa are sometimes used d co to make
p
r ab
s transitions
os
a.
s.c . ies s.co
sa om a m
between states less llabrupt. ow For example, if you want to enlargelloor we rotate a picture,
ed d!
!
increasing the size or changing the orientation progressively over a short time period
can look better than simply switching from one size or orientation to another.
To create and apply an animation effect in XAML, you need to do three things:
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/64
10/25/2019 20483A - Programming in C# | Skillpipe
1. Create an animation.
WPF includes various classes that you can use to create animations in XAML. The
most commonly used animation element is DoubleAnimation. The
DoubleAnimation element specifies how a value should change over time, by
Th Th
is i
do the initial value, the final value, and thes duration
specifying do over which the value
cu cu
m me ma me
nt
shouldartchange. rt nt
a.b be a.b be
l
arb on arb lon
No o st g No os gs
un sa oM un a@ to
au @ au Ma
tho prim art tho pri rta
riz av aB riz m av Ba
2. Create a ed storyboard.
co
era
bs
arb
os
ed
co
era
b
rbo
pie s.c a. pie s s.c sa
sa sa .
om om
llo llo
we we
d! d!
<Window.Resources>
T Th
his is
do oc d
cu
<Style TargetType="Image" x:Key="CoffeeImageStyle">
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/64
10/25/2019 20483A - Programming in C# | Skillpipe
Th </Setter.Value> Th
is is
do d oc
c </Setter>
um um
ma en maen
rta tb a.b rttb
elo
.ba <Style.Triggers> elo
No rbo ng N arb ng
un sa s to o un o sa st
@ M @ oM
au p<EventTriggera au
RoutedEvent="Image.MouseDown"> p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed er<BeginStoryboard>
a ed era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo
we <Storyboard> llo
we
d! d!
<DoubleAnimation
Storyboard.TargetProperty="Height"
From="200" To="300" Duration="0:0:2" />
<DoubleAnimation
Storyboard.TargetProperty="RenderTransform.Angle"
T T
his his
do do
cum From="0" To="30"
cu
m Duration="0:0:2" />
ma nte ma en
rta be rt a.b tb
.ba lon </Storyboard> elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au
tho pri </BeginStoryboard>
rta
au
tho p rim art
riz m av Ba riz av aB
ed </EventTrigger>
era rbo ed era arb
co b s sa co b s os
pie s.c . pie s.c a.
sa om sa om
</Style.Triggers> llo
we
llo
we
d! d!
</Style>
</Window.Resources>
Th Th
Additional
is
do Reading: is
do
cu cu
ma m en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
For more hinformation
t ori r im
a
about
r ta
B
animations, see the Animation t ho
r
Overview
r im
a
rta page
Ba
at
ze ve a ize ve
dc rab rbo dc rab rbo
http://go.microsoft.com/fwlink/?LinkID=267835.
op
ies ss
.co
sa
. op
ies ss
.co
sa
.
all m all m
ow ow
ed ed
! !
Demonstration: Customizing Student Photographs and
Styling the Application Lab
In this demonstration, you will learn about the tasks that you will perform in the lab for
this module.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/64
10/25/2019 20483A - Programming in C# | Skillpipe
Scenario
NowTthat
his you and The School of Fine Arts are happy
Th
is with the basic functionality of
do do
cu cu
the application,
ma me
n
you need to improve the appearance
ma of
me the interface to give the user
n
rta tb rta tb
.ba e .ba
lon through the use of animations and lon e
a nicer
No experience
rbo gs No rbao consistent
gs look and feel.
un sa to un sa to
au @ Ma au @ Ma
tho pri r t t h pri rta
riz m av a Ba o riz m av Ba
ed era rbo ed era rbo
You decide to createc b
a StudentPhoto control that will enable c b
opie s s.c s a. o pie you to s s.c display
sa
.
sa om sa om
llo llo
photographs of students we in the student list and other views. You also
d!
we
d! decide to create
a fluid method for a teacher to remove a student from their class.
Finally, you want to update the look of the various views, keeping their look consistent
across the application.
Th Th
is is
do d oc
c um um
Objectives
ma
rta nt
b
e ma
rt a.b
en
tb
.ba elo elo
No rbo ng No arb ng
un sa st un os st
After completing @ this oM lab, a oM
art you will be able to:
au au @
tho prim tho p rim art
riz av aB riz av aB
ed era arb ed era arb
co b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
• Create and use user llo
we controls.
llo
we
d! d!
his T Th
Scenario is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/64
10/25/2019 20483A - Programming in C# | Skillpipe
In this exercise, you will customize the appearance of student photographs in the
production application.
You will begin by creating a StudentPhoto user control that will host the photographs
on the various pages in the UI. Then you will lay out the user controls and write code
to raise the Student_Click method when a user clicks a student photograph.
Th Th
is is
do d oc
cum um
ma e nt ma en
r rt tb
Next, you t a.b will add
arb
belo a remove button with a red X to the
ng
a.b user
arb
elocontrol that users can
ng
No o s N o o st
sa to sa
click tounremove
au
tho
@ a
p student M a from a class. When a un hovers
user au
tho
@
p over o Mthe button, the
art
rim rta rim aB
riz av B arb photograph will change. r iz a v arb
opacity of theedbutton co
eraand the
bs o sa
ed
co
era
bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d! d!
Finally, you will run the application to verify that the student’s image is displayed
correctly on the StudentsPage view.
3. Start Visual Studio, and then open the Grades.sln solution from the
E:\Labfiles\Starter\Exercise 1 folder.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/64
10/25/2019 20483A - Programming in C# | Skillpipe
a. Grades.Web
b. Grades.WPF
5. Add a new WPF user control named StudentPhoto.xaml to the Controls folder
Th Th
inisdthe
oc
Grades.WPF project. is
do
um cu
ma en ma me
rta tb r nt
.ba the elo t a.b be
6. Modify
No rbo XAML
ng
st
markup for the user control
N as a r follows:
b os
lon
gs
un sa o ou a to
au @ M n au @ Ma
tho pri art t h pri rta
riz m av a Bcontrol o riz control m av will Buse
a. Add ed an Image era arb
os
to the Grid. This Image ed era arb data binding
os
co b s a. c o b s a.
pie s.c pie s.c
to display s a the photograph,
llo
om and the source of the Image sa
llo should
om be the File
we we
d! d!
property of the data source. The Image should fill the user control except
for a margin of 8 points all the way around to allow for a frame.
b. Add a second Image control to the Grid. This Image control will display
the frame around the student photograph, and it should completely fill the
Th
is Grid, so specify a margin of 0 points.ThUse
is the Image_Frame.png file in
do do
umc cu
ma the
en Images folder as the source for the ma Image; me
nt this image has a
rta t b r t a be
.ba elo .ba lon
No rtransparent
bo ng
s center that enables the student
N o r bphotograph
o gs to show through.
un sa to un sa to
au @ M a uth @ M
tho pri art pri art
riz ma aB ori ma aB
v a z v arbunderneath
c. Add ed a TextBlock
co
era
b
rbocontrol to display the name eof
s
d c the student
o
era
b os
pie s s.c a . pie s s.c a.
sa om sa om
the photolloframe. we
This control will also use data binding, llo and the name will
we
d! d!
be provided by the Name property of the data source. Use the static
resource LabelCenter to style the text and set the FontSize to 16. Set the
VerticalAlignment to Bottom to ensure that the name appears
underneath the photograph, and specify a margin of 8, 0, 14.583, 8 to add
Th
a bit of space around the name. Th
is is
do d
oc
cum um
md.
art Change
en the Class name of the control
m ato Grades.WPF.StudentPhoto.
en
a.b t be r ta. tb
l o b elo
No ar bo n gs No a r bo ng
un s t u s st
a @ o n a @ oM
Theuthcompleted
a pri
ma
markup
M art
aB
should look like the following:
a uth pri
ma
art
aB
ori ori
ze ve a rbo ze ve arb
dc rab dc rab os
op s s sa o p s s a.
ies .co . ies .co
all m all m
ow ow
ed
<UserControl x:Class="Grades.WPF.StudentPhoto" ed
! !
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio
n"
Th Th
ixmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
sd is
oc do
um cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 44/64
10/25/2019 20483A - Programming in C# | Skillpipe
xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
Th Th
is is
do
c
d:DesignHeight="300" d:DesignWidth="300">
do
c
um um
ma en ma en
rta <Grid>tb r t a.b tb
.ba elo elo
No rbo ng N arb ng
sa <Image s to o o sa st
un
au @ M Stretch="UniformToFill"
un
au
Source="{Binding
@ oM File}"
tho prim a rta tho p rim art
riz av /> Ba riz av aB
Margin="8" ed era rbo ed era arb
co bs sa co bs os
pie s.c . pie s.c a.
sa
<Image om
Margin="0" Source="../Images/Image_Frame.png" sa om
llo llo
we we
Stretch="Fill"d! /> d!
• System.Windows.Controls
• System.Windows.Media.Animation
define the layout for the list of photographs. The ItemsPanel control should
contain an ItemsPanelTemplate element with the following property values:
o Margin: 0:
o Orientation: Horizontal
Th Th
ois do HorizontalAlignment: Center is
d oc
cum um
ma ent ma en
rta be rt a.b tb
The .bacompleted markup should look like the elo
N following:
lon arb ng
No rbo gs ou os st
un sa t o na a@ oM
au @ Ma uth
tho pri rta pri art
riz m av Ba ori ma aB
ed era rbo ze ve arb
co b dc rab os
p s s sa op s s a.
<ItemsControl ies .co
x:Name="list">. ies .co
all m all m
ow ow
ed
<ItemsControl.ItemsPanel> ed
! !
<ItemsPanelTemplate>
<WrapPanel Margin="0" Orientation="Horizontal"
HorizontalAlignment="Center" />
</ItemsPanelTemplate>
Th Th
is </ItemsControl.ItemsPanel> is
do oc d
cum um
ma<ItemsControl>
en m a en
rta t be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
ed era rbo ed era
3. Add an ItemTemplate c op b s element
s to the ItemsControl. c This
o element
b s oswill specify
ies s.c a . pie s.c a.
all o m s all o m
how each photograph ow is displayed and formatted. ow
ed ed
! !
Th Th
is i
Use thedofollowing
cu information to set the propertiess of
do the StudentPhoto control.
cu
ma me ma me
rta n tb rt nt
.ba elo a.b be
ng arb lon
No r bo st No os gs
un s a oM un a@ to
au @ au Ma
• Height:tho150 pri art tho pri rta
riz m av aB riz ma Ba
ed era arb ed ve rbo
co bs os co rab
pie s.c a. pie ss sa
sa sa . c .
• Width: 127.5 o m om
llo llo
we we
d! d!
• Cursor: Hand
control contains the following namespace definition to bring the types in the
Grades.WPF namespace into scope with the alias local:
xmlns:local="clr-namespace:Grades.WPF"
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="8">
Th Th
is is
<local:StudentPhoto Height="150" Width="127.5"
do do
cum c um
ma e nt ma en
Cursor="Hand"
rta
.ba be /> rt a.b tb
elo
lon arb ng
No rbo gs No os st
un sa </Grid>
to un a oM
au @ Ma au @
tho pri rta tho p rim art
m
riz </DataTemplate>
av Ba riz av aB
ed era rbo ed era arb
co b s sa co b s os
pie s.c . pie s.c a.
</ItemsControl.ItemTemplate>
sa om sa om
llo llo
we we
<ItemsControl> d! d!
T T
Task h3:
is Enable the user to display the detailshfor
do
is
do a student
cu cu
ma me ma me
rta nt rt nt
.ba belo a .ba be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
1. The au user
tho will
pri be able
art to click on a photograph ato
uth display pri theMadetails rta
of a student.
riz ma aB ori ma B
ed ve arb ze ve arb
In StudentsPage.xaml.cs,
co rab
ss os
a
in the Events region, add d c a private
o
rab
s
method
os
a.
named
pie .c . p i e s. c
sa om sa om
Student_Click llothat takes
we an object and a MouseButtonEventArgs llo
we as
d! d!
parameter and returns void.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 47/64
10/25/2019 20483A - Programming in C# | Skillpipe
The StudentProfile view subscribes to this event and uses it to display the details of
the selected student. The Student_Click method should verify that the
StudentSelected event has at least one subscriber before raising the event. The
StudentSelected event expects a LocalStudent object containing the data for the
student to be provided as an event parameter (this is so that the StudentProfile view
knows which student to display). This is actually the same object that will be used as
Th Th
is i
the data dosource for the StudentPhoto control thats dthe
oc user clicked. You can retrieve
cu u
m me m me
art
this object nt the DataContext property of the asender nt parameter to the
a.b formbe
l
rta
.b be
l
arb on arb on
No os gs No os gs
Student_Click
una a @ method to
Ma (you must cast the sender
un property
au a @ to tthe
o M StudentPhoto
uth pri rta tho pri art
ori ma Ba riz ma aB
type first). zed ve
rab rbo ed v era arb
os
co s sa co bs a.
pie s.c . pie s.c
sa om sa om
llo llo
we we
d! d!
The completed method should look like this:
Note: The LocalStudent type is a wrapper around the Student class retrieved
from the database by using the WCF data service. It provides additional
Thhelper methods that the WPF application T can
his
use to format the details of a
is
d
student d
for display purposes. This type is defined u in the Data.cs file.
oc oc
ume me
ma nt ma nt
rta belo r t a be
.ba .ba lon
No rbo ng No rbo gs
un s s t un s to
a@ oM a@ Ma
au pri art a uth pri
tho ma aB o ma rta
3. In StudentPage.xaml,
r i ze
dc
ve
rab a rbomodify the instance of the r izStudentPhoto
e dc
v e rab
Ba control in the
rbo
op ss sa op ss sa
DataTemplate s a element . .
i e .c om to invoke the Student_Click event i e s a handler . com when a user
llo llo
we we
clicks a photo. d! d!
The XAML markup for the StudentPhoto control should look like this:
Th Th
1. InisdStudentsPage.xaml,
oc
is
add another Grid control do
cu
to the existing Grid control in
um me
ma en ma
therta DataTemplate
.ba
tb
elo element. You will add controls rta
.ba
tont this grid to display a
be
ng lon
No rbo st N ou r b os each gs
customized
un
au
sa
@ "remove"
o M
icon in the top right corner
n au
of a @ photograph.
to
Ma
If the user
tho pri art t h pri r t
ma aB ori ma aB
clicks rthis ize icon,
dc
ve the student
rab arb will be removed. ze
dc
ve
rab arb
op s o sa op s os
ies s .co . ies s .co a.
all m all m
2. Use the following ow information to set properties of the Grid control. ow
ed ed
! !
• VerticalAlignment: Top
• HorizontalAlignment:
T
Right Th
his is
do d oc
cum um
• Background:
ma
rta nt #00000000
e
be
ma
rt
en
tb
.ba lon a.b elo
No rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
• Opacity:
a uth 0.3 pri
ori m rta
au
tho p rim art
aB
ze ave Ba riz av arb
dc rab rbo ed era
op s sa co b s os
ies s.c . pie s.c a.
• Width: 20 all om sa
llo
om
ow we
ed d!
!
• Height: 20
• Tag: {Binding}
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.brt tb
.Note: The
lon Tag property will contain a reference toelothe
No
ba
r bo gs No a r bo ng student, so that the
un "remove" s t s st
au a@
pri
functionality
oM
art
knows which student
un to remove.
a uth
a@
pri
o This
Ma property will
tho m a o m rta
usezethe
r i
dc
data
a ve binding
rab
B arb of the ItemsControl that contains r ize
dc
a ve the DataTemplate
rab
B arb
op s os o s os
to reference ies the.costudent.
s a . p ies s.co a.
all m all m
ow ow
ed ed
! !
3. Add an Image control as a child of the Grid control and use it to display the
delete.png picture in the Images folder. Set the Stretch property to Uniform.
Th Th
is i
do image contains a cross symbol that willsbe
This do displayed by the remove icon.
c um c um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 49/64
10/25/2019 20483A - Programming in C# | Skillpipe
The XAML markup for the Grid control should look like this:
This method is an event handler that will run when the mouse moves over the
Th Th
is
remove icon for a student photograph. is
do do
cu cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
lon
5. NoIn therbRemoveStudent_MouseEnter
o
n g s method,
N o add
r b o code gs to change the Opacity
un sa to un sa to
au @ M a @ Ma
propertytho ofprithe Grid art control holding the delete uicon t h to p1.0
r i and rtathe Opacity
riz m av aB ori m a Ba
ed era arb ze ve rbo
co the StudentPhoto os d co r ab
property of pie b s s.c a . control to 0.6. pie s s.c sa
.
sa om sa om
llo llo
we we
d! d!
Note: The Grid control that holds the delete icon is available in the
sender parameter; cast it to a Grid control first before setting the
Opacity property. The StudentPhoto control can be located by
accessing the Parent property of the Grid control holding the delete
Th icon, and then accessing the first child
Th element; use the expression
is is
do Children[0] and cast the result to the StudentPhoto
do type.
cu cu
ma m en m ma en
rta tb rta tb
.ba elo .ba elo
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho m a o m aB
This code riz
ed highlights
av
era Bthe
arb remove icon and slightly ridims ze
d
the
av student
e r arb photograph.
co bs os co ab os
pie s.c a. pie ss a.
sa om sa .co
m
The completedllocode we
d!
for this method should look like this: llowed
!
grid.Opacity = 1.0;
StudentPhoto photo = ((Grid)grid.Parent).Children[0] as
StudentPhoto;
photo.Opacity = 0.6;
}
Th Th
is is
do ocd
c
um um
6. mAdd
art a private
e nt
b
method named RemoveStudent_MouseLeave m art en
tb that takes an
a.b elo a.b elo
Noobject arbo and nagsMouseEventArgs parameter a
No and rreturns ng
un sa to un
bo
sa void.
st
oM
au @ M au @
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
7. In this method, co
pie
add
bs
s.c
code o sa to change the Opacity property co
pie
of the
bs
s.c
Gridos control
a.
to
sa . sa
om om
0.3 and the Opacity l l ow
ed
property of the StudentPhoto controlowtoe 1.0. This code l l
! d!
restores the photograph to its original brightness and dims the remove icon as
the mouse moves away.
The completed code for this method should look like this:
Th Th
is is
do do
cu
private void cu
RemoveStudent_MouseLeave(object sender,
ma m en ma me
rta t rta n t
.ba
MouseEventArgs be e) .ba be
lon lon
No rbo gs No rbo gs
un sa to un sa to
a
{ uth @ M a uth @ Ma
pri art pri rta
ori m a aB ori m a Ba
ze ve arb ze ve rbo
Grid d co grid rab = (Grid)sender;
os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
grid.Opacity llo
we = 0.3; llo
we
d! d!
StudentPhoto photo = ((Grid)grid.Parent).Children[0] as
StudentPhoto;
photo.Opacity = 1.0;
}
Th Th
is is
do oc d
cum um
ma en ma en
8. InrtaStudentsPage.xaml,
.ba
tb
elo in the Grid control for
r ta.
b