0% found this document useful (0 votes)
718 views

20483C - Programming in C#

Uploaded by

Afonso Macedo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
718 views

20483C - Programming in C#

Uploaded by

Afonso Macedo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 923

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!

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

document may be reproduced, stored in or introduced into a retrieval system, or


transmitted in any form or by any means (electronic, mechanical, photocopying,
recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Th Th
is is
do oc d
cum um
ma e m en
Microsoftrta may n t have
be patents, patent applications, trademarks,
a rta tb
elo
copyrights, or other
.ba lon .ba
No rbo gs No rbo n gs
intellectual
un property
sa
@ torights covering subject matter
M unin this sa document.
@ to
Ma
Except as
au p a a u p
tho rim rta tho rim rta
expressly providedriz
ed
avin any
era Bawritten license agreement from
rbo
riz Microsoft,
ed
av
era Bthe
arb furnishing of
co b s s co b s os
pie sc a . pie s.c a.
this document does s a not .give om you any license to these patents, s atrademarks, om
llo llo
we we
copyrights, or other intellectual d! property. d!

The names of manufacturers, products, or URLs are provided for informational


purposes only and Microsoft makes no representations and warranties, either
expressed, implied, or statutory, regarding these manufacturers or the use of the
T
his his T
products do with any Microsoft technologies. The inclusion
c
do
c
of a manufacturer or product
um um
doesmnota.
en
art imply
e
ma
rta
.
en
t b endorsement of Microsoft of the manufacturertb
e
or product. Links may
ba lon ba lon
No bo r gs No bo gs r
be provided
un
a
sto
a@thirdtoparty
M
sites. Such sites are notununder
a
sathe control
@ to
M
of Microsoft and
uth pri art uth pri art
ma aB m a
Microsoft isoriznot
ed responsible
ve
r
ori
arb for the contents of any linkedze siteavor
d er anyBlink
arb contained in
co ab os co ab os
pie s.c . s a pie s.c . s a
a linked site, or anys a changes
om or updates to such sites. Microsoft
s a is not
om responsible for
llo llo
ed w ed w
webcasting or any other ! form of transmission received from any linked
! site. Microsoft
is providing these links to you only as a convenience, and the inclusion of any link
does not imply endorsement of Microsoft of the site or the products contained therein.

© 2012 Microsoft Corporation. All rights reserved.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 1/10
10/28/2019 20483B - Programming in C# | Skillpipe

Microsoft and the trademarks listed at


http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/E
N-US.aspx are trademarks of the Microsoft group of companies. All other trademarks
are property of their respective owners

Product Number: 20483B


Th Th
is is
do d oc
cum um
ma nte ma en
rta rt tb
Part Number.ba (if
be applicable):
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
Released: xx/20xx e dc e 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!
Welcome!

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.

Customer Satisfaction Guarantee


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 2/10
10/28/2019 20483B - Programming in C# | Skillpipe

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!

1 IDC, Value of Certification: Team Certification and Organizational Performance,


November 2006
Th Th
is is
do d
Acknowledgments
ma
r nt
c um
e ma
en
tb
rt
oc
um
ta.be a.b elo
ba
lon a ng
No rbo
gs No rbo st
un sa t o u na s a oM
au @ Ma u @
tho p rim rta tho p rim art
riz avwantsBto riz following av a
Microsoft Learning ed era a acknowledge
rbo and thank the ed era forBatheir rbo
co b ss sa c op b ss sa
pie . . i es stages . .
contribution towards adeveloping llo
co
m this title. Their effort at various a llo
co in the
m
we we
development has ensured d! that you have a good classroom experience. d!

Lin Joyner – Content Developer


Lin Joyner is an experienced .NET Framework application developer and SQL Server
Th She has been working with the .NET Framework
expert. Th since it was first released
is is
d oc d oc
me u me LINQ, and the Entity u
and specializes
ma
r nt in data access solutions with ADO.NET,
ma
r nt
ta. be ta. be
arb on b l arb on b l
Framework.
No
u o Lin
s hasgs been writing training courses
t
No and
u
other
o s instructional
gs
t
content for
na a@ oM na a@ oM
Microsoftuthfor z
pri
ori over
v
art
ma12 years.
aB
uth
ori
ze
pri
ma
ve
art
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
John Sharp – Subject Matter Expert d! ed
!

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.

Jason Lee – Subject Matter Expert


Th Th
Jason isLee is a Principal Technologist with Content
d
is Master where he has been
d
oc oc
um um
working
m art withnMicrosoft
e
t b
products and technologies,art especially
m en
tb SharePoint, Visual C#,
a.b elo a.b elo
a rbo forngseveral a ng
and NASP.NET,
ou sa st
oM
years. Jason holds aNPhD
ou inrbocomputing
sa st
oM
and is currently
na @ na @
uth pri art uth pri art
MCPD andoriMCTS ze
macertified
ve
aB
arb
ori
ze
ma
ve
aB
arb
dc rab o dc rab os
op s s sa op s s a.
ies .co . ies .co
all m all m
ow ow
Antony Norris – Subject Matter Expert ed
!
ed
!

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

About About This Course


This
Course
Th
is
Th
is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 4/10
10/28/2019 20483B - Programming in C# | Skillpipe

Course Materials

Virtual Machine Environment

Module 1: Review of Visual C# Syntax


Module Overview
Th
Lesson
is 1
do Overview of Writing Application Tby
his Using Visual C#
do
cu cu
: ma me
n ma
me
n
rta tb rta tb
.ba elo .ba elo
No rbo ng N r b ng
un 2: sData s to o o sa st
Lesson au a @
p
Types,M a
Operators, and Expressions
un
au @
p
oM
art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co o
bs Programming sa co bs os
Lesson 3: Visual pie C#
sa
s.c
om
. Language Constructs pie
sa
s.c
om
a.
llo llo
we we
d! d!
Lab: Developing the Class Enrollment Application

Module Review and Takeaways

Module 2: Creating Methods, Handling Exceptions, and Monitoring


Applications
Th Th
is is
do
cum
Module Overview d oc
um
ma ent ma
en
rta be a.b rttb
.ba lon elo
Lesson
No 1 rbosCreating gs and Invoking Methods No a rbo ng
un 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 c o b s os
pie s.c a . pie s.c a.
Lesson 2: Creating sa
llo
Overloaded
om Methods and Using Optional sa
llo
and
om Output
we we
Parameters d! d!

Lesson 3: Handling Exceptions

Lesson 4: Monitoring Applications

Lab:Th Extending the Class Enrollment TApplication


h
Functionality
is is
do oc d
cum um
ma e ma en
rta nModule
tb
elo
Review and Takeaways r ta. tb
elo
.ba b a
No r bo n gs No r bo ng
un s t u s st
a @ o M n a @ oM
Module u3:
a
tho Developingpri
m
art the Code for a GraphicaluthApplication
a
a
o
pri
m
art
aB
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa co os
Modulepie
sa
Overview
s.c
om
. p ies s s.co a.
llo a llo m
we we
d! d!
Lesson 1 Implementing Structs and Enums
:

Lesson 2: Organizing Data into Collections

Lesson 3: Handling Events


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 5/10
10/28/2019 20483B - Programming in C# | Skillpipe

Lab: Writing the Code for the Grades Prototype Application

Module Review and Takeaways

Module 4: Creating Classes and Implementing Type-Safe Collections


Module Overview
Th Th
Lesson
is 1
do Creating Classes is
d
cu oc
: m um
ma en maen
rta tb a.b rttb
.ba elo elo
No rbo ng N arb ng
un 2: sDefining s to and Implementing Interfaces o o sa st
Lesson au a @
p M a
un
au @
p
oM
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
Lesson 3: Implementing pie
sa
s.c
om
Type-Safe
. Collections pie
sa
s.c
om
a.
llo llo
we we
d! d!
Lab: Adding Data Validation and Type-Safety to the Application

Module Review and Takeaways

Module 5: Creating a Class Hierarchy by Using Inheritance

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!
!

Module Review and Takeaways

Module 6: Reading and Writing Local Data


Module Overview
Th Th
is is
do do
um c cu
Lesson
ma 1 enReading and Writing Files ma me
rta tb r nt
. elo t a . be
: N barb
os
ng
s N
b arb
o
lon
gs
ou a@ t oM o un s a@ to
na a Ma
uth pri art uth pri rta
ori ma aB ori ma
Lesson 2: zeSerializing
dc
ve
rab and
a rbo Deserializing Data ze dc
ve rab
Ba
rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
Lesson 3: Performing o we I/O by Using Streams o we
d! d!

Lab: Generating the Grades Report

Module Review and Takeaways

Module 7: Accessing a Database


Th Th
is is
do d oc
cum Module Overview um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 6/10
10/28/2019 20483B - Programming in C# | Skillpipe

Lesson 1 Creating and Using Entity Data Models


:

Lesson 2: Querying Data by Using LINQ

Lab: Retrieving and Modifying Grade Data


Th Th
is is
do
cum
Module Review and Takeaways d oc
um
ma nt e ma en
rta be rt a.b tb
.ba lon elo
Module
No 8:rbo Accessing gs Remote Data No arb
os
ng
st
un sa to un a oM
au @ M au @
tho pri art tho p rim art
riz Module ma
v Overview
aB
arb riz av aB
arb
ed era ed era
co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
Lesson 1 Accessing l l ow Data Across the Web llo
we
ed d!
: !

Lesson 2: Accessing Data in the Cloud

Lab: Retrieving and Modifying Grade Data in the Cloud

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 2: Binding Controls to Data

Lesson 3: Styling a UI

Lab:Th Customizing Student Photographs


Th and Styling the Application
is is
do oc d
cum um
ma e ma en
rta
.ba
nModule
tb
elo
Review and Takeaways 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
a @ M a @
Module utho Improving pri
m
art Application Performanceuand
a tho Responsiveness
pri
m
art
aB
riz av Ba riz av
10: ed
co
era rbo e d co
e r ab
arb
os
pie bs sa p s a.
s.c . ies s.co
sa om a m
ModulellowOverview llo
we
ed d!
!

Lesson 1 Implementing Multitasking


:

Lesson 2: Performing Operations Asynchronously

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

Lab: Improving the Responsiveness and Performance of the Application

Module Review and Takeaways

Module Integrating with Unmanaged Code


11:
Module Overview
Th Th
is is
do d o
Lesson c cu
ma 1 menCreating and Using Dynamic Objects
u me
ma nt
rta tb r t a.b be
: .ba
r
elo
n a r
lon
No bo gs No bo gs
un sa to un sa to
au @ Ma au @ Ma
tho pri rta tho pri rta
Lesson 2: rizeManaging m av the
Ba Lifetime of Objects and m
Controlling
riz av Unmanaged
Ba
dc e rab rbo ed era rbo
sa co b sa
Resources
opie
sa
s s.c
om
. pie
sa
s s.c
om
.
llo llo
we we
d! d!
Lab: Upgrading the Grades Report

Module Review and Takeaways

Module Creating Reusable Types and Assemblies


12:
Th Th
is is
do
cum
Module Overview d oc
um
ma ent ma en
rta be rt a.b tb
.ba lon elo
Lesson
No 1 rbosExamining gs Object Metadata No arb ng
un to un osst
a@ M a @ oM
: a 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 b s os
ies s.c a. pie s.c a.
Lesson 2: Creating all and o m Using Custom Attributes sa
llo
om
ow we
ed d!
!
Lesson 3: Generating Managed Code

Lesson 4: Versioning, Signing, and Deploying Assemblies

Lab: Specifying the Data to Include in the Grades Report


Th Th
is is
do
cum
Module Review and Takeaways um
d oc
ma ent ma en
rta be a.b rt tb
.ba lon elo
Module
No r bo Encrypting gs and Decrypting DataNo a r bo ng
st
u s a t o u s a oM
13: n au
tho
@
pri M art
n a uth @
pri art
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
Module
co Overview
bs sa co ab os
pie s.c . p ies s s a.
sa om .co
llo a llo m
we we
Lesson 1 Implementing Symmetric Encryption d ! d!

Lesson 2: Implementing Asymmetric Encryption

Lab: Encrypting and Decrypting the Grades Report


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 8/10
10/28/2019 20483B - Programming in C# | Skillpipe

Module Review and Takeaways

Course Evaluation

Lab Module 1: Review of Visual C# Syntax


Answer
Key:
Lab:This Developing the Class EnrollmentThiApplication
s
do do
cum cu
ma e m me
Lab rta.b Module n 2: Creating Methods, Handling nt
a.b Exceptions, and Monitoring
tb a r t be
elo lon
Answer
No arbo Applications
ng N a r b g
s st ou os st
Key: unauth a@pri o Mart na
uth
a@
pri
oM
art
ori ma aB ori ma aB
ze ve arb zed vera arb
dc rab o os
Lab: Extending
op
ies s s the
.co
Class
sa
. Enrollment Application co Functionality
p ies
bs
s .co a.
all m all m
ow ow
e ed
Lab Module 3:d!Developing the Code for a Graphical Application !
Answer
Key:
Lab: Writing the Code for the Grades Prototype Application

Lab Module 4: Creating Classes and Implementing Type-Safe


T
Answerhis Collections Th
is
do do
Key: cu
m
cu
m
ma en ma en
rta tb rta tb
.ba elo .ba el
Lab:No rbo Adding n gs Data Validation and Type-Safety No rbo to othe ng Application
st
un sa t o u na s a oM
au @ Ma u @
tho prim rta tho p rim art
riz av B riz av aB
Lab eModule
dc era5: Creating a rbo a Class Hierarchy byedUsing c
eraInheritance
arb
os
o b s s o b s
Answer pie
sa
s.c
om
a . pie
sa
s.c
om
a.
Key: llo
we
llo
we
d! d!
Lab: Refactoring Common Functionality into the User Class

Lab Module 6: Reading and Writing Local Data


Answer
Key:
Lab:This Generating the Grades Report Th
is
do d oc
cum um
ma ent ma e
Lab ta.b Module
r be
l o
7: Accessing a Database a.b nt belo rt
arb ng arb ng
Answer
No
un os
a
st
o
No
u os
a
st
oM
@ M n @
Key: auth
ori
pri
ma
art
aB
a uth
ori
pri
ma
art
aB
ze ve a rbo ze ve arb
dc rab dc rab os
Lab: Retrieving
op s s and sModifying
a Grade Data o p s s a.
ies .co . ies .co
all m all m
ow ow
ed ed
Lab !
Module 8: Accessing Remote Data !
Answer
Key:
Lab: Retrieving and Modifying Grade Data in the Cloud

Lab Module 9: Designing the User Interface for a Graphical Application


Th Th
Answeris
do
is
do
Key:m cume m
cu
me
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 9/10
10/28/2019 20483B - Programming in C# | Skillpipe

Lab: Customizing Student Photographs and Styling the Application

Lab Module 10: Improving Application Performance and


Answer Responsiveness
Key:
Lab: Improving the Responsiveness and Performance of the Application
Th Th
Lab is doc Module 11: Integrating with Unmanaged
is
do
cu
Code
um
Answer
ma en ma me
nt
Key: rta.bar t belon rta
.ba
r
be
lon
No bo gs No bo gs
un sa to un sa to
@ M @ Ma
Lab: autho Upgrading
pri
m
art the Grades Report
a
au
t h 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 .
Lab Module s a 12: oCreating
llo m Reusable Types and Assemblies
sa
llo
om
Answer we
d!
we
d!
Key:
Lab: Specifying the Data to Include in the Grades Report

Lab Module 13: Encrypting and Decrypting Data


Answer
Key:T Th
his is
do d o
c cu
Lab:ma umenEncrypting and Decrypting the Grades
ma meReport
n
rta tb rta tb
.ba elo .ba elo
No rbo ng No rbo ng
un 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 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 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

About This Course

This section provides a brief description of the course, audience, suggested


hisT Th
prerequisites,
do and course objectives. is
d oc
cu um
ma me ma en
rta nt rt tb
.ba belo a.b elo
No rbo ng N arb ng
Course Description
un
au
tho
sa
@
p
s to
M a
o un
au
tho
o sa
@
p
st
oM
art
rim rta rim aB
riz av B arb r iz a v arb
ed era ed era
This training course co o the programmingcoskills osrequired for
pie teachesbs
s.c sdevelopers
a. pie that
bs are
s.c a.
sa om sa om
llo llo
developers to create Windows we
d! applications using the Visual C# language. we
d! During
their five days in the classroom students review the basics of Visual C# program
structure, language syntax, and implementation details, and then consolidate their
knowledge throughout the week as they build an application that incorporates several
features of the .NET Framework 4.5.
Th Th
is is
do d oc
cum um
Audience
ma
rta nt
b
e
a.b
ma
rt
en
tb
.ba elo elo
No rbo n gs No a rbo ng
un sa t u s st
o a oM
This course
au
tho
is @intended
prim
Ma for experienced developers
rta
na who already
u tho
@
p rim
have
art programming
riz av Ba r a a Ba
ize ve
experience inedC, co C++,
era JavaScript,
b s
rbo
s Objective-C, Microsoft d Visual
co raBasic®,
b s
rbo or Java and
sa
pie s.c a . pie s.c .
sa om sa om
understand the concepts llo
we
of object-oriented programming. llo
we
d! d!

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
! !

o Arithmetic operators to perform arithmetic calculations involving one or more


variables.

o Relational operators to test the relationship between two variables or


Th Th
is
expressions. is
do do
cu cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
lon
oNoLogical rbo operatorsn gs to combine expressionsNothat contain rbo relational
gs operators.
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 arusing
• How to create ed
co theracode
e
b syntax
rbo
s
for simple programming ed statements
c o
era
b bo
sa
Visual
pie s s.c a . pie s s.c .
sa om sa om
C# language keywords llo
we
and recognize syntax errors by using llothe Visual
we
Studio
d! d!
IDE.

• How to create a simple branching structure using an if statement.

• 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

• How to sort data in a loop.

• How to recognize the classes and methods used in a program.

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!

• Implement the basic structure and essential elements of a typical desktop


application.

• 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!

• Integrate unmanaged libraries and dynamic components into a Visual C#


application.

• 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

• Encrypt and decrypt data by using symmetric and asymmetric encryption.

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 4, “Creating Classes and Implementing Type-Safe Collections"

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 9, “Designing the User Interface for a Graphical Application"

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!

Module 13, “Encrypting and Decrypting Data"

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

The following materials are included with your kit:

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.

• Lab Answer Keys: provide step-by-step lab solution guidance.

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.

Student Course files: includes the Allfiles.exe, a self-extracting executable file


Ththat contains all required files for the labs Tand his demonstrations.
is
do 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
Note: @ @
tho Forprthis version of the Courseware on Prerelease pri Software, Allfiles.exe
au M art au Ma
im a t h o m rta
riz av B r iz a v B
file is not ed available.
co
era
bs
However,
arb
os this file will be published ed
co
whenera the
bs
arbnext (B)
os
pie s.c a. pie s.c a.
version of this s a course
llo
om is released, and students who have s a taken
llo
om this course
we we
will be able to download d! the Allfiles.exe at that time from the d!
http://www.microsoft.com/learning/companionmoc site.

• 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!

Virtual Machine Environment

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
! !

Course Hardware Level


To ensure a satisfactory student experience, Microsoft Learning requires a minimum
equipment configuration for trainer and student computers in all Microsoft Certified
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/20a6287e-a599-4ecc-be43-11a90126e874 7/8
10/28/2019 20483B - Programming in C# | Skillpipe

Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft


Learning Product courseware is taught.

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

• Super VGA (SVGA) 17-inch monitor

• Microsoft Mouse or compatible pointing device


Th Th
is is
do d oc
• Sound ucardc with amplified speakers um
ma me ma en
rta nt rt tb
.ba belo a.b 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
*Striped c op b s s.c
os
a. co
pie b s s.c
os
a.
ies o sa om
all m llo
ow we
ed d!
!
In addition, the instructor computer must be connected to a projection display device
that supports SVGA 1024 x 768 pixels, 16 bit colors.

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
! !

Lesson 3: Visual C# Programming Language Constructs

Lab: Developing the Class Enrollment Application

Module Review and Takeaways


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
Module Overview
au
tho
riz
ed
pri
m av
era
rta
Ba
rbo
au
tho
riz
ed
p rim
av
era
art
aB
arb
co b ss. sa co b s os
pie . pie s.c a.
sa co sa om
llo m llo
we we
d! d!
The Microsoft® .NET Framework version 4.5 provides a comprehensive development
platform that you can use to build, deploy, and manage applications and services. By
using the .NET Framework, you can create visually compelling applications, enable
seamless communication across technology boundaries, and provide support for a
wide range of business processes.
Th Th
is d is d
oc oc
um um
ma en ma en
rta t r ta. features tb
In this module,
.ba beyou will learn about some of the core
lon ba elo provided by the .NET
ng
No r bo gs No rbo st
u sa to u sa o M some of the core
Frameworkn au
tho
and @
priMicrosoft M art Visual Studio®. You will n also
auth learn
@
pri about art
riz m av a Ba o riz m av aB
Visual C#® constructs e dc e rab thatrbenable you to start developing e d .NET e r Framework arb
op os co a bs os
ies s s .co a . p ies s .co a.
applications. all
ow
m all
ow
m
ed 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.

• Use basic Visual C# data types, operators, and expressions.

• Use standard Visual C# constructs.


Th Th
is d is d
oc oc
um um
ma en ma en
rta t rta tb
Lesson 1 : Overview of Writing Application by Using
No
un
.ba
rbo
sa
be
lon
gs
to
No
un
.ba
rbo
sa
elo
ng
st
oM
au @ Ma au @
Visual C# tho
riz
ed
pri
m av
era
rta
Ba
rbo
tho
riz
ed
p rim
av
era
art
aB
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!
The .NET Framework 4.5 and Visual Studio provide many features that you can use
when developing your applications.

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.

• Describe the key features of Visual Studio 2012.

• Describe the project templates provided in Visual Studio 2012.


T
his Th
• Createdo a .NET Framework application. is d
c 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
What Is the .NET Framework?
ze
dc
ve
rab
Ba
rbo
sa
riz
ed
co
av
era
bs
arb
os
op ss. . pie s.c a.
ies co sa om
all m llo
ow we
ed 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
The .NET au Framework
tho prim
M 4.5
a rta provides a comprehensive au development
tho p rim art platform that offers
riz av B r a aB
ed era arb i z ed v era arb
a fast and efficient co
pie
way bs to build
o sa applications and services. coBypie
using bs Visual os Studio
a.
s.c . s.c
s om sa om
2012, you can use athe llo .NET
we Framework 4.5 to create a wide range
llo
we of solutions that
d! d!
operate across a broad range of computing devices.

The .NET Framework 4.5 provides three principal elements:

• 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!

The .NET Framework Class Library


The .NET Framework provides a library of reusable classes that you can use to build
applications. The classes provide a foundation of common functionality and
constructs that help to simplify application development by, in part, eliminating the
need to constantly reinvent logic. For example, the System.IO.File class contains
functionality that enables you to manipulate files on the Windows file system. In
addition to using the classes in the .NET Framework class library, you can extend
Th Th
these iclasses
sd
oc
u
by creating your own libraries of is d
classes.
oc
u
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
Development Frameworks
un
au
tho
sa
@
pri
o M art
n au
t
a @
pri
to
Ma
m a h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
The .NET Framework c bprovides a. several development frameworks c b that
o pie s s.c s o pie ss.c you sa
. can use to
sa om sa om
llo llo
build common application we
d! types, including:
we
d!

• Desktop client applications, by using Windows Presentation Foundation (WPF).

• Windows 8 desktop applications, by using XAML.

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!

Key Features of Visual Studio 2012


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
Visual Studio
au
tho 2012
prim provides
M a rta a single development aenvironment
u tho p rim that
art enables you to
riz av B r a aB
ed era arb i z ed v era arb
rapidly design, coimplement,
pie bs build,
o sa test, and deploy various types
co
pie
ofbs applications
os
a.
and
s.c . s.c
sa om sa om
components by using llo a range
we of programming languages. llo
we
d! d!

Some of the key features of Visual Studio 2012 are:

• 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!

Templates in Visual Studio 2012


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!

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

project to meet your own requirements.

The following steps describe how to create a console application:

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
!

b. Click the Console Application template.

c. In the Name box, specify a name for the project.


d. In the Location box, specify the path where you want to save the project.

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!

Programmer Productivity Features


Visual Studio 2012 provides a host of features that can help you to write code. When
writing code, you need to recall information about many program elements. Instead of
manually looking up information by searching help files or other source code, the
IntelliSense feature in Visual Studio provides the information that you need directly
from the editor. IntelliSense provides the following features:

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#.

• Create and use expressions.


• Declare and assign variables.

• Access type members.

• Cast data from one type to another.

• Concatenate and validate strings.


Th Th
is d is d
oc oc
um um
ma en ma en
rta bet rta tb
.ba lon .ba elo
No rbo gs No rbo ng
What are Data Types?
un
au
sa
@
pri
to
Ma un
au
sa
@
p
st
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
llo llo
we we
d! d!

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!

Commonly Used Data Types


The following table shows the commonly used data types in Visual C#, and their
characteristics.
T Th
his is d
do oc
cu um
ma me ma en
rta nt rta tb
.ba be .ba elo
lon ng
Type
No rbo Description
gs Size No Range rbo st
u na s 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
dc rab co bs os
op ss. sa
ies co . (bytes) pie
sa
s.c
om
a.
all m llo
ow we
ed d!
!
int Whole numbers 4 –2,147,483,648 to 2,147,483,647

long Whole numbers 8 – 9,223,372,036,854,775,808 to


(bigger range) 9,223,372,036,854,775,807
Type Description Size Range

(bytes)

float Floating- point 4 +/–3.4 × 10^38


numbers
Th Th
i is d
doubles doc Double precision 8 +/–1.7
oc × 10^308
um um
ma en (more accurate) ma en
rta be t rta tb
.ba lon .ba elo
No rbo floating-
gs point No rbo ng
un sa to un sa st
@ M @ oM
au prinumbers art au p art
tho ma aB tho rim aB
riz v arb riz av arb
ed era ed era
co bs os co bs os
decimal pMonetary
ies s values
.co a. 16 28 significant pifigures
es s .co a.
all m all m
ow ow
ed ed
char Single character! 2 N/A !

bool Boolean 1 True or false

DateTime Moments in time 8 0:00:00 on 01/01/2001 to 23:59:59 on


12/31/9999

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!

Expressions and Operators in Visual C#

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!

Comparison ==, !=, <, >, <=, >=, is

String concatenation +

Logical/bitwise operations &, |, ^, !, ~, &&, ||


Th Th
is is d
Indexingdo(counting
cu starts from element 0) [] oc
um
ma me ma en
rt nt rta tb
a.b be .ba elo
Casting arb lon ( ), as ng
No o gs No rbo st
un s a@ to un s a oM
a uth M au @
pri art tho p rim art
Assignmentorize m aB =, +=, -=, *=, r/=, a B<<=, >>=, ??
av
era arb ize %=, &=, av |=, ^=,
era arb
dc bs os dc bs os
op s.c a. op s.c a.
ies om ies o
Bit shift all <<, >> all m
ow ow
ed ed
! !
Type information sizeof, typeof

Delegate concatenation and removal +, -

Overflow exception control checked, unchecked

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.

The following code example shows how to use the + operator.


+ Operator

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

"ApplicationName: " + appName.ToString()

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.

Declaring and Assigning Variables


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
@ Ma @ 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!

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
!

naming convention and use it!


Declaring and Assigning Variable
When you declare a variable, you reserve some storage space for that variable in
memory and the type of data that it will hold. You can declare multiple variables in a
single declaration by using the comma separator; all variables declared in this way
have the same type.
Th Th
is d is d
oc oc
um um
The following
ma en example shows how to declare a new
ma variable.
en
rta tb rta tb
.ba elo .ba elo
No rbo ng No rbo ng
un sa st un sa st
@ oM @ oM
au p art au pri art
t
Declaringoariz Variable
h r ima aB th ori ma aB
ed v era arb zed ve arb
co bs os co rab os
pie s.c a. p ies ss. a.
sa om c om
llo all
we ow
d! ed
!
// DataType variableName;
int price;
// OR
// DataType variableName1, variableName2;
intThiprice,
s tax; 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
un s a t o u na to it @ s a oM
After you au declare
tho
@
prim a variable,
Ma
rta
you can assign a value u tho byp using
rim aran
ta
assignment
riz av B arb r ize a ve B
statement. You ed can echange
co rab othe value in a variable as many d c times rab as ayourbo want during
pie s s.c s a o pie ss. sa
sa . sa co .
om m
the running of the application. llo
we The assignment operator = assigns llo a value to a
we
d! d!
variable.

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.

The Tfollowing code example declares an int named


T
price and assigns the value 10.
his his
do do
cu cu
ma me ma me
rta nt rta nt
Declaring be Assigning Variables
.ba and .ba be
lon lon
No r bo gs No rbo gs
u na sa to un sa to
uth @ Ma au @ Ma
pri rta tho pri rta
ori mav Ba riz m av Ba
ze era rbo ed era rbo
dc bs co b
op s.c sa pie ss.c sa
ies . sa .
om om
int price = 10;all ow llo
we
ed d!
!

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! !

ServiceConfiguration config = new ServiceConfiguration();

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

ServiceConfiguration class exposes.

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!

// Set the .DatabaseServerName property.


config.DatabaseServerName = "78.45.81.23";
// Invoke the SaveConfiguration method.
var saveSuccessful = config.SaveConfiguration();

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!

Casting Between Data Types

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!

• Implicit conversion, which is automatically performed by the CLR on operations


that are guaranteed to succeed without losing information.

• Explicit conversion, which requires you to write code to perform a conversion that
otherwise could lose information or produce an error.

Th conversion reduces the possibility of bugs


Explicit Th in your code and makes your code
is do is do
um c um c
moremefficient.
a en Visual C# prohibits implicit conversions
t
ma ethat
nt lose precision. However,
rta be rta be
athat on.b l arb on .b l
be aware
No rbo some
s
gs explicit conversions can yield
t
No unexpected
os gs results.
t
un a@ oM un a@ oM
au pri art au pri art
tho m aB th ori ma aB
riz av arb z ve arb
ed era ed rab
co bs os co os
Implicit Conversions
pie
s
s.c
om
a. p ies ss.
com
a.
all all
ow ow
ed ed
! !
An implicit conversion occurs when a value is converted automatically from one data
type to another. The conversion does not require any special syntax in the source
code. Visual C# only allows safe implicit conversions, such as the widening of an
integer.

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

sbyte short, int, long, float, double, decimal

byte short, ushort, int, uint, long, ulong, float, double,


decimal

shortTh int, long,


Th float, double, decimal
is d is d
oc oc
um u
ma
ushort en ma long,mulong,
int, uint, en float, double, decimal
rta be t rta t be
.ba lon .ba lon
No rbo gs No rbo gs
int un sa to un double,
long, float, sa decimal 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
uint co b s sa long, ulong, float, double,
co decimal
b s sa
pie s.c . pie s.c .
sa om sa om
llo llo
long, ulong we float, double, decimal we
d! d!

float double

char ushort, int, uint, long, ulong, float, double, decimal

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.

Conversions by Using the as Operator

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!

string possibleInt = "1234";


int count = Convert.ToInt32(possibleInt);
Some of the built-in data types in Visual C# also provide a TryParse method, which
enables you to determine whether the conversion will succeed before you perform
the conversion.

The Tfollowing code example shows how to convert


T
a string to an int by using the
his his
do
int.TryParse() method. do
cu 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
TryParse au Conversion
tho
@
pri Ma
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!
int number = 0;
string numberString = "1234";
if (int.TryParse(numberString, out number))
{
// Conversion succeeded, number now equals 1234.
Th Th
is d is d
} oc oc
um um
ma en ma en
t tb
else rta.ba be
lon
rta
.ba elo
No rbo gs No rbo ng
un s to un s st
{ a@ Ma a@ oM
au p au p art
tho rim rta tho rim aB
ize r ve failed, arb a B riz av arb
// Conversion
dc rab os number now equals 0.ed c era
bs os
op s s.c a. op s.c a.
ies om ies o
} all all m
o we ow
d! ed
!

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!

string address = "23";


address = address + ", Main Street";
address = address + ", Buffalo";
Th Th
is d is d
oc oc
um um
ma en ma en
rta bet r ta. tb
.ba lon ba elo
An alternative
No r bo approach
sa
gs is to use the StringBuilder
No class,
rbo
sa
which
ng
st enables you to build
un @ to u n @ oM
au pri M art much more efficiently. auth pri art
a string dynamically
tho
riz ma and aB ori ma aB
ed ve a rbo z e v e arb
co ra bs d co ra bs os
pie s.c sa p s a.
sa . ies .co
om a m
llo llo
The following code example we shows how to use the StringBuilder we class.
d! d!

Concatenation by Using the StringBuilder Class


StringBuilder address = new StringBuilder();
address.Append("23");
address.Append(", Main Street");
address.Append(", Buffalo");
string concatenatedAddress = address.ToString();

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!

Lesson 3: Visual C# Programming Language


Constructs
Th Th
is d is d
oc oc
When ma
developing
u me an application, you will often need m
uto
meexecute logic based on a
rta n t a r nt
b
.ba or toerepeatedly t a.bauntilba elocondition is met. You may
condition,
No rbo
lon
gs
execute a section of logic
No rbo ng
un s t u s st
a @ o Ma na a@ oM
also want au to store
tho prim a collection
rta of related data in a singleu tho variable.
p rim aVisual
rta C# provides
riz av B a riz av B a
ed era rbo ed era rbo
a number of constructs co
pie bs than
s.c senable
a. you model complex behavior co
pie bsin your
s.c saapplications.
sa sa .
om om
llo llo
we we
d! d!
In this lesson, you will learn how to implement decision and iteration statements and
how to store collections of related data. You will also learn how to structure the API of
your application by using namespaces, and how to use some of the debugging
features that Visual Studio provides.
Th Th
is d is d
oc oc
Lesson
ma
rt
Objectives
en
tb
um
ma
rta
um
en
tb
a.b elo .ba elo
No arb ng No rbo ng
os st s
After completing
nau
uth
a@ this
pri
oM lesson,
art
you will be able to: unau sa@p to Ma
ori ma aB tho rim rta
ze ve arb riz av Ba
dc rab ed era rbo
op s os co b ss. sa
ies s .co a. pie .
sa c om
• Use conditional statements. all m llo
ow we
ed d!
!

• Use iteration statements.

• Create and use arrays.


• Describe the purpose of namespaces.

• Describe some of the features provided by the Visual Studio debugger.

Implementing Conditional Logic


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
@ Ma @ 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!

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!

Implementing Iteration Logic

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

for (int i = 0 ; i < 10; i++)


{ T Th
his is d
do oc
// cuCode to execute.
me um
ma nt ma en
rta 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 sabs co b s os
pie s.c . pie s.c a.
In this example, i =s a0; is the om initializer, i < 10; is the expression, s a and oi++;
m is the
llo llo
we we
iterator. d! d!

For Each Loops


While a for loop is easy to use, it can be tricky to get right. For example, when
iterating
Th
i
over a collection or an array, you have Tto
hi know how many elements the
sd sd
oc oc
collection
ma
uor
me array contains. In many cases this m is straightforward,
um
en but sometimes it
rta n tb art tb
.ba e a e
.ba betterlo to use a foreach loop.
can Nbe easy rbo to get
lon wrong. Therefore, it is sometimes
gs No rbo ng
st
ou s a@ t oM un sa oM
na a @
uth pri art uth pri art
ori ma aB ori ma aB
ze ve a rbo z e v e arb
dc rab dc rab os a string
The following code op
ies example
s s .co
sshows
a . how to use a foreach loop
o p ies to iterate
ss .co a.
all m all m
array. ow ow
ed ed
! !

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.

The following code example shows how to use a while loop.


Th Th
is d is d
while Loopo cu oc
me um
ma n m a 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 rta tho rim aB
riz av B a riz av arb
bool dataToEnter e d e r rb
ab= CheckIfUserWantsToEnterData(); e d e rab
co s os co s os
pie s.c a . pie s.c a.
sa om sa om
while (dataToEnter) llo
we
llo
we
d! d!
{
// Process the data.
dataToEnter = CheckIfUserHasMoreData();
}

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.

The following code example shows how to 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.

• Arrays can be single-dimensional, multidimensional, or jagged.


Th Th
is d is d
oc oc
• The
m rank
um of an array is the number of dimensions uin
en m methe array.
n
art tb art 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
riz av B arb r i z a v arb
ed era ed era
Arrays of a particular co
pie btype
ss. can o sa only hold elements of that type.
.
co
p i e
If byou
ss .
needos to
a.
sa c om sa c om
llo llo
manipulate a set of unlike we
d!
objects or value types, consider using wone ed of the collection
!
types that are defined in the System.Collections namespace.

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: ! !

• Single-dimensional arrays. To declare a single-dimensional array, you specify the


type of elements in the array and use brackets, [] to indicate that a variable is an
array.
T
Later, you specify the size of the arrayTwhen you allocate memory for the
his his
arraydobym
do
cu using the new keyword. The size of an array
cu
m
can be any integer
ma en ma en
rta tb t
expression.
.ba eThe
lo following code example showsrtahow
.ba tobecreate
lo a single-
No rbo ng No rbo ng
u sa st u sa st
dimensional
n @ array o Mof integers with elements zero n through @ oM
nine.
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 a m
llo llo
int[] arrayName we = new int[10]; we
d! d!

• 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");

ThAdditional Reading: For more information Th about namespaces, see the


is d is d
namespace
oc
um
(C# Reference) page at http://go.microsoft.com/fwlink/?
oc
um
ma e m en
LinkID=267780.
rta nt
b elo
art
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 av B arb r i z a v arb
ed era ed era
co bs o co bs os
Debugging by Using Visual Studio 2012
pie
sa
s.c
om
sa
. pie
sa
s.c
om
a.
llo llo
we we
d! 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 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.

Menu item Toolbar button Keyboard Description


Th Th
is d is d
oc shortcut oc
um um
ma en ma en
rta be t rta tb
.ba lon Start/continue .ba elo
Start
NoDebuggingrbo gs F5 No rbo This
ng button is available when
un sa to un sa st
@ Ma @ oM
au au
tho pri
m rta tho p rim application
your art
aB
is not running
riz av Ba riz av arbare in break
ed era rbo ed and ewhen rab you
co b s sa co s os
pie
sa
s.c
om
. pmode.
ies s .co starta.your
It will
llo all m
we ow
d! application ed in Debug mode or
!
resume the application if you
are in break mode.

Break All Break all Ctrl+Alt+Break This button causes application


processing to pause and break
mode to be entered. The button
Th Th
is d is d is available when an application
oc oc
um um
ma en ma en is running.
rta be t rta tb
.ba lon .ba elo
No rbo gs N rbo ng
Stop Debugging
un s Stop
to Shift+F5 o un sa Thiss t button stops debugging. It
a@ Ma @ oM
au pri au p art
tho m rta tho rim a Bwhen an application
riz av Ba riz is aavailable
v
ed era rbo ed era arb
co b sa co is running b os break mode.
pie ss.
co . pie ss.c is in
or a.
sa m sa om
llo llo
we we
Restart Restart d! Ctrl+Shift+F5 This button d! is equivalent to stop
followed by start. It will cause
your application to be restarted
from the beginning. It is
available when an application is
running or is in break mode.
Th Th
is is d
Step Intodoc Step into F11 oc This button is used for stepping
um um
ma en ma en
rta be t rta t b into method calls.
.ba lon .ba elo
No rbo gs No rbo ng
u s to u sa st
na
Step Over a@ n obutton
pri Step Ma over F10 This is used for stepping
uth au @ Ma
rta tho pri rta
ori ma Ba riz m a B
ze
dc
ve
rab rbo ed over ve methodarcalls.
rab bo
op ss. sa co ss. sa
ies co . pie c .
sa om
Step Out llo outm
aStep Shift+F11 Thisllbutton
ow is used for
we ed
d!
executing! the remaining code in
the method and returning to the
next statement in the calling
method.
Additional Reading:

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.

• Perform simple data transformations for displaying information.


Th Th
is d is d
oc oc
um um
ma en ma en
rta t b rta tb
.ba elo .ba elo
Estimated
No rbTime:
o
n45
gs minutes No rbo ng
st
un sa to un s a oM
au @ Ma au @
tho pri rta tho p rim art
riz mav Ba riz av aB
ed era rbo ed era arb
c os
• Virtual Machines:
op b
ies 20483-SEA-DEV11-01,
ss.
co
sa
. MSL-TMG1 copie bs
s.c a.
all m sa om
ow llo
ed we
! d!
• User Name: Student

• 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.

The main tasks for this exercise are as follows:

1. ThDetect whether the user has pressed the Enter Th key


is d is d
oc oc
um um
ma en ma e
2. Initialize
rta t bthe
elo StudentForm window and populate rta it nwith t b the details of the
elo
.ba .ba
No rbo ngs No rbo ng
st
currently
un
au
s a @ selected t o Ma student 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 StudentForm b co b os
3. Display the pie s s.c s a . window and copy the updated pie student ss.c details a. entered
sa om sa om
llo llo
back to the Student we object
d!
we
d!

4. Run the application and verify that the edit functionality works as expected

5. Use the Visual Studio Debugger to step through the code.

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!

the password Pa$$w0rd.

3. Start Visual Studio and from the E:\Labfiles\Starter\Exercise 1 folder, and then
open the School.sln solution.

4. In the code for the MainWindow.xaml.cs window, find the


studentsList_KeyDown method.

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. !

The initial students list should look like this:

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!

FIGURE 01.1: THE INITIAL STUDENTS LIST

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! !

5. Verify that the Save Changes button is now enabled.

6. Close the application.

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!

2. Debug the application.

3. Edit the row for George Li.

4. ThWhen Visual Studio enters break mode, open Th


is d is d the Watch 1 window and
oc oc
um um
mpopulate
art e n the grid with a row for each of them following:
a en
a.b t be r ta. tb
l o b elo
No a r bo ngs No a rbo ng
un sa to u sa st
o aut sf.Title @ M n @ oM
pri art auth pri art
ho m a o m aB
riz av Ba riz av arb
ed era rbo e d e ra
co bs sa co bs os
p s p s a.
o sf.firstName.Text
ies
all
.co
m
. ies
all
.co
m
ow ow
ed ed
! !
o sf.lastName.Text

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.

5. Step over the next code statement four times.

6. ThUse the Immediate Window to view the value


is d
Th
is d of sf.firstName.Text and to
oc oc
um um
mverify
art
that
e nt it contains the value George. 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
riz av B r i z a v
Note:ed
co
Whenera
bs
Visual
arb
o Studio enters break mode, ed the Immediate
co
era
bs
arb
os Window
pie s.c sa pie s.c a.
.
automatically sa
llo
oappears
m in the tab group in the bottom s a middle
llo
om window
we we
d! d!

7. In the Watch 1 window, change the value George to Dominik.

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.

Exercise 2: Implementing Insert Functionality for the Students List


Th Th
is d is d
oc oc
um um
ma en ma en
rta b t r t a tb
. e . elo
Scenario
No
ba
rbo
lon
gs No
ba
rbo ng
un sa to un sa st
@ M @ oM
au p a au p art
tho rim rta tho rim aB
In this exercise, riz
ed you av will write
era B arb code that enables an administrator
r i z ed
a v era using arb the
co b s o s c o b s os
pie s.c a. pie s.c a.
application to add a
sa new student
om to the students list. sa om
llo llo
we we
d! d!

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.

The Tmain tasks for this exercise are as follows: T


his his
do do
cu um c
ma me ma en
rta nt r tb
1. Add.balogic beto the key down method to detect iftathe .ba Insert elo key has been pressed.
lon ng
No r bo gs No rbo st
un sa to u n sa oM
au @ M auth @
tho pri art pri art
m a o m aB
2. Initialize riz the student
ed
av
era Baform
rbo
riz
e d
av
e r arb
co bs sa co a bs os
pie s.c . p ies s .co a.
sa om a m
llo llo
3. Display the StudentForm we
d!
window and enable the user to provide we
d!
the details of
the new student

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.

Th Note: You can use code similar to the


Th following to create the string for
is d is d
oc
um
the Title property. oc
u
ma en ma me
rta t rta nt
.ba be .ba be
lon lon
No rbo gs No rbo gs
un s a@ to un s 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
"New Student for Class llo
we " + teacher.Class llo
we
d! d!
Task 3: Display the StudentForm window and enable the user to provide the
details of the new student

1. Display the StudentForm window by using the ShowDialog method.

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.

3. Enable the Save Changes button in the user interface.

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.

The main tasks for this exercise are as follows:

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!

The confirmation prompt should look like this.


Th his T
FIGURE
is d
o 01.3: PROMPT TO CONFIRM THE dDELETION
o OF A STUDENT.
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 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
Task 3: Removeiethe p s p s
s a student .co
m
.and enable the user to saveiesthe all
changes
.co
m
.
llo ow
we ed
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.

3. Delete the student Jon Orton from class 4B.


Th Th
is d is d
4. Verify
oc that the prompt window appears, the student
u
oc
u
is removed from the list, and
ma me ma me
rta thentSave
that be Changes button is enabled. rta nt
be
.b arb l on .ba lon
No os gs No rbo gs
u na a@to un s a@ to
uth pri Ma au pri Ma
5. Closeorithe
ze
application.
ma rta
Ba
tho
riz ma rta
Ba
ve rbo ed ve rbo
dc rab co rab
op ss. sa pie ss. sa
ies co . sa c .
om
6. In Visual Studio, all close
ow
m the solution. llo
we
ed d!
!
Results: After completing this exercise, users will be able to remove students from
classes.

Exercise 4: Displaying a Student’s Age


Th Th
is d is d
oc oc
um um
ma en ma en
rta be t rta tb
.ba .ba elo
Scenario
No rbo
lon
gs No rbo ng
un sa to un sa st
@ Ma @ oM
au pri au p art
tho m rt tho rim
In this exercise, av willaupdate aB
ed you the application to display
riz Ba riz a student’s
av aage instead of
era rbo ed era rbo
co b s sa co b s s a.
pie s.c . pie s.c
their date of birth. s a om sa om
llo llo
we we
d! d!

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!

1. Examine the MainWindow XAML

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.

3. View the MainWindow.xaml code.

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
! !

Note: You can use the DateTime.Now.Subtract method to subtract the


date of birth from the current date and store the result in a TimeSpan
object. You can use the TimeSpan.Days method to retrieve the
difference in days and then use the following formula to calculate the
Th Th
is d
oc
age in years from this difference. is d
o
um cu
ma en ma me
rta t rta nt
.ba be .ba be
lon lon
No rbo gs No rbo gs
una s 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 rab rbo ed rab rbo
op ss. sa co ss. sa
ies c . pie c .
Age in years = difference all o in
m days / 365.25 sa
llo
om
ow we
ed d!
!

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

1. Build the solution and resolve any compilation errors.


Th Th
is d is d
2. Runcuthe
o
me
application and verify it displays the initial
oc
um list of students, with their
ma n m a en
rta tb rta tb
ages. .ba elo
ng
.ba elo
ng
No rbo s N o rb o st
un sa to un sa oM
au @ M au @
t pr a r t p r art
The student
h ori
ze
imlist
av should
taB
arb
now look similar to the following:
h ori
z
i ma
v
aB
arb
dc era ed era
op bs o sa co bs os
ies s .co . p ies s .co a.
all m all m
ow ow
ed ed
! !

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.

4. Close the application.

5. ThIn Visual Studio, close the


is d
solution. Th
is d
oc oc
um 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
Results:thoAfter riz completing
m av a B this
arb
exercise, the tho
application riz will mdisplay
av a Ba student’s
arb
age
ed era ed era
in years. co bs os co bs os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
d! d!

Module Review and Takeaways


Module Review
In this module, you learned about some of the core features provided by the .NET
Framework and Microsoft Visual Studio®. You also learned about some of the core
Visual C#® constructs that enable you to start developing .NET Framework
applications.
Th Th
is d is d
oc oc
um um
Test mYour
a
Knowledge
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
au p a au p art
tho rim rta tho rim aB
riz av B r i a
Question ed era arb
o
z ed v era arb
os
co bs sa co bs a.
pie s.c . pie s.c
sa om sa om
llo llo
What Visual Studio template we would you use to create a .dll? we
d! d!

Select the correct answer.

Console application

Windows Forms application


Th Th
is WPF
do application is d
cu oc
m um
ma en ma en
rtClass
a.b tb
library rta tb
elo .ba elo
No a rbo ng No rbo ng
un s st un s st
a@ oM a@ oM
au
WCF Service p art
application 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
Verify the correctness llo of the statement
we by placing a mark in thellocolumn we to the right.
d! d!

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++;
}

Th the correct answer.


Select Th
is do is d
cu oc
me um
ma nt ma en
rt3a be rta tb
.ba lon .ba elo
No rbo gs No rbo ng
un sa to un sa st
@ Ma @ oM
5aut pri rta
au
tho p rim art
ho m aB
riz av Ba riz av arb
ed era rbo ed era
c o b s sa co bs os
7 pie s.c . pie s.c a.
sa om sa om
llo llo
we we
9 d! d!

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

Module 2: Creating Methods, Handling Exceptions,


and Monitoring Applications

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 2: Creating Overloaded Methods and Using Optional and Output


Parameters

Lesson 3: Handling Exceptions

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

Applications often consist of logical units of functionality that perform specific


Th Th
functions,
is
do such as providing access to data or triggering
is
do some logical processing.
cu cu
me me
Visual
maC# is
rt nan
t b object-orientated language and uses
ma
rt thent concept
b
of methods to
a.b elo a.b elo
N arb ng N arb ng
encapsulate
ou oslogical tounits of functionality. A method
a@
s o u can o be
s a as ssimple
to or as complex
na M n a @ Ma
uth pri art uth pri r tto
as you like,oriand
ze therefore
ma
ve
a B it is important to consider what
arb
ori happens
ze
ma
ve
a B the state of your
arb
dc rab os d co r ab os
op s a s a.
application when iean s a exception
s .co
m
. occurs in a method. p ies s .co
m
llo a llo
we we
d! d!

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

After completing this module, you will be able to:

• Create and invoke methods.

• Create overloaded methods and use optional parameters.

• 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!

• Describe the purpose of methods.

• 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

A method comprises of two elements:

1. The method specification.

2. The method body.

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

method name. Each parameter is separated by a comma. If a method takes no


parameters, you specify an empty parameter list.

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

void StartService(int upTime, bool shutdownAutomatically)


{
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/50
10/25/2019 20483A - Programming in C# | Skillpipe

// Perform some processing here.


}

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
!

Defining a Parameter by Using the ref Keyword

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.

Returning Data 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. !

Invoking a Method Passing Parameters

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

var upTime = 2000;


var shutdownAutomatically = true;
StartService(upTime, shutdownAutomatically);
// StartService method.
void StartService(int upTime, bool shutdownAutomatically)
{ Th Th
is is
do do
cu
// Perform some processing here. cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
} rbo ng 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
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 .
If the method returns s a a value,
llo
om you specify how to handle this value,
sa
llo
typically
om by
we w
assigning it to a variable d! of the same type, in your calling code. ed!

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

1. ThStart the MSL-TMG1 virtual machine if it isThnot already running.


is is
do do
cu cu
ma m en ma me
r t r nt
2. Startt a.ba the 20483A-SEA-DEV11-02
belo virtual machine.
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
3. Log onrizeto Windows m av
era
a B8 as Student with the password
arb
ori
ze Pa$$w0rd.
m a ve Ba
dc os d r ab rbo
op bs a co s sa
ies s.c . pie s.c .
all om sa om
ow llo
ed we
! d!
Note: If necessary, click Switch User to display the list of users.

4. Switch to the Windows 8 Start window.

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

FourthCoffee.MethodTestHarness.sln, and then click Open.

8. In Visual Studio, on the View menu, click Task List.

9. In the Task List window, in the Categories list, click Comments.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/50
10/25/2019 20483A - Programming in C# | Skillpipe

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.

15. On the Build menu, click Build Solution.

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
! !

20. Press Shift+F11 to step out of the Initialize method.

21. Press F10 to step over the Initialize method call.

22. ThHover over the isInitialized variable, and verify


Th that the value returned is true.
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/50
10/25/2019 20483A - Programming in C# | Skillpipe

23. On the Debug menu, click Stop Debugging.

24. On the File menu, click Close Solution.

Lesson 2: Creating Overloaded Methods and Using


Th Th
Optional
m
is
do cu
me
and Output Parameters
m
is
do
cu
me
art nt art nt
a.b be a.b be
a lon a lon
No rbo gs No rbo gs
un sa t o u n s a to
au @ M au @ Ma
pri art pri
You have seent h ori
ze
thatma you acan
ve Ba define a method that accepts
t h o riz a m fixed
av number
rta
Ba of
dc rab rbo e dc e rab rbo
parameters. However, ssometimes sa you might write one generic sa requires
ies method .co that
op s.c . op ss .
ies om
all all m
ow
different sets of parameters ed
!
depending on the context in which itowised!used. You can
create overloaded methods with unique signatures to support this need. In other
scenarios, you may want to define a method that has a fixed number of parameters,
but enables an application to specify arguments for only the parameters that it needs.
You can do this by defining a method that takes optional parameters and then using
named
Th arguments to satisfy the parameters by T
is name.
his
do do
cum cu
ma e mema
rta nt nt
rt
.ba belo a .ba be
n lon
In this
No lesson,
un
rbo yougswill learn how to create overloaded
sa to
No
un
rbmethods,
o sa
gs define and
to
use
au @ M a uth @ Ma
t pri art pri
optional parameters,
h ori
ze
m a ve
namedaB arguments, and output parameters.
ori
ze
m a ve
rta
Ba
dc rab arb d r rbo
op os co ab sa
ies s s.c a . pie s s.c .
all om sa om
ow llo
we
Lesson Objectives ed
! d!

After completing this lesson, you will be able to:

• Create an overloaded method.


Th Th
is is
• Use optional
do
cu parameters. d oc
um
ma me ma en
rta n tb rt tb
.ba elo a.b elo
ng arb ng
• Use
No named
un
r bo
s arguments.
st 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
• Define output e e ed era
d co parameters.
rab
ss os
a. co bs os
a.
pie .co pie s.c
sa m sa om
llo llo
we we
d! d!

Creating Overloaded Methods

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

parameters do not vary sufficiently to enable the compiler to distinguish between


implementations.

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!

Incorrect Optional Parameter Definition

void StopService(string serviceName = null, bool forceStop, int


T
his Th
serviceId = 1) 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
co rab co bs os
pie ss sa pie s.c a.
sa .c . sa
om om
llo llo
we we
d! d!
You can call a method that takes optional parameters in the same way that you call
any other method. You specify the method name and provide any necessary
arguments. The difference with methods that take optional parameters is that you can
omit the corresponding arguments, and the method will use the default value when
the method
Th
is
runs. Th
is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/50
10/25/2019 20483A - Programming in C# | Skillpipe

The following code example shows how to invoke the StopService method, passing
only an argument for the forceStop mandatory parameter.

Invoking a Method Specifying Only Mandatory Arguments.

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.

Invoking a Method Specifying Mandatory and Optional Arguments

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!

Calling a Method by Using Named Arguments

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

Defining Output Parameters


Th Th
is is
do d oc
cum um
ma e nt ma
nt e
bool rIsServiceOnline(string
ta.
ba
be
lon serviceName, a.out
ba
rt
be
string
lon statusMessage)
No rbo gs No rbo gs
un sa to un sa to
{ au @
pri Ma au @
pri Ma
tho m rta tho m rta
riz av Ba r ize a ve Ba
var isOnline ed era = FourthCoffeeServices.GetStatus(serviceName);
rbo d r ab rbo
co b s s a co s sa
pie s.c . pie s.c .
sa om sa om
if (isOnline) llo llo
we we
d! d !
{
statusMessage = "Services is currently running.";
}
else
{
Th Th
is is
do statusMessage = "Services do
is currently stopped.";
c
um cu
ma en ma me
tb nt
}rta.b elo rt a.b be
lon
No ar bo ng No arb gs
u s st un os to
return
n a isOnline;
@ oM a@ 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
pie s.c a. pie . .
sa om sa com
llo llo
we we
d! d!

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
!

Exception handling is an important concept to ensure a good user experience and to


limit data loss. Applications should be designed with exception handling in mind.

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!

After completing this lesson, you will be able to:

• Describe the purpose of an exception.

• 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

• Use a finally block to run code after an exception.

• 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:

• Not all methods return a value.

• 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

How Exceptions Propagate


The .NET Framework uses exceptions to help overcome these issues. An exception
is an indication of an error or exceptional condition. A method can throw an exception
when it detects that something unexpected has happened, for example, the
application tries to open a file that does not exist.
Th Th
is is
do d oc
um c um
When
maa method
en throws an exception, the callingmcode
a
must
en be prepared to detect
rta tb rta tb
ba . l n e ba lon . e
o rbothis oexception.
and Nhandle gs If the calling code does
No not rbdetect
os gsthe exception, the code
un s a@ to un a@ to
au p Ma au p Ma
is aborted oand
t h
riz ther i m exception
av
r ta Ba
is automatically propagated t h o riz to r ithe
m av code rta that invoked the
Ba
ed era rbo ed era rbo
calling code. This c b c b
opieprocess s s.c continues
s a. until a section of code ptakes o
ies responsibility
s s.co
sa
. for
sa om a m
llo llo
handling the exception. we Execution continues in this section of code
d!
we after the
d!
exception-handling logic has completed. If no code handles the exception, then the
process will terminate and display a message to the user.

The Exception Type


Th Th
is is
do exception occurs, it is useful to include information
When an do about the original cause
cu cu
ma me ma me
r nt r nt
so that the
t a.ba method belo that handles the exception can take t a .ba the be appropriate corrective
lon
No rbo n gs No rbo gs
s to sa to
action.unIn au the a.NET @
pri
Framework,
M art
exceptions are based
un
a uth on the
@
pri
Exception
Ma class, which
tho m aB ori m rta
riz av ze throws a ve B
contains information ed
co
eraaboutarthe
b bo exception. When a method dc rab an aexception,
rbo it
pie s s.c s a o pie s s.c sa
sa . sa .
creates an Exception om and can populate it with information om the cause of
llo object llo about
we we
d d!
the error. The Exception! object is then passed to the code that handles the
exception.

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.
! !

SystemException System Represents all exceptions


raised by the CLR. The
SystemException class is
the base class for all the
exception classes in the
Th Th
is is System namespace.
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/50
10/25/2019 20483A - Programming in C# | Skillpipe

Exception Class Namespace Description

ApplicationException System Represents all non-fatal


exceptions raised by
applications and not the
CLR.

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.

The Tfollowing code example shows the syntax for


T
defining a try/catch block.
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/50
10/25/2019 20483A - Programming in C# | Skillpipe

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.

Th following code example, if the code in theThtry block causes a


In the is is
d oc d oc
me u me u
NullReferenceException
ma
r nt exception, the code inmathe
r
corresponding
nt catch block runs.
ta. be ta. be
arb b
on l arb on b l
If any
No other
u otype
s ofgs exception occurs, the code N
t
ino the
u
catch
o s block
gs
t
for the Exception
na a@ oM na a@ oM
uth pri art uth pri art
type runs. ori
z av m 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 o
we
Handling NullReferenceException
d! and Exception exceptionswed!

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

catch (NullReferenceException ex)


{
// Catch all NullReferenceException exceptions.
}
catch (Exception ex)
{
Th Th
is is
//docCatch all other exceptions. d oc
um 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
o os
When defining cmore op
ies
bs
than s .co one sacatch block, you must ensure
.
co
p that
ies
bs
yous .co place a. them in
all m all m
ow ow
the correct order. When ed an exception is thrown, the CLR attempts
!
edto match the
!
exception against each catch block in turn. You must put more specific catch blocks
before less specific catch blocks, otherwise your code will not compile.

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

exceptions, handled or unhandled, occur. If an exception is caught and handled, the


exception handler in the catch block will run before the finally block.

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!

var ex = new NullReferenceException("The 'Name' parameter is


null.");
throw ex;
Th Th
is is
do d oc
cum um
ma ent ma en
A common tb
ba strategy is for a method or block of code a.bto catch elo any exceptions and
r ta. be rt
lon a ng
No r bo gs No r bo st
attemptun to handle sa t
them.
o If the catch block for an exception
u n sa cannot o M resolve the error, it
au @ M a uth @
tho pri art pri art
riz m av a Ba o riz m av aB
can rethrow the e d c exception
e rab to
rbo propagate it to the caller. e dc e rab arb
os
op s s sa o p s s a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
The following code example shows how to rethrow an exception that has been
caught in a catch block.

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// Catch all NullReferenceException Th exceptions.


is is
do do
} cu cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
catch (Exception
rbo ng ex) 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
riz m av a Ba o riz m av Ba
// Attempt e dc e rab handle rbo e dc e rab rbo
op to s s s a .
the exception o p s s sa
.
ies .co ies .co
... a llo m a llo m
we we
d! d!
// If this catch handler cannot resolve the exception,
// throw it to the calling code
throw;
}

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:

• Use logging and tracing in your code.

• Use application profiling in 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 27/50
10/25/2019 20483A - Programming in C# | Skillpipe

Use performance counters to monitor the performance of your application.

Using Logging and Tracing

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
! !

string eventLog = "Application";


string eventSource = "Logging Demo";
string eventMessage = "Hello from the Logging Demo application";
Th Th
is
// Create the event source if it does notis
do do already exist.
cu cu
ma me ma me
If (!EventLog.SourceExists(eventSource))
rt n tb rt nt
b
a.b elo a.b elo
arb ng
NEventLog.CreateEventSource(eventSource, N arb ng
ou os
a@
s t oM o un eventLog);
o s a
st
oM
na a @
uth pri art uth pri art
// Log the o m
riz message. 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.
EventLog.WriteEntry(eventSource,
ies .co eventMessage); ies .co
all m all m
ow ow
ed ed
! !

Additional Reading: For more information on writing to the Windows event


log, see the How to write to an event log by using Visual C# page at
http://go.microsoft.com/fwlink/?LinkID=267789.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/50
10/25/2019 20483A - Programming in C# | Skillpipe

Debugging and Tracing


The System.Diagnostics namespace includes two classes, Debug and Trace,
which you can use to monitor the execution of your application. These two classes
work in a similar way and include many of the same methods. However, Debug
statements are only active if you build your solution in Debug mode, whereas Trace
statements
Th
is are active in both Debug and Release
Th mode builds.
is
do do
cum cu
ma e m me
rta n tb a r nt
.ba elo t a.b be
a lon
TheNDebug
ou r b and
os Trace
ng
st classes include methodsN to
ou writer b os format gs strings to the Output
na a @ o na a @ to
uth p M a uth p Ma
window in oVisualriz
r i Studio,
m av
r ta as
Ba
well as to any other listeners o riz thatr im you
av
rconfigure.
ta
Ba
You can
ed era rbo ed era rbo
co Output bs window co
also write to the pie s.c sa only when certain conditions
. pie arebsmet, s.c and
sa you can
.
sa om sa om
llo llo
adjust the indentationwof ed your trace messages. For example, if you
!
we are writing details
d!
of every object within an enumeration to the Output window, you might want to
indent these details to distinguish them from other output.

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.

Using the Debug Class


Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
r a r ng
intNo number;
un
bo
s
gs
t o
No
u
bo
s st
oM
au a @ M n a a @
t pri art uth pri a
h
Console.WriteLine("Please
o riz m av a Ba type a number between o riz m1avandrta10, Ba and then
ed era rbo e dc e rab rbo
co b ss sa op ss sa
press Enter"); pie .co . ies .co .
sa m a m
llo llo
string userInput w=ed!Console.ReadLine(); we
d!

Debug.Assert(int.TryParse(userInput, out number),


string.Format("Unable to parse {0} as integer", userInput);
Debug.WriteLine(The current value of userInput is: {0}", userInput);
Debug.WriteLine(The current value of number is: {0}", number);
Th
Console.WriteLine("Press Th
Enter to finish");
is is
do do
cu cu
Console mReadLine();
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/50
10/25/2019 20483A - Programming in C# | Skillpipe
Console.ReadLine();

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 See which functions consume the most CPU time.

o View a timeline that shows what your application was doing when.

o View warnings and suggestions on how to improve your code.

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 !

Performance sessions work by sampling. When you create a performance session,


you can choose whether you want to sample CPU use, .NET memory allocation,
concurrency information for multi-threaded applications, or whether you want to use
instrumentation to collect detailed timing information about every function call. In
Th Th
is is
most cases
do
cu you will want to start by using CPU sampling,
do
cu which is the default option.
ma me ma me
r nt r nt
CPU sampling
t a.ba beuses
lon statistical polling to determine which t a .ba bfunctions
elo are using the most
No rbo gs No rbo ng
sa to sa s to application, without
CPU time.
un
au This @ provides
pri Ma an insight into the performance un
au of
@ your
pri Ma
tho m rta tho m rta
riz av Ba r ize a ve Ba
consuming many ed
co
resources
era
b
rboand slowing down your application. d co r ab rbo
pie s s.c s a pie s s.c sa
sa . sa .
om om
llo llo
we we
d! d!
Additional Reading: For more information on application profiling, see the
Analyzing Application Performance by Using Profiling Tools page at
http://go.microsoft.com/fwlink/?LinkID=267791.

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.

Creating Custom Performance Counters


You Tcan
his use the PerformanceCounter and PerformanceCounterCategory
Th
is classes
do do
um c um c
to interact
ma with
en performance counters in a variety
maof ways.
en For example, you can:
rta tb rta tb
.ba elo elo
.ba
No rbo ng No ng rbo
un sa st un sa st
@ oM @ oM
au p art au p art
• t
Iterate over r
themaperformance t
counter categories available r monav a specified computer.
h ori i aB h ori i aB
ze ve arb ze era arb
dc rab os dc bs os
op s s a. op s a.
ies .co ies .co
a m a m
• Iterate over the performance l l ow counters within a specified category. l l ow
ed ed
! !

• Check whether specific performance counter categories or performance counters


exist on the local computer.

• Create custom performance counter categories or performance counters.


Th Th
is is
do d oc
c um um
ma e nt ma
en
rta be a.b tb
rt
.ba l elo
You Ntypically
ou rbo create o n gs custom performance counter
No categories
a rbo ngand performance
st
na s a t o u na s a oM
@ Ma @
counters tduring
u ho p ran
im installation
rta routine, rather than during
u tho the
p rim execution
art
aB of your
riz av B a riz av arb
ed era rbo ed era
application. After co a custom
pie bs
s.c performance
sa
. counter is createdcopon ies
a specific
bs
s.c
os computer, it
a.
sa om a o m
llo l
remains there. You do wenot need to recreate it every time you runlowyour ed application. To
d! !
create a custom performance counter, you must specify a base counter type by using
the PerformanceCounterType enumeration.

The following example shows how to programmatically create a custom performance


counter
Th category. This example creates a new performance
is
Th
is counter category named
do do
cu cu
FourthCoffeeOrders.
ma me
n
The category contains two
ma performance
me
n
counters. The first
rta tb rta tb
.ba lon e .ba lon placed, and the second e
performance
No rbo counter
gs tracks the total number ofNcoffee
o rborders
o gs
un sa to un to sa
au @ Ma au @ Ma
tracks thehonumber
t
riz
pr im of orders
av
r ta
B
placed per second. t ho
r
p r im
a
rta
Ba
ed era arb ize ve
o dc rab rbo
co b ss sa op ss sa
pie .c . i e . c .
sa om sa om
llo llo
Programmatically Creating we
d! Performance Counter Categoriesweand d! Performance
Counters

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!

The following example shows how to programmatically update custom performance


counters.

Using Custom Performance Counters


Th Th
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

// Get a reference to the custom performance counters.


PerformanceCounter counterOrders = new
PerformanceCounter("FourthCoffeeOrders", "#
Orders", false);
PerformanceCounter counterOrdersPerSec = new
PerformanceCounter("FourthCoffeeOrders",
T T "#
his his
oc d do
Orders/Sec",
um false); cu
ma en ma me
rta tb rta nt
// Update.ba elo performance counter
the values .at be
ng ba appropriatelon points in
No rbo st No rbo gs
un sa oM un sa t o
au
your code. @ au @ Ma
tho prim art tho pri rta
riz av aB riz m av Ba
ed OrderCoffee()
era arb ed era rbo
public void co bs os co b s sa
pie s.c a. pie s.c .
sa om sa om
{ llo
w
llo
we
ed d!
!
counterOrders.Increment();
counterOrdersPerSec.Increment();
// Coffee ordering logic goes here.
}

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
! !

Demonstration: Extending the Class Enrollment


Application Functionality Lab
In this demonstration, you will learn about the tasks that you will perform in the lab for
Th Th
this module.
is
d
is
d
oc oc
um um
ma ent ma en
rta be rt a.b tb
.ba lon elo
arb ng
Lab: Extending the Class Enrollment Application
No
un
au
rbo

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!

Estimated Time: 60 minutes

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!

Exercise 1: Refactoring the Enrollment Code

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

Task 1: Copy the code for editing a student into the


studentsList_MouseDoubleClick event handler
Th Th
is is
do d oc
cum um
ma e nt ma en
rta rt tb
1. Start .ba the bMSL-TMG1
elo virtual machine if it is not a.b
already
a
elo running.
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
2. Start the riz 20483A-SEA-DEV11-02
ed
av
era Ba
rbo virtual machine rizand log
e d
av on as
e r ab
aStudent
rbo with
co bs sa co s sa
pie s.c . p i s. .
the passwords aPa$$w0rd. llo
om e sa
llo
com
we we
d! d!
3. Start Visual Studio and open the School.sln solution from the
E:\Labfiles\Starter\Exercise 1 folder.

4. In the code for the MainWindow.xaml.cs window, in the


studentsList_KeyDown event, locate the code for editing student details which
Th Th
is is
is dinocuthe case Key.Enter block. d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/50
10/25/2019 20483A - Programming in C# | Skillpipe

5. Copy the code in this block to the clipboard and then paste it into the
StudentsList_MouseDoubleClick method.

TaskT 2: Run the application and verify that the


Th user can now double-click a
his is
studentdoto
cu edit their details
do
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 @ M au @ Ma
1. Build thothe solution
riz
pri
m
arand
ta resolve any compilation errors.
t h o riz
pri
m rta
av Ba av Ba
ed era rbo ed era rbo
co b s s a. c o b s sa
pie s.c pie s.c .
2. Change Kevin s a Liu’s omlast name to Cook by pressing Enter s a in the om main
llo llo
we we
d! d!
application window.

3. Verify that the updated data is copied back to the students list and that the Save
Changes button is now enabled.

4. ThChange George Li’s name to Darren Parker Th by double-clicking on his row in


is is
do do
the cmainum application window. cu
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
5. Verify
un that
sa the tupdated
@ oM data is copied back to
un the student sa
@ tolist.
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
6. Close thecoapplication.
pie b s s.c
os
a .
co
pie s s.c sa
.
sa om sa om
llo llo
we we
d! d!

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.

4. Call this method from the studentsList_MouseDoubleClick and


studentsList_KeyDown methods.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/50
10/25/2019 20483A - Programming in C# | Skillpipe

Task 4: Refactor the logic that adds and deletes a student into the
addNewStudent and deleteStudent methods

1. Refactor the code in the case Key.Insert code block in the


studentsList_KeyDown method into a method called addNewStudent that
takes no parameters.
Th Th
is is
do oc d
c
um um
2. mCall
art this e nt method from the case Key.Insert code
b
m art block
en
t b in the
a.b elo a.b elo
arbo
NostudentsList_KeyDown ng a rbo ng
un sa s to method. No
un sa st
oM
au @ M au @
tho prim a rta tho p rim art
riz av B r a aB
arb iz v arb
3. Refactored the co
pie
era
code bs in
s.c
the o sacase Key.Delete code block ed
co in
pie
era
the bs
s.c
os
a.
sa . sa
om om
studentsList_KeyDown l l ow
ed
method into a method called removeStudent l l ow
ed
that
! !
takes a Student as a parameter.

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!

2. Run the application.

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
! !

6. Close the application.

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

1. Add a breakpoint at the start of the switch statement in the


studentsList_KeyDown method.

2. Debug the application.

3. Edit the row for Kevin Liu by pressing Enter.


Th Th
4. Step
is
do over the code, watching the Call Stacks window
i
do and Locals window, until
cu cu
ma m en m m estep
you rta reach t b the editStudent method call, andarthen
elo ta.
nt
be into that method.
.ba b a lon
No rbo ng N r b gs
un sa st ou os to
@ o M n a @ Ma
au au
5. Step thoout of prithe editStudent
m
art
a method. t h 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 .
6. Cancel editing s a the student’s
llo
om details, and then continue debugging.
sa
llo
om
we we
d! d!

7. Add a new student by pressing Insert.

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.

13. Step out of the removeStudent method.

14. Cancel deleting the student.


Th Th
is is
do d oc
c
15. mStop debugging
um
en the application. ma
um
en
art tb rt tb
a.b elo a.b elo
No arb ng No arb ng
o s st os st
16. InunaVisual
uth
a@Studio,
pri
o M delete all breakpoints
art
and then
un
au close a @
pri
the osolution.
Ma
ori ma aB tho m rta
ze ve arb riz av Ba
dc rab ed era rbo
op s os co b ss sa
ies s .co a. pie . .
sa com
all m llo
ow we
ed d!
!
Results: After completing this exercise, you should have updated the application
to refactor duplicate code into reusable methods.

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

3. Add code to validate the date of birth


Th Th
4. Run
is
do the application and verify that student information
is
do is now validated correctly
cu cu
ma m en ma m 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
Task 1: Run riz the application
ed
m av
era
a Ba and observe that student o riz details
e
m av
e
thata B are not valid
arb
rbo d r ab os
can be entered co bs sa co s a.
pie s.c . p ies s.co
sa om a m
llo llo
we we
d! d!

1. In Visual Studio, from the E:\Labfiles\Starter\Exercise 2 folder, open the


School.sln solution.

2. Build the solution and resolve any compilation errors.


Th Th
is is
3. do the
Run application. d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 42/50
10/25/2019 20483A - Programming in C# | Skillpipe

4. Press Insert to display the new student window.

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. !

3. In the ok_Click method in StudentForm.xaml.cs code, add a statement to


check if the Last Name box is empty.

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!

1. In the ok_Click method in StudentForm.xaml.cs code, add a statement to


check if the Date of Birth box is empty.

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.

3. In the ok_Click method in StudentForm.xaml.cs code, add a statement to


calculate the student’s age in years, and check if the age is less than five years.

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!

Age in years = Age in Days / 365.25

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. !

3. Press Insert to display the new student window.

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.

The main tasks for this exercise are as follows:

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

2. Add code to save changes back to the database

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!

2. Build the solution and resolve any compilation errors.

3. Run the application.

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.

8. Close the application.

9. ThRun the application again and verify that itTdisplays his


the original list of students,
is
do do
without
ma
cu
me the changes that you just made. ma
cu
me
rta n tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
10. Close
un
au
the
s a@ application.
t oM 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
llo llo
we we
d! d!

Task 2: Add code to save changes back to the database

1. In the MainWindow.xaml.cs code bring the System.Data and


System.Data.Objects namespaces into scope.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 46/50
10/25/2019 20483A - Programming in C# | Skillpipe

2. Add code to perform the following tasks when a user clicks Save Changes:

a. Call the SaveChanges method of the schoolContext object.

b. Disable the Save Changes button.

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.

2. Below the try block, add a catch block to catch any


OptimisticConcurrencyException exceptions that may occur.

3. ThIn the catch block, add the following code:Th


is is
do do
cu cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
n lon
No // If rbo g s N o r b o gsearlier, then
un sathe user
to has changed the same un students sa to
au @ M a uth @ Ma
tho pri art pri rta
overwrite r m atheir a Bchanges o r m a Ba
ize ve arb ize ve
dc rab os d r ab rbo
op s a co s sa
with the enew i s . . p i s. .
s a data co
m
es
a
co
m
llo llo
we we
d!
this.schoolContext.Refresh( d!

RefreshMode.StoreWins, schoolContext.Students);
this.schoolContext.SaveChanges();

4. ThAdd another catch block to catch any UpdateException


is
Th
is exceptions that may
do do
cu cu
moccur,
art
mestoring the exception in a variable named
nt ma muEx.
en
a.b be rta tb
l o . b elo
No ar bo n gs No a r bo ng
u s t u s st
5. In athe
n catcha @ o
block, M add the following code: n 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.
ies .co . ies .co
all m all m
ow ow
// If some sort ed of database exception has occurred, ed then
! !
display the reason for the
exception and rollback
MessageBox.Show(uEx.InnerException.Message, "Error saving
changes");
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

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.

4. ThIn the main application window, click SaveThChanges.


is is
do do
cu cu
ma m en ma me
rta tb r nt
t a be
5. Delete.ba theelostudent George Li by pressing Delete.
rbo ng
.ba
rbo
lon
No s No gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho ma a B and note that the button is odisabled ma rta
6. Click Save riz
ed Changes
ve
rab a rbo
r ize dc
vewhen
rab
Bno
arb changes are
co s s op ss os
pending. pies a s.com a. ies
a
.co
m
a.
llo llo
we we
d! d!
7. Close the application.

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.

9. ThClose the application Th


is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 48/50
10/25/2019 20483A - Programming in C# | Skillpipe

10. In Visual Studio, close the solution.

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!

Test Your Knowledge

Question

Th using output parameters in a method signature, which


When Th
is is one of the following
do do
cum cu
ma e ma me
rta nt rt nt
statements .ba is true? 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
t
Select the correct
ho answer.
r im r ta t ho r im rta
riz av B arb r ize a ve Ba
ed era dc rab rbo
co b ss o sa op ss sa
You cannot return p i e . . i e . .
s a dataoby c
m using a return statement in a method that use s a outputomparameters.
c
llo llo
we we
d! d!
You can only use the type object when defining an output parameter.

You must assign a value to an output parameter before the method returns.

You define an output parameter by using the output keyword.

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

Module 3: Developing the Code for a Graphical


Application

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!

Lesson 2: Organizing Data into Collections

Lesson 3: Handling Events

Lab: Writing the Code for the Grades Prototype Application


Th Th
is is
do d oc
um Module Review and
c Takeaways 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 b os co b os
Module Overview pie
sa
llo
we
s s.c
om
a. pie
sa
llo
we
s s.c
om
a.

d! d!

To create effective graphical applications by using Windows Presentation Foundation


(WPF) or other .NET Framework platforms, you must first learn some basic Visual C#
constructs. You need to know how to create simple structures to represent the data
itemsThyou
i
are working with. You need to know how
Th to organize these structures into
i
sd sd
oc oc
collections,
ma
umeso that you can add items, retrieve items, ma
um and
en
iterate over your items.
rta n tb r tb
.ba need elo t a .ba so that elo
Finally,
No you rbo ngto know how to subscribe to events
No rbo ngyou can respond to the
un s s t u s st
a @ o M n a @ oM
actions of a uthyour pusers. art a uth pri art
ori rim a o m aB
ze av Ba riz av arb
dc e rab rbo e dc e rab
op s sa o s os
ies s .co . p ies s.co a.
all m all m
In this module, you will ow learn how to create and use structs and oenums,
ed we
d!
organize data
!
into collections, and create and subscribe to events.

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

• Create and use structs and enums.

• Use collection classes to organize data.

• Create and subscribe to events.

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 and use enums.

• 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!

Creating and Using Enums

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.

The following example shows how to create an enum:

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.

The following example shows how to use an enum:


Th Th
is is
do d oc
cum um
ma ent ma en
tb
Using ran
ta. Enum
ba
be
lon
rt a.b
arb
elo
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
Day favoriteDay = om
Day.Friday; om
llo llo
we we
d! d!

Using enums has several advantages over using text or numerical types:

• Improved manageability. By constraining a variable to a fixed set of valid values,


This his T
you are
do less likely to experience invalid arguments
c
do and spelling mistakes.
c
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 3/55
10/25/2019 20483A - Programming in C# | Skillpipe

• Improved developer experience. In Visual Studio, the IntelliSense feature will


prompt you with the available values when you use an enum.

• 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:

Using Enum Names and Values Interchangeably


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 an saenum
// Set variable
to by name. un os st
@ Ma a @ oM
au pri au p art
tho m rta tho rim aB
Day favoriteDayriz av = Day.Friday;
Ba riz av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
// Set an enums avariable om by value. sa om
llo llo
we we
Day favoriteDay = (Day)4; d! d!

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!

• A struct named Point might consist of fields to represent an x-coordinate and a y-


coordinate.

• A struct named Circle might consist of fields to represent an x-coordinate, a y-


Th Th
is is
coordinate,
do
c
and a radius. d oc
um um
ma ent ma en
rta be a.b rt tb
.ba lon elo
• ANstruct rbnamed gsColor might consist of fieldsNto a
represent
rbo na
gs red component, a
ou os t o o u s to
na a @ M na a @ Ma
greenucomponent,
tho
riz
pri
m av
art a blue component.
and aB
uth
ori
pri
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!
Most of the built-in types in Visual C#, such as int, bool, and char, are defined by
structs. You can use structs to create your own types that behave like built-in types.

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

// Other methods, fields, properties, and events.


}

The struct keyword is preceded by an access modifier— public in the above


example—that specifies where you can use the type. You can use the following
Th modifiers in your struct declarations:
access Th
is is
d oc d oc
um um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
sa s to o o sa st
Accessun
au @
p
DetailsM a
un
au @
p
oM
art
tho rim rta tho rim aB
riz av B r iz a v
Modifier ed c era
bs
arb
o
ed
co
era
bs
arb
os
op s sa p s a.
ies .co . ies .co
all m all m
ow ow
public The type ed is available to code running in any assembly. ed
! !

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

public struct Coffee


{ Th Th
is is
do d
//
ma
Thisum c
en
is the custom constructor. m ocume
rta tb art nt
. e a.b be
b l lon
Npublic arb Coffee(int strength, string Nbean, arb string countryOfOrigin)
ong
ou os st g ou os st
na a@ oM na a@ oM
{ uth pri
ma
art
aB
uth pri
ma
art
aB
ori ori
ze ve arb ze ve arb
d rab d r ab
this.Strength
co
pie ss = ostrength;
sa
.
co
pie ss os
a.
sa .co sa .co
m m
this.Bean llo=webean; llo
we
d! d!
this.CountryOfOrigin = countryOfOrigin;
}
// These statements declare the struct fields and set the default
values.
Tpublic
his
int Strength; Th
is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 7/55
10/25/2019 20483A - Programming in C# | Skillpipe

public string Bean;


public string CountryOfOrigin;
// Other methods, fields, properties, and events.
}

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!

// Call the custom constructor by providing arguments for the three


required parameters.
Coffee coffee1 = new Coffee(4, "Arabica", "Columbia");

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

• A get accessor to provide read access to a field.

• A set accessor to provide write access to a field.

The following example shows how to implement a property in a struct:


Th Th
is is
do d oc
um c um
Implementing
ma
rta
en a Property
tb
ma
rt
en
tb
.ba elo a.b 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
public struct pie Coffee s.c a. pie s.c a.
sa om sa om
llo llo
{ we we
d! d!
private int strength;
public int Strength
{
get { return strength; }
Th set { strength = value; } 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
Within the property, lthe low get and set accessors use the followingllowsyntax:
ed ed
! !

• 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

Coffee coffee1 = new Coffee();


Th Th
is is
// The do following code invokes the set accessor.
cu
do
cu
m m e m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/55
10/25/2019 20483A - Programming in C# | Skillpipe

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
!

// This is a read-only property.


public int Strength
{
Th Th
is is
do
get d oc
cu { return strength; } um
ma me ma en
nt tb
} rta.ba be
lon
rt a.b
arb
elo
No rbo gs No ng
sa os st
//unThis
au @ a twrite-only
is oM property. un
au a @ oM
thop a
rim rta tho p rim art
r a B riz av aB
public izstring
ed
c
ve Bean ar
rab bo ed
co
era
b
arb
os
op ss sa pie s s.c a.
ies .co . sa
{ a m om
llo llo
we we
d! d!
set { bean = value; }
}

• 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

else if(value > 5)


{ strength = 5; }
else
{ strength = value; }
}
}
Th Th
is is
do d oc
cum um
ma e nt ma en
rta b rt
a.b tb
.ba elo elo
r ng arb ng
• Properties
N ou bos are required
a@
st
oM
for data binding in WPF.
N o un
For o example,
sa s t you can bind
oM
na au @
uth pri art t p r a
controlsorto h ma fieldrtavalues.
ize property ve values, but you cannot bind controls to
ma aB ori i
arb zed vera Ba
dc rab os rbo
op s a c o b s sa
ies s .co . p ies s.co .
all m all m
ow ow
ed ed
! !
When you want to create a property that simply gets and sets the value of a private
field without performing any additional logic, you can use an abbreviated syntax.

• 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:

public int Strength { get; }


Th Th
is is
do d oc
cum um
ma ent ma en
• rta
To create tb
rt
.ba a bproperty
elo that writes to a private field,a.byou
a
canelo use the following syntax:
No rbo ng No rbo ng
un sa s to un sa st
@ Ma @ oM
au pri au pri art
tho ma rta tho m aB
riz ve Ba riz av arb
ed rab rbo ed era
c
public intopiStrength ss {sa. set; } co bs os
es .co pie s.c a.
all m sa om
ow llo
ed we
! d!

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

Additional Reading: In addition to controlling access to a property by omitting


get or set accessors, you can also restrict access by applying access
modifiers (such as private or

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.

The following example shows a struct that includes an array:


Th Th
is is
do d oc
c um um
Creating
ma
rt a Struct
nt
b
that Includes an Array
e ma
rt
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
public structiesMenu .cop s a. pie s.c a.
all m sa om
ow llo
{ ed we
! d!

public string[] beverages;


public Menu(string bev1, string bev2)
{
beverages = new string[] { "Americano", "Café au Lait", "Café
Th
Macchiato", Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/55
10/25/2019 20483A - Programming in C# | Skillpipe

"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!

string firstDrink = myMenu.beverages[0];

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! !

The following example shows how to define an indexer for a struct:

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

// Enable client code to determine the size of the collection.


public int Length
{
get { return beverages.Length; }
}
}
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
n arb ng
Wheno uyou use
N r bos an indexer
g st to expose the array, you
N o un
use o sa following
the st syntax to
na a@ oM @ oM
uth pri art au p a
retrieve theoribeverages ma from
a B the list: tho rim rta
ze ve a riz av 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
Accessing Array Items ed by Using an Indexer
!
ed
!

Menu myMenu = new Menu();


string firstDrink = myMenu[0];
intThnumberOfChoices
is = myMenu.Length; Th
is
do d oc
cum um
ma ent ma en
rta be a.brt tb
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
@ o na a @ oM
Just likeauath property, pri
m
you
Ma can customize the get and
r taB
set
u t h accessors
p r im
artin an indexer
aB
ori av ori av
ze era a rbo You can create a read-onlyedindexerz era arb
without affecting d c client
op b scode.
s.c s a c o pie
by
b s s.c
including
os
a.
only a
ies . s
all can o m all o m
get accessor, and you ow
ed
create a write-only indexer by including ow only a set
ed
! !
accessor.

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

6. Start the 20483A-SEA-DEV11-03 virtual machine.

7. Log on to Windows 8 as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.


Th Th
is is
do d oc
cum um
ma e nt ma en
r rt tb
8. Switch
t a.b
arb
to bethe
lon Windows 8 Start window. a . ba elo
No g N r b ng
un o sa s to o un o sa st
@ M @ oM
au p a au p art
tho rim rta tho rim
9. Click Visual riz
ed
Studio
av
era B 2012.
arb r ized
a vera
aB
arb
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
10. In Visual Studio,owon l l
ed
the File menu, point to New, and then oclick l l we Project.
! d!

11. In the New Project dialog box, in the Templates list, click Visual C#, and then
in the Project Type list, click Console Application.

12. In the Name box, type UsingStructs


Th Th
is is
13. In dtheum
do
oc Location box, set the location to E:\Democode,
cu
m
and then click OK.
ma en ma en
rta tb rt a.b tb
.ba elo elo
NoIn therbUsingStructs ng ng arb
14. un o sa st
oM namespace, add theNfollowing
ou os code:
a
st
o
au @ na @ Ma
tho prim a rta uth pri rta
riz av Ba ori ma Ba
ed era rbo ze ve rbo
co b dc rab
pie s s.c sa op s s.c sa
sa . ies .
om all om
struct Coffee llo
we ow
d! ed
!
{
public string Name { get; set; }
public string Bean { get; set; }
public string CountryOfOrigin { get; set; }
public int Strength { get; set; }
Th Th
is is
}doc um
d oc
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
15. In the Program
r i ze
dc
ve class,
rab
Ba in the
rbo Main method, add the riz following
ed
av
era code: arb
op ss sa co bs os
ies .co . pie s.c a.
all m sa om
ow llo
ed we
! d!
Coffee coffee1 = new Coffee();
coffee1.Name = "Fourth Coffee Quencher";
coffee1.CountryOfOrigin = "Indonesia";
coffee1.Strength = 3;
Th Console.WriteLine("Name: {0}", coffee1.Name);
T his
is
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/55
10/25/2019 20483A - Programming in C# | Skillpipe

Console.WriteLine("Country of Origin: {0}",


coffee1.CountryOfOrigin);
Console.WriteLine("Strength: {0}", coffee1.Strength);

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.

20. Press Enter to close the console window.

21. Close Visual Studio.


Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
arb ng
Lesson 2: Organizing Data into Collections
No
un
au
rbo

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

• Choose appropriate collections for different scenarios.

• Manage items in a collection.

• Use Language Integrated Query (LINQ) syntax to query a collection.

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!

• Retrieve specific items from the collection.

• Count the number of items in the collection.

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?

• Will you need to sort the collection?

• How large do you expect the collection to get?


Th Th
is is
• d
If youoare d
cu using a dictionary class, will you need oto cu retrieve items by index as well
ma m en ma me
rta key?t be rta nt
as by .ba lon .ba be
lon
No rbo gs No rbo gs
un s a@ t oM un s a@ to
au pri art a uth pri Ma
tho rta
• Does your riz collection
ed
ma
ve consist
aB
a
solely of strings? ori
ze
ma
v Ba
rab rbo 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!

If you can answer all of these questions, you will be able to select the Visual C#
collection class that best meets your needs.

Standard Collection Classes


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 18/55
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 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

ArrayList The ArrayList is a general-purpose list that stores a linear


collection of objects. The ArrayList includes methods and
Th T
is
do properties thathenable
is
d you to add items, remove items, count
c oc
um u
methe collection, and sort the collection.
ma ent the number ofmitems
a
in n
rta be rta tb
.ba lon .baelo
No rbo gs No ng
rbo
BitArray
un sa to The BitArray isuna list classsa thatsrepresents
to a collection of
au @ Ma au @ Ma
tho pri rta t h pri r t
riz m av Ba bits as Boolean values. m
ori The BitArray
av a Bmost commonly
is
ed era rbo ze era arb
co b dc b os
pie s s.c sa
. used for bitwise operations oand pie Boolean s s.c arithmetic,
a. and
sa om sa om
llo
we includes methods to perform common llo
we Boolean operations
d! d!
such as AND, NOT, and XOR.

Hashtable The Hashtable class is a general-purpose dictionary class


that stores a collection of key/value pairs. The Hashtable
includes methods and properties that enable you to retrieve
items by key, add items, remove items, and check for
Th
is
particular keys
Thand values within the collection.
i
do sd
c oc
um um
ma
Queue ent m
The Queue class en in, last out collection of objects.
art is a first
rta be a.b tb
.ba lon elo
No rbo gs The Queue includes
No a rmethods
bo ngto add objects to the back of
un s to un s st
a@ Ma a @ oM
au pri a
the queue (Enqueue) uth and retrieve
pri objects
art from the front of
tho ma rta ori ma aB
riz ve Ba z v a
ed rab rbo the queue (Dequeue). d c e e rab rbo
co ss sa op ss sa
pie .c . ies .co .
sa om all m
llo o
SortedList we The SortedList class stores a collection we of key/value pairs
d! d!
that are sorted by key. In addition to the functionality
provided by the Hashtable class, the SortedList enables
you to retrieve items either by key or by index.

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

HybridDictionary The HybridDictionary is a dictionary class that you


can use when you cannot estimate the size of the
collection. The HybridDictionary uses a
ListDictionary implementation when the collection
size is small, and switches to a Hashtable
Th Th
is is
implementation as the collection size grows larger.
do do
cum cu
ma e ma me
rta nt rt nt
OrderedDictionary
.ba be a.b be
The OrderedDictionary is an indexed dictionary
lon a lo ng
No rbo gs N os rb
st
un
au
sa
@ to
Ma classothat
un enables
a a@ you too retrieve
M items by key or by
tho pri rta ut pr ar
riz m av Ba index. Notehothat im the SortedList
riz unlikeav
ta
Ba class, items
ed era rbo ed era rb
co b sa co
in an OrderedDictionary os
bs not sorted
are
pie s s.c . pie s. a. by key.
sa om sa co
llo llo m
we we
NameValueCollection d! The NameValueCollection is! an indexed dictionary d
class in which both the key and the value are
strings. The NameValueCollection will throw an
error if you attempt to set a key or a value to
anything other than a string. You can retrieve items
by key or by index.
Th Th
is is
do
StringCollection do
The StringCollection is a list class in which every
cu cu
ma me m
rta nt
be item m
inarthe en
ta collection
tb is a string. Use this class when
.ba lon .b elo
No rbo
sa
gs youNwant
o toarstore
bo ng
s a simple,
s linear collection of
un @ to n u a@ oM t
au Ma
tho pri
m rta strings. autho pri
m
art
aB
riz av Ba riz av arb
ed era rbo ed era
co b s sa co b s os
StringDictionary pies s.c . The StringDictionary pie is a dictionary
s.c aclass
. in which
all om s o all m
ow oware strings. Unlike the
both the key and the value
ed ed
! !
NameValueCollection class, you cannot retrieve
items from a StringDictionary by index.

BitVector32 The BitVector32 is a struct that can represent a 32-


bit value as both a bit array and an integer value.
Unlike the BitArray class, which can expand
Th This
is indefinitely,
do d the BitVector32 struct is a fixed 32-bit
oc
cum um
ma e nt
size.mAs a result,
en the BitVector32 is more efficient
rta be art tb
.ba
rbo
lon than the aBitArray
.ba
r
efor
lon small values. You can divide a
No gs No bo gs
un s a@ to un sa to sections to efficiently
au pri Ma BitVector32
au instance
@
p
intoMa
tho ma rta ori th rim rta
riz ve Ba store multiple zvalues. av Ba
ed rab rbo e e dc rab rbo
co ss sa op ss sa
pie .c . ies .co .
sa om all m
llo ow
we ed
d
Reference Links:! For more ! structs listed in
information about the classes and
the previous table, see the System.Collections.Specialized Namespace page
at http://go.microsoft.com/fwlink/?LinkID=267796.

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!

// Create a new ArrayList collection.


ArrayList beverages = new ArrayList();
// Create some items to add to the collection.
Coffee
Th coffee1 = new Coffee(4, "Arabica",
Th "Columbia");
is is
d d
Coffeeoccoffee2
um = new Coffee(3, "Arabica",oc"Vietnam");
um
ma en ma en
a.b rt tb a.b rt tb
Coffee elo elo
No acoffee3
rbo ng = new Coffee(4, "Robusta", No a"Indonesia");
rbo ng
un s s t u s st
a @ o M n a @ oM
a
// Add utthe items
pri to
art the collection. a uth pri art
ho m a o m aB
riz av Ba riz av a
ed era rb e d e r ab yourboadd
// Items are co implicitly
pie bs os cast to the Object type
a. co when
pie ss sa them.
s.c .co .
sa om sa m
beverages.Add(coffee1); llo llo
w
ed w ed
! !
beverages.Add(coffee2);
beverages.Add(coffee3);
// Retrieve items from the collection.
// Items must be explicitly cast back to their original type.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/55
10/25/2019 20483A - Programming in C# | Skillpipe

Coffee firstCoffee = (Coffee)beverages[0];


Coffee secondCoffee = (Coffee)beverages[1];

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
!

Iterating Over a List Collection

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"]);
}

Dictionary classes, such as the Hashtable, actually contain two enumerable


collections—the keys and the values. You can iterate over either of these collections.
Th scenarios, however, you are likely to iterate
In most Th
is is through the key collection, for
d oc d oc
u u
ma tomretrieve
example en the value associated with each me in turn.
ma key nt
r tta. be r 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
The following riz
ed
example
m av shows
a Ba how to iterate over the keys
o riz
ed
in m a
av Hashtable Ba collection
era rbo era rbo
co b s s c o b s sa
and retrieve the value p ies associated
s .co a . with each key: p ies s.co .
all m all m
ow ow
ed ed
! !
Iterating Over a Dictionary Collection

foreach(string key in ingredients.Keys)


Th Th
{ is
do
is
d
c oc
um me u
ma For neach key in turn, retrieve the
// e ma value nt associated with the
rta tb r t a be
.ba elo .ba lon
N r b ng N r b gs
key.o u os
a@
st
oM o un o sa to
na a @ Ma
uth pri art uth pri rta
ori
Console.WriteLine("The m a aB ingredients of a o{0}
r m
are a {1}", Ba key,
ze ve arb ize ve
dc rab o d r a rbo
op ss sa c op b ss sa
ingredients[key]); ies .co . ies .co .
all m all m
ow ow
} ed ed
! !

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!

select <variable names>

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
! !

// Create a new Hashtable and add some drinks with prices.


Hashtable prices = new Hashtable();
prices.Add("Café
Th au Lait", 1.99M); Th
is is
do d o
um
prices.Add("Caffe c Americano", 1.89M); m cu
ma en me
rta tb art nt
. elo a . be
b
prices.Add("Café
arb ng Mocha", 2.99M); b arb lon
Nou os st N ou g
os st
na a@ oM na a@ oM
uth pri
prices.Add("Cappuccino", art 2.49M); uth pri art
ori ma aB ori ma aB
ze ve a r ze ve arb
d co
prices.Add("Espresso", rab b os1.49M); d co r ab os
pie ss a . p ies s s a.
sa .co .co
llo m a llo m
prices.Add("Espresso we Romano", 1.59M); we
d! d!
prices.Add("English Tea", 1.69M);
prices.Add("Juice", 2.89M);
// Select all the drinks that cost less than $2.00, and order them
by cost.
varThbargains = Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/55
10/25/2019 20483A - Programming in C# | Skillpipe

from string drink in prices.Keys


where (Decimal)prices[drink] < 2.00M
orderby prices[drink] ascending
select drink;
// Display the results.
foreach(string bargain in bargains)
Th Th
is is
{ do
c
d oc
um um
ma nt e ma en
Console.WriteLine(bargain);
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
Console.ReadLine();
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!

Note: Appending the suffix m or M to a number indicates that the number


should be treated as a decimal type.

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
! !

// Query the Hashtable to order drinks by cost.


var drinks =
Tfrom
his string drink in prices.Keys Th
is
do do
cu cu
orderby
ma m en prices[drink] ascending ma me
rta t r nt
.ba belo t a .ba be
select drink;n lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
Console.WriteLine("The
tho pri art cheapest drink is {0}: pri
", rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os d co r ab
drinks.FirstOrDefault()); pie s s.c a . pie s s.c sa
.
sa om sa om
llo llo
// Output: "The cheapest we
d!
drink is Espresso" we
d!
Console.WriteLine("The most expensive drink is {0}: ",
drinks.Last());
// Output: "The most expensive drink is Café Mocha"
Console.WriteLine("The maximum is {0}: ", drinks.Max());
// TOutput:
his "The maximum is Juice" Th
is
do do
// "Juice" c u is the largest value in the collectioncu when ordered
ma m en ma me
rta tb r nt
.ba elo t a .ba b elo
alphabetically.
N rb ng N rb ng
ou os st ou os st
na a@ oM na a@ oM
uth pri
Console.WriteLine("The art minimum is {0}: ",uthdrinks.Min());
pri art
ori ma aB ori ma aB
ze ve a rbo ze ve arb
dc rab dc rab os
// Output: "The op minimum
s s sa is Café au Lait"
. o p s s a.
ies .co ies .co
all m all m
// "Café au Lait" ow is the smallest value in the collection ow when
ed ed
! !
ordered alphabetically.

Note: The return type of a LINQ expression is IEnumerable<T>, where T is


Th
the type of the items in the collection. IEnumerable<T>
Th
is an example of a
is is
generic
do
cu type. The methods you use on a results do set, such as FirstOrDefault,
cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/55
10/25/2019 20483A - Programming in C# | Skillpipe

Last, Max, and Min, are extension methods. Generic types and extension
methods are covered later in this course.

Reference Links: For more information about using LINQ to query


collections, see the LINQ Query Expressions (C# Programming Guide) page
That http://go.microsoft.com/fwlink/?LinkID=267799.
Th
i sd i sd
oc oc
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
Lesson 3: Handling Events
un
au
tho
riz
@
pri
m av
Ma
rta
Ba
un
au
tho
riz
a @
p rim
av
oM
art
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 w
Events are mechanisms d! that enable objects to notify other objectsedwhen ! something
happens. For example, controls on a web page or in a WPF user interface generate
events when a user interacts with the control, such as by clicking a button. You can
create code that subscribes to these events and takes some action in response to an
event.
Th Th
is is
do oc d
cum um
ma e m en
Withoutrtaevents,
.ba
nt
be your code would need to constantly
a rta
.ba
read t bcontrol values to look
elo
for
lon ng
No rbo gs No rbo s inefficient
any changes
un
au
sain state
@ t o that
Ma
require action. This would
u na be a
s a @very to
Ma
way of
tho p rim rta u tho p rim rta
developing ran ize application.
dc
av
era Ba In this lesson, you will learnrizhow
rbo ed toavcreate,
era Ba or raise,
rbo
op b s s a c o b s sa
i s . p i s .
events, and how to es subscribe
all
.co
m to events. es
all
. co
m
ow ow
ed ed
! !

In this lesson, you will learn how to handle events.

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!

Creating Events and Delegates


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/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
@ @ 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

public struct Coffee


{ Th Th
is is
do do
um c cu
public
ma enEventArgs e; ma me
rta t r nt
.ba belo t a .ba be
n lon
Npublic
ou r bos delegate g st void N
OutOfBeansHandler(Coffee
o r b o gcoffee,
st EventArgs
na a@ oM un sa oM
u a uth @
pri art pri art
args); thoriz ma
v
aB ori
z
ma
v
aB
ed era a rbo ed era arb
co b s s c o b s os
public event pie OutOfBeansHandler
s.c a . OutOfBeans; pies s.c a.
sa om a o m
llo llo
} we we
d! d!

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.

To raise an event, you need to do two things:

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

public event OutOfBeansHandler OutOfBeans;


int currentStockLevel;
int minimumStockLevel;
public void MakeCoffee()
{
// Decrement the stock level.
Th Th
is is
docurrentStockLevel--; do
cu cu
ma me m me
rta// If n t b the stock level drops below rtthe a nt
minimum, raise the
.ba elo a.b be
ng a lon
No rbo st N ou r b os g st
event.
un sa oM na a@ oM
au @ u
tho prim a rta tho p rim art
r a B r a aB
i z
if (currentStockLevel
ed v era arb < minimumStockLevel) ized vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
{ sa om sa om
llo llo
we we
// Check whether d! the event is null. d!

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
!
}

In this example, the signature of the HandleOutOfBeans method matches the


delegate
T for the OutOfBeans event. When you Tcall the SubscribeToEvent method,
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 34/55
10/25/2019 20483A - Programming in C# | Skillpipe

the HandleOutOfBeans method is added to the list of subscribers for the


OutOfBeans event on the coffee1 object.

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

1. ThStart the MSL-TMG1 virtual machine if it isThnot already running.


is is
do do
cu cu
ma m en ma me
2. Start
rta thet b20483A-SEA-DEV11-03
.ba elo
virtual machine.
r t a .ba
nt
be
ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au a u Ma
3. Log hon t ori to Windows
p r im
a
a r ta 8 as Student with the password
B
t ho
r
Pa$$w0rd.
p r im
a
rta
Ba
ze ve a ize ve
dc rab rbo dc rab rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed e
Note: If necessary, ! click Switch User to display the listdof ! users.

4. Switch to the Windows 8 Start window.

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.

7. In the Open Project dialog box, browse to the E:\Democode\Starter folder,


click EventsAndXAML.sln, and then click Open.

8. ThIn Solution Explorer, expand EventsAndXAML, Th and then double-click


is is
do do
MainWindow.xaml.
cu
me
cu
me
ma n m a nt
rta tb r t a.b be
.ba elo lon
NoNotice rbo ng N a r b gs
9. un that
sa
@
the s t window includes a button named
o ou
n
btnGetTime
os
a @ to and a label
au pri M art au pri Ma
tho ma aB t h ma r taB
namedrizelblShowTime. ve arb
ori
ze ve arb
dc rab o dc rab os
op s s sa op s s a.
ies .co . ies .co
all m all m
10. In the Design window, ow
ed click the button to select it. ow
ed
! !

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.

15. TIn the btnGetTime_Click method, add theT following code:


his his
do do
cum cu
ma e ma me
rta nt rt nt
.ba belo a .ba be
ng lon
rbo
No lblShowTime.Content s = rbo
DateTime.Now.ToLongTimeString();
No 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
16. In Solution Explorer, llo
we expand MainWindow.xaml, expand llo
we
d! d!
MainWindow.xaml.cs, and then double-click MainWindow.

17. Switch back to the MainWindow.xaml window.

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"

This attribute subscribes the btnGetTime_Click method to the Click event.

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
! !

Lab: Writing the Code for the Grades Prototype


Application
Th Th
is is
Scenario
do
cu
d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/55
10/25/2019 20483A - Programming in C# | Skillpipe

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.

Estimated Time: 60 minutes


Th Th
is is
do d oc
c um um
ma e nt ma nt e
• Virtual
rta Machine:
.ba be
lon 20483A-SEA-DEV11-03, MSL-TMG1
a.b rt be
lo
No rbo gs No arb ng
un sa to un os st
@ Ma a@ oM
au p au pri art
• User Name:t ho r
Student
im rta tho m aB
riz av 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
• Password: Pa$$w0rd llo
we
llo
we
d! d!

Exercise 1: Adding navigation logic to the Grades Prototype


Application
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 38/55
10/25/2019 20483A - Programming in C# | Skillpipe

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! !

1. Examine the window and views in the application

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

4. Add code to determine the type of user

5. Handle the Student_Click event

6. Build and test the application

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.

6. Raise the LogonSuccess event.

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!

1. In the MainWindow.xaml.cs code, locate the GotoLogon method, and then


add code to display the logonPage view and to hide the studentsPage and
studentProfile views.
Th Th
is is
2. In dthe
oc Event Handlers region, add code to thedo Logon_Success method to
c
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 41/55
10/25/2019 20483A - Programming in C# | Skillpipe

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.

3. In the MainWindow.xaml XAML editor, locate the definition of the LogonPage


page.
Th Th
is is
do do
4. Modify cu the definition to call the Logon_Success
me
cu method for the
me
ma n m a nt
rta tb r t be
LogonSuccess
.ba
rbo
elo
ng
event. 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
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!
Task 4: Add code to determine the type of user

1. In the MainWindow.xaml.cs file, in the Refresh method, add code to


determine the type of user, display Welcome <username> in the txtName box,
Thand then call either the GotoStudentProfile Th method (for students) or
is is
do do
c
GotoStudentsPage method (for teachers) cu
ma display
to the appropriate view.
um me
ma en nt
rta t b r t a b
.ba elo .ba elo
No rbo ng No rbo ng
s st
2. Inunathe GotoStudentProfile
sa
@ t o Ma method, add codeu na to hide
s a @ the ostudentsPage
Ma view,
uth pri r t u t h p r i r t
ori m av aB ori m aB
and then ze to display era and
arb refresh the studentProfile ze view.ave arb
dc b o dc rab os
op s s.c s a o pie s s.c a.
ies . s
all o m all o m
ow ow
3. In the GotoStudentsPage ed
!
method, add code to hide the studentProfile ed
!
view,
and then add code to display and refresh the studentsPage view.

4. In the StudentProfile.xaml.cs file, in the Refresh method, add code to:

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.

Task 5: Handle the Student_Click event


Th Th
is is
do d oc
cum um
ma ent ma en
rta b rt tb
1. In the.ba StudentsPage.xaml.cs
rbo
elo
ng
file, in the StudentsPage
a.b
arb
elo
ng
class, locate the
No s N o o s
un sa to un sa to
Student_Click
au
tho
@
pri method.
M art au
t h
@
pri Ma
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
2. Add code toiethis p s p s
s a method .co
m to identify which student was clicked
. ies
a
.cby
om using the Tag
.
llo llo
we we
property of the button, d! and then raise the StudentSelected event, d! passing the
student name as the second parameter.

3. In the MainWindow.xaml.cs file, in the studentsPage_StudentSelected


method, add code to set the CurrentStudent property of the SessionContext
Thobject to the student who was clicked by using Th the Child property of the e
is is
do do
cu cu
margument.
art
me
nt ma me
nt
a.b be rta be
a lon .ba lon
No rbo gs No rbo gs
4. Call
un thesaGotoStudentProfile
au @ to
M method. un
a
sa
@ to
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
5. In the MainWindow.xamlpie s s.c a . XAML editor, locate the definition
pie of
s s.c the sa.
sa om sa om
llo llo
StudentsPage page. w ed
!
wed
!

6. Modify the definition to call the studentsPage_StudentSelected method for the


StudentSelected event.

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. ! !

3. Log on as the teacher, vallee with a password of password.

4. Verify that the application displays the StudentPage view.

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.

The Student Profile page should look like this:

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!

ThFIGURE 3.2: THE STUDENT PROFILE PAGE Th


is is
do do
cu cu
ma m en ma me
rta off the t b application. r nt
6. Log .ba elo t a .ba be
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 rta
7. Log onrizeas the ma student,
ve
a B grubere, with a password
a
oriof password.
ze
ma
v Ba
dc rab rbo dc e rab rbo
op ss sa op ss sa
ies .co . ies .co .
a m a m
8. Verify that the application llo
we displays the student profile page llofor Eric Gruber.
we
d! d!

9. Close the application and then close the solution.

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.

Exercise 2: Creating Data Types to Store User and Grade


Information
Th Th
is is
do d oc
cum um
ma e nt ma en
rta rt tb
Scenario .ba 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
In this exercise,
t h ori
ze
you
ma willrtadefine
ve Ba basic structs that will hold
t h ori
ze
themateacher,
r i
ve
a B student, and
dc rab rbo dc rab arb
sa os
grade information op for the
ies ss application.
.co . op
ies s s.co a.
all m all m
ow ow
ed ed
! !
You will then add a unit test project to the solution to test the creation and use of the
structs. You will run these tests and verify that the structs function as expected.

The main tasks for this exercise are as follows:


Th Th
is is
do ocd
cum um
1. mDefine e basic structs for holding Grade, m
Student, en Teacher information
art
a.b
nt
be a rta and tb
elo
a l o . b a
No rbo n gs No rbo ng
un sa t u s st
o na a oM
2. Add au unit @ tests
p to Ma
create and use the collections u of @
structsp 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.
sa om sa om
llo llo
we we
d! d!
Task 1: Define basic structs for holding Grade, Student, and Teacher
information

1. Open the GradesPrototype solution from the E:\Labfiles\Starter\Exercise 2


Thfolder. Th
is is
do do
cu cu
ma m en ma me
t b folder, open Grade.cs. nt
2. Inrtathe
.ba Data elo r t a .ba be
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 rta
3. In the rGradesPrototype.Data
ize
ma
ve
aB
a
namespace, create ori a struct
ze
ma
v named Ba Grade that
dc rab rbo dc e rab rbo
op ss sa op ss sa
contains the iesfollowing .co fields: . ies .co .
all m all m
ow ow
ed ed
! !
• StudentID as an integer

• 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

4. In the GradesPrototype.Data namespace, create a struct named Student that


contains the following fields:

• 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

5. In the GradesPrototype.Data namespace, create a struct named Teacher that


contains the following fields:

Th• TeacherID as an integer Th


is is
do d oc
cum um
ma e ma en
• rtaUserName
nt
be as a string rt a.b tb
elo
.ba lon arb
No rbo gs No ng
un sa to un os st
@ Ma a @ oM
au au
• Password
tho
riz
pri
m as artastring tho
riz
p rim art
aB
av Ba av arb
ed era rbo ed era
co b s sa co b s os
pie s.c . pie s.c a.
• FirstNames aas llo a string
om sa
llo
om
we we
d! d!

• 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!

2. In Solution Explorer, rename the UnitTest1.cs file as GradesUnitTests.cs.

3. Add a using directive to the GradesUnitTests file to bring the


GradesPrototype.Data namespace into scope.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 46/55
10/25/2019 20483A - Programming in C# | Skillpipe

4. Define the following tests and support methods:

• StudentTest test method: To create a new student by using the following


information, and then verify that it is created correctly.

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
!

• GradeTest test method: To create a new grade by passing the following


information to the createGrade method, and then verify that it is created correctly.

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!

assessment subject comments

B+ Math Good

A- English Very Good


Th Th
is is
do d oc
C- cum Geography um Could do better
ma e nt ma en
rta be rt a.b tb
.ba lon elo
N r b gs No arb
ng
D- o u os to History un o sa Very spoor
to
na a@ Ma au @ Ma
uth pri rta tho p rim rta
ori ma Ba riz av Ba
ze ve rbo ed era rbo
dc rab co b
op s s.c sa pie s s.c sa
ies . .
5. Build the solution all
ow
and om resolve any compilation errors. s allo om
ed we
! d!
6. Run all tests and verify that they all pass.

7. Close Test Explorer and then close the solution.

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:

1. Examine the dummy data source used to populate the collections

2. Add the LogonFailed event


Th Th
is is
do do
c
um cu
3. mAdd
art the e n Logon_Failed
tb
event handler m art
me
nt
a.b elo a . be
arb ng b arb lon
No o s N o o gs
un s athe t oM un s a@ to
4. Display
au
tho
@ students
pri art for the current teacher 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
5. Set the DataContext i esa .c omfor the page
. i e sa . com
.
llo llo
we we
d! d!
6. Build and test the application

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

1. Open the GradesPrototype solution from the E:\Labfiles\Starter\Exercise 3


folder.

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!

2. In the Logon_Click event, add code to do the following:

Determine whether the user is a teacher by using a LINQ query to retrieve


teachers with the same user name and password as the current user. If the
Th Th
LINQ
is
do query returns a result, then the user issa
i
doteacher.
cu cu
ma me ma me
rta n tb r nt
.ba userelois a teacher, set the UserID, UserRole, t a be
3. If
No
the rbo ng No
.ba
rbo UserName,
lon
gs
and
un s s t un s t
a@ oM a@ oM
CurrentTeacher
au
tho pri
m
aproperties
rta of the SessionContext au
tho object
pri
m
toartthe
aB
appropriate
riz av Ba riz av a
ed era rbo e dc e rbo
fields fromcopthe data bs source,
s.c sa and then raise the LogonSuccess op
rab
ss event. sa
ies . i e sa . c .
all om om
ow llo
we
4. If the user is not aedteacher, ! determine whether the user is a student d! by using a
LINQ query to retrieve students with the same user name and password as the
current user.

5. If the user is a student, set the UserID, UserRole, UserName, and


ThCurrentStudent properties of the SessionContext
Th object to the appropriate
is is
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 50/55
10/25/2019 20483A - Programming in C# | Skillpipe

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
! !

2. In the Logon_Failed event handler, add code to display an error message to


the user.

3. In the MainWindow.xaml XAML editor, locate the definition of the LogonPage


Th Th
is is
page.
do
c
d oc
um um
ma ent ma en
rta be a.brt tb
.ba lon elo
4. NoModify rbo the definition
gs to call the Logon_Failed
No a
method
rbo nfor
gs the LogonFailed
un sa t o u na s a to
au @ M uth @ Ma
pri art pri
event. tho
riz m av aB ori
ze
m a
rta
Ba
ed era arb ve rbo
co b os d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
5. In the MainWindow.xaml.cs llo
we
code, locate the Refresh method.
llo
we
d! d!

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.

Note: DataBinding is also used to retrieve the StudentID of a student.


Th Th
is This binding is used when a user clicksis on a Student on the Student
do do
cum c um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 51/55
10/25/2019 20483A - Programming in C# | Skillpipe

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.

f. Find the details of that student by examining the DataContext of the


Th Th
is is
do d
ubutton.
c oc
me um
ma nt en ma
rta be a.b tb rt
.ba lon elo
Nog. rRaise a rbthe ng
un
bo
sa the
gs StudentSelected event, passing
t o
No
u o s a
student
st
oM
as the second
au @ Ma na @
tho p rim rta u tho p rim a rta
parameter.
riz
ed
av Ba riz
ed
av Ba
era rbo era rbo
co b s s a co b s sa
pie s.c . pie s.c .
sa om sa om
h. In the StudentsPage_StudentSelected
llo
we event handler, llo add code to set
we
d! d!
the CurrentStudent property of the SessionContext object to the student
passed to the event by using the Child property of the e argument.

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!
!

2. In the StudentProfile.xaml XAML editor, locate the definition of the firstName


text block.

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

4. Locate the definition of the lastName text block.

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.

2. Run the application.

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.

7. Close the application and then close the solution.

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 and Takeaways

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.

Test Your Knowledge

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.

public string CountryOfOrigin { get; set; }

public string CountryOfOrigin { get; }

Th public string CountryOfOrigin { set; } Th


is is
do d oc
cu um
ma public me ma en
rta string
nt CountryOfOrigin { get; private set; } rt tb
.ba be a.b elo
lon arb ng
No rb gs No st
unprivateosstring to
a@ CountryOfOrigin
Ma { get; set; } un os
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.
Test Your Knowledge sa
llo
om sa
llo
om
we we
d! d!

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

Test Your Knowledge

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 the correct answer.


Select Th
is is
do oc d
cum um
ma ne m a en
public
rta void
t be HandleOutOfBeans(delegate OutOfBeansHandler)
rta tb
.ba lon .ba elo
No { rbo gs No rbo ng
un sa t u s st
@ o Ma na a @ oM
}autho pri
m rta u tho p rim art
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
public void HandleOutOfBeans(Coffee a . c, EventArgs e) pie s.c a.
sa om sa om
llo llo
{ we we
d! d!
}

public Coffee HandleOutOfBeans(EventArgs e)

public Coffee HandleOutOfBeans(Coffee coffee, EventArgs args)

Th public void HandleOutOfBeans(Coffee c, EventArgsTe) his


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
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 55/55
10/25/2019 20483A - Programming in C# | Skillpipe

Module 4: Creating Classes and Implementing Type-


Safe Collections

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!

Lesson 2: Defining and Implementing Interfaces

Lesson 3: Implementing Type-Safe Collections

Lab: Adding Data Validation and Type-Safety to the Application


Th Th
is is
do d oc
um Module Review and
c Takeaways 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 b os co b os
Module Overview pie
sa
llo
we
s s.c
om
a. pie
sa
llo
we
s s.c
om
a.

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!

• Create and instantiate classes.

• Create and instantiate interfaces.


Th Th
is is
do d oc
• Use generics
cu
me to create type-safe collections. um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 1/71
10/25/2019 20483A - Programming in C# | Skillpipe

Lesson 1 : Creating Classes

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.

• Create static classes and members.

• Describe the high-level process for testing class functionality.


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
Creating Classes and Members
No
un
rbo
s a@
gs
to
No
un
arb
os
a @
ng
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
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 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

Access modifier Description

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

public class DrinksMachine


{ Th Th
is is
do do
// The cu
m following statements are properties cu
me with implicit private
ma en ma nt
rta t be rta be
fields. .ba lon .ba lon
No rbo gs No rbo gs
un sa to un sa to
public
au @
int Age M { get; set; } a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
e e arb ze ve rbo
public string d co rabMake o{s get; set; } d co r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
public stringllowModel { get; set; } llo
we
ed d!
!
// The following statements are methods.
public void MakeCappuccino()
{
// Method logic goes here.
}
Th Th
is is
do d oc
public cu
me
void MakeEspresso() um
ma n ma en
{ rta.ba t belon rt a.b
arb
tb
elo
ng
No rb gs No st
un // oMethod
sa
@ to
logic
Ma goes here. un os
a @ oM
au pri au pri art
tho ma rta tho m aB
riz ve B arb riz av arb
} ed rab ed era
co ss os co bs os
pie .co a. pie s.c a.
sa m sa om
} llo
we
llo
we
d! d!
// The following statement defines an event. The delegate
definition is not shown.
public event OutOfBeansHandler OutOfBeans;

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

class is called an object.

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

var dm = new DrinksMachine();

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.

The following example shows how to add multiple constructors to a class:


Th Th
is is
do d oc
cum um
ma nt e ma en
tb
Addingrta.Multiple
ba
be Constructors
lon
rt 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 DrinksMachine s a o m sa om
llo llo
we we
d! d!
{
public int Age { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public DrinksMachine(int age)
Th Th
is is
{ docu do
cu
ma m en ma me
rtathis.Age t r nt
.ba belo = age; t a .ba be
n lon
No rbo gs No rbo gs
} unau sa to un sa to
@ M a uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
public eDrinksMachine(string era arb make, string zmodel)
ed ve rbo
dc bs os co r ab
op s.c a pie s s.c sa
ies . sa .
{ all om om
o llo
we we
! d d !
this.Make = make;
this.Model = model;
}
public DrinksMachine(int age, string make, string model)
{
Th Th
is is
dothis.Age = age; d oc
cu um
ma me ma en
rtathis.Make nt rt tb
.ba be
lon
= make; a.b elo
No rbo gs No arb ng
un this.Model sa to = model; 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
os
co ss sa co bs a.
pie .c . pie s.c
} sa om sa om
llo llo
we we
d! d!

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

var dm1 = new DrinksMachine(2);


var dm2 = new DrinksMachine("Fourth Coffee", "BeanCrusher 3000");
var dm3 = new DrinksMachine(3, "Fourth Coffee", "BeanToaster
Turbo");

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 and Unboxing


In some scenarios you may need to convert value types to reference types, and vice
versa.
Th For example, some collection classes will
is
Thonly accept reference types. This is
is
do do
um c um c
less likely
ma toenbe an issue with the advent of generic
ma collections.
en However, you still
rta tb rta tb
ba .
lon e ba lon . e
need
Noto berbaware
os gof
s the concept, because a fundamental
No rbo
s
concept
gs of Visual C# is that
un a@ to un a@ to
au p Ma au pri Ma
you can treat
t h ori anymtype
r i
av as
rta an object.
Ba
tho
riz m av
rta
Ba
ze e 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
The process of converting ed a value type to a reference type is called we boxing. To box a
! d!
variable, you assign it to an object reference:

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

Demonstration: Comparing Reference Types and Value


Types
In this demonstration, you will create a value type to store an integer value and a
reference type to store an integer value. You will create a copy of each type, and then
observe what happens when you change the value of the copy in each case.
Th Th
is is
do d oc
cum um
Demonstration
rta
.
ma
nt
be Steps e ma
rt a.b
en
elo
tb
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
m aB
1. Start theriz MSL-TMG1
ed
av
era Ba virtual machine if it
rbo is not already
riz
ed running.
av
era arb
co b s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
2. Start the 20483A-SEA-DEV11-04 we
d!
virtual machine. we
d!

3. Log on to Windows 8 as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba l elo
4. Switch
No rbo to theon gsWindows 8 Start window. 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
riz av B riz av aB
5. Click Visual ed
co
Studio
era
b
2012.
a rbo ed
c
era
b
arb
os
pie s s.c s a o pie s s.c a.
sa . sa
om om
llo llo
6. In Visual Studio,won ed the File menu, point to New, and then click
!
we
d! Project.

7. In the New Project dialog box, in the Templates list, click Visual C#, and then
in the Project Type list, click Console Application.

8. In the Name text box, type ValuesAndReferences


Th Th
is is
do do
c cu
9. In
ma the um Location
en text box, set the location to
ma E:\Democode,
me
nt
and then click OK.
rta tb r t a b
.ba elo .ba elo
No rbo ng No rbo ng
s s t s st
10. Within
un
au thea @ ValuesAndReferences
pri
o M art
namespace,u n a uth
add a @ the
pri
following
oM
art
code:
tho m a o m a
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
struct MyStruct we we
d! d!
{
public int Contents;
}

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:

Value types: 0, 100


Th Th
iReference
sd types: 100, 100 is
oc d oc
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
14. Pressa uth Enter pri to close art the console window. au pri art
ori ma aB tho m 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.
15. Close Visual Studio all
ow
2012.
m sa
llo
om
ed we
! d!

Creating Static Classes and Members

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

public static class Conversions


{ Th Th
is is
do oc d
public c
um static double PoundsToKilos(doubleum pounds)
mart en art m en
a.b tb a.b tb
{ elo elo
No ar bo n gs No a r bo ng
un s t u s st
a @ o M n a @ oM
a//
uth Convert pri argument
art a
from pounds to kilograms
uth pri art
ori ma aB ori ma aB
ze ve a r ze ve arb
double d co kilos rab = pounds b os * 0.4536; d co r ab os
pie ss a . p ies s s a.
sa .co .co
llo m a llo m
return kilos; w w
ed ed
! !
}
public static double KilosToPounds(double kilos)
{
// Convert argument from kilograms to pounds
Th double pounds = kilos * 2.205; Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 13/71
10/25/2019 20483A - Programming in C# | Skillpipe

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!

double weightInPounds = Conversions.KilosToPounds(weightInKilos);

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
!

int drinksMachineCount = DrinksMachine.CountDrinksMachines();

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

DateTime dob = DateTime.Today;


dob.AddDays(7);
dob.AddYears(-24);
Customer testCust = new Customer();
testCust.DateOfBirth = dob;
// The customer's 24th birthday is seven days away, so the age in
Th Th
is is
years doshould
c
be 23. d oc
um um
ma nt e ma en
int
rta expectedAge
be = 23; rt a.b tb
. ba lon elo
No rbo gs No arb ng
sa to os st
//
un Act.
a @ Ma un
au a @ oM
uth pri rta tho p rim art
ori ma Ba riz av aB
ze
int actualAge ve = testDog.GetAge();
rbo ed era arb
dc rab co bs os
op s s sa pie s.c a.
.
// Assert.ies al .co
m sa
llo
om
low we
ed d! age are
// Fail the test ! if the actual age and the expected
different.
Assert.IsTrue((actualAge == expectedAge), "Age not calculated
correctly");
}
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
Notice
No thatrbthe unit gs test method is divided into three a
conceptual s t phases:
No rbo ng
un o sa t o u s oM
au @ M na a @
tho pri art uth pri art
riz m av aB ori m av aB
ed era a rbo zed era arb
co b s s c o b s os
• Arrange. In this pie phase,
sa
s.c you. create the conditions for the ptest.
om
a ies You s.c instantiate
o
a. the
llo a llo m
we w
class you want to test, d! and you configure any input values that ethe d! test requires.

• 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
!

Lesson 2: Defining and Implementing Interfaces

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

An interface is a little bit like a class without an implementation. It specifies a set of


characteristics and behaviors by defining signatures for methods, properties, events,
and indexers, without specifying how any of these members are implemented. When
a class implements an interface, the class provides an implementation for each
member of the interface. By implementing the interface, the class is thereby
guaranteeing that it will provide the functionality specified by the interface.
Th Th
is is
do d oc
cum um
ma ent ma en
In this lesson, you t binterfaces.
r t a.b belo will learn how to define and implement a.b rt 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
riz av B r iz a v
Lesson Objectives ed
co
pie
era
bs
s.c
arb
o sa
.
ed
co
pie
era
bs
s.c
arb
os
a.
sa om sa om
llo llo
we we
After completing this lesson, d! you will be able to: d!

• Explain the purpose of interfaces in Visual C#.

• 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!
!

• A method named ResetPoints.

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.

The following example shows a class that implements the ILoyaltyCardHolder


interface:
Th Th
is is
do d oc
cum um
ma ent en ma
rta be a.b tb rt
Implementing
. b an
l o Interface 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 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.
sa om sa om
public class Customer llo : ILoyaltyCardHolder llo
we we
d! d!
{
private int totalPoints;
public int TotalPoints
{
Th get { return totalPoints; } Th
is is
do d oc
} cum um
ma ent en ma
rta be a.b tb rt
public.ba int lon AddPoints(decimal transactionValue) elo
No r bo gs No a r bo ng
un s t u s st
a @ o M n a @ oM
{ auth pri art a uth pri art
ori ma aB ori ma aB
ze ve a r ze ve arb
int points d co r b
ab= Decimal.ToInt32(transactionValue);
os d co r ab os
pie ss a . p ies s s a.
sa .co .co
m
llo += points; a llo m
totalPoints we we
d! d!
}
public void ResetPoints()
{
totalPoints = 0;

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

// Other members of the Customer class.


}

The details of the implementation do not matter to calling classes. By implementing


the ILoyaltyCardHolder interface, the implementing class is indicating to consumers
that Tithiwill T
s d take care of the AddPoints operation.hOne
is
d
of the key advantages of
oc oc
u
me that they enable you to modularize m me u
interfaces
ma
r
is nt your
ar code.
nt You can change the way
ta. be ta. be
ba lon ba lon
in which
N o u yourr bos class gs implements
to
the interface at any
N o u point,
r b os without gs
to
having to update
na a @ Ma na a @ Ma
uth pri uth pri
any consumer ori
ze
classes
ma
ve
rthat
ta
Ba rely on an interface implementation.
ori
ze
ma
ve
rta
Ba
dc rab rbo dc rab rbo
op s s sa op s s sa
ies .co . ies .co .
all m all m
ow ow
Defining Interfaces ed
!
ed
!

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

Similar to a class declaration, an interface declaration can include an access


modifier. You can use the following access modifiers in your interface declarations:

Access modifier Description

public The interface is available to code running in any assembly.


Th Th
is is
do d
internal c um The interface is available to any codeocwithin um the same assembly, but not
ma en ma en
rta tb available to code in another assembly.r t a.b This tis bethe default value if you do not
.ba elo lon
No rbo ng N arb gs
un sa st specify an access modifier. 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
Adding Interface Members pie
sa
llo
s.c
om
pie
sa
llo
s.c
om
.
we we
d! d!
An interface defines the signature of members but does not include any
implementation details. Interfaces can include methods, properties, events, and
indexers:

• 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:

bool IsFairTrade { get; set; }


Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
rbo an event, ng arb
• To
No define
un s a@
gs
to you use the event keyword,
No
u
followed
os
a
by s t the event handler
o
au Ma na @ Ma
tho pri rta uth pri rta
delegate, rizfollowed
ed
ma
ve by the Ba name of the event: ori
ze
ma
ve Ba
rab rbo dc rab rbo
co ss sa op ss sa
pie .c . ies .co .
sa om all m
llo ow
we ed
d! !
event EventHandler OnSoldOut;

• 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

string this[int index] { get; set; }

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!
!

public interface IBeverage


{
int GetServingTemperature(bool includesMilk);
bool IsFairTrade { get; set; }
Th Th
is is
} do d oc
c um um
ma e nt ma en
rta class
public be Coffee : IBeverage rt a.b tb
.b lo elo
No arb ng No ng arb
un o
sa st u st os
{ @ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
riz av B a riz av arb
privateed int co
servingTempWithoutMilk
era rbo { get; eset; dc }era
os
pie b s s a o pie b s a.
s.c . s.c
s
private int aservingTempWithMilk o m { get; set; } s a o m
llo llo
we we
d! d
public int GetServingTemperature(bool includesMilk)!
{
if(includesMilk)
{
return servingTempWithMilk;
Th Th
is is
do} d oc
c um um
ma e nt en ma
rtaelse be a.b tbrt
.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
return
ed erservingTempWithoutMilk;
ab rb os
e d e r ab os
co ss a co s a.
pie .co . p ies s.co
} s all m all m
ow ow
ed ed
} ! !

public bool IsFairTrade { get; set; }


// Other non-interface members 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 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:

Representing an Object as an Interface Type

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.

Casting to an Interface Type

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
! !

Casting an Interface Type to a Derived Class Type

Coffee coffee3 = beverage as Coffee;


Th Th
is
// OR is
do d oc
cu um
m m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/71
10/25/2019 20483A - Programming in C# | Skillpipe

Coffee coffee4 = (Coffee)beverage;

Implementing Multiple 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 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.

To implement multiple interfaces, you add a comma-separated list of the interfaces


that Tyou
his want to implement to your class declaration.
Th
is Your class must implement
do do
um c um declaration. c
everymamember
en of every interface you add to your
maclass en
rta tb rta tb
.ba elo .ba elo
No r bo ng No ng
rbo
un s st un sast
a @ oM @ oM
au pri art au pri art
The followingtho
riz example
m av shows
aB how to create a class that
tho implements
riz m av a Bmultiple
ed era arb ed era arb
co bs os co bs os
interfaces: pie
sa
s.c
om
a. pie
sa
s.c
om
a.
llo llo
we we
d! d!

Declaring a Class that Implements Multiple Interfaces

public class Coffee: IBeverage, IInventoryItem


{ Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/71
10/25/2019 20483A - Programming in C# | Skillpipe

Implicit and Explicit Implementation


When you create a class that implements an interface, you can choose whether to
T
his his T
implementdo the interface implicitly or explicitly. To implement
c
do
c
an interface implicitly, you
um um
ma en ma e
implement
rta
.
eacht b interface member with a signature
e rta that nmatches
.
tb
e
the member
ba lon ba lon
No b r gs No bo gs r
definition
un in othe
a
sa interface.
@ to
M
To implement an interface
un explicitly,
a
sa
@ you
to
M
fully qualify each
uth pri art uth pri art
ori m aB ori m aB
member name ze so athat
d
ve it is
r aclear
rb that the member belongsze to aavparticular
d er arb interface.
co ab os co ab os
pie ss a. pie ss a.
sa .c om sa .co
llo llo m
we we
The following example shows d! an explicit implementation of the IBeverage
! interface: d

Implementing an Interface Explicitly

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!

// Other non-interface members.


}

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

In most cases, whether you implement an interface implicitly or explicitly is an


aesthetic choice. It does not make a difference in how your class compiles. Some
developers prefer explicit interface implementation because doing so can make the
code easier to understand. The only scenario in which you must use explicit interface
implementation is if you are implementing two interfaces that share a member name.
For example, if you implement interfaces named IBeverage and IInventoryItem, and
Th Th
is is
both interfaces
do
cu declare a Boolean property named dIsAvailable,
oc
u
you would need to
m me m me
art
implement n nt
art explicitly.
a.b at tleast
be
l
one of the IsAvailable membersa.b be
l
In this scenario, the
arb on arb on
No g No gs
compiler
una would
os
a @ be sunable
to
Ma to resolve the IsAvailable
u os
na reference
a @ towithout an explicit
Ma
uth pri rta uth pri rta
ori ma Ba ori ma Ba
implementation. ze
dc
ve
rab rbo ze
dc
ve
rab rbo
op s s sa op s s sa
ies .co . ies .co .
all m all m
ow ow
ed ed
Implementing the IComparable Interface ! !

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.

The following example shows the IComparable interface:


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/71
10/25/2019 20483A - Programming in C# | Skillpipe

The IComparable Interface

public interface IComparable


{
int CompareTo(Object obj);
Th Th
is is
} do
c
d oc
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
@ M @ oM
au p a au p art
t
As you canorisee,
h r the
i ma IComparable
r taB t
interface declares oarizsingle
h r imamethod a B named
ze ve arb ed vera arb
dc rab o co bs os
op
CompareTo. Implementations s s sa of this method must: p s a.
ies .co . ies .co
all m all m
ow ow
ed ed
! !
• Compare the current object instance with another object of the same type (the
argument).

• 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:

Implementing 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 following example shows the IComparer interface:

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

public interface IComparer


{
int Compare(Object x, Object y)
}

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.

The following example shows how to implement the IComparer interface:


Th Th
is is
do d oc
um c um
Implementing
ma
rta
en the IComparer Interface
tb
ma
rt
en
tb
.ba elo a.b 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 b s os co b s os
public class pCoffeeRatingComparer
ies s.c a. : IComparer pies s.c a.
all o m all o m
ow ow
{ ed
!
ed
!
public int Compare(Object x, Object y)
{
Coffee coffee1 = x as Coffee;
Coffee coffee2 = y as Coffee;
Th Th
double rating1 = coffee1.AverageRating;
is is
do do
c
um cu
ma double en rating2 = coffee2.AverageRating; ma me
rta tb r nt
.ba elo t a .ba be
nrating1.CompareTo(rating2); lon
No rbo
return gs No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
} t ho r im r ta t ho r im rta
riz av B arb r ize a 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!

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.

The following example shows how to use a custom IComparer implementation:

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.

• Use generic dictionary collections.

• Create custom generic collections.


Th Th
is is
do d oc
• Create c
uenumerable generic collections. um
ma me ma en
rta nt rt tb
.ba belo a.b 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
Introducing Generics co
pie
sa
b s s.c
om
os
a. co
pie
sa
b s s.c
om
os
a.
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 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 following example shows how to create a generic class:

Creating a Generic Class


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
u s to un os st
publicna class a @ CustomList<T>
Ma a @ oM
uth pri au p art
ori ma rta tho rim aB
ze ve Ba riz av arb
{ dc rab rbo ed era
os
op s sa co bs a.
ies s .co . pie s.c
public T this[int all mindex] { get; set; } sa om
ow llo
ed we
! item) d!
public void Add(T
{
// Method logic goes here.
}
public void Remove(T item)
Th Th
is is
{ doc d oc
um um
ma en ma en
rta// Method tb logic goes here. rt a.b tb
.ba elo elo
No rbo ng No arb ng
sa st os st
} una @ oM 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
op s s.c a. pie s s.c a.
ies o sa om
all m llo
ow we
ed d!
!
When you create an instance of your generic class, you specify the type you want to
supply as a type parameter. For example, if you want to use your custom list to store
objects of type Coffee, you would supply Coffee as the type parameter.

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!

Coffee coffee1 = new Coffee();


Coffee coffee2 = new Coffee();
clc.Add(coffee1);
clc.Add(coffee2);
Th Th
Coffee
is
d firstCoffee = clc[0];
is
d
oc oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 35/71
10/25/2019 20483A - Programming in C# | Skillpipe

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

Type Safety Limitations for Non-Generic Collections

var coffee1 = new Coffee();


var coffee2 = new Coffee();
var tea1 = new Tea();
Th Th
is is
var arrayList1
do
cu
= new ArrayList(); d oc
me um
ma nt ma en
arrayList1.Add(coffee1);
rta be rt a.b tb
. ba lon elo
No rbo gs No arb ng
sa to os st
arrayList1.Add(coffee2);
un
a @ M un
au a @ oM
uth pri art tho p rim art
ori ma aB riz av aB
z
arrayList1.Add(tea1);
ed v era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
// The Sort method sa om
throws a runtime exception because sa om collection
the
llo llo
we we
is not homogenous. d! d!

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!
!

var coffee1 = new Coffee();


var coffee2 = new Coffee();
var tea1 = new Tea();
varThgenericList1
is = new List<Coffee>();This
do do
cu cu
m m e m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/71
10/25/2019 20483A - Programming in C# | Skillpipe

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 !

No Boxing and Unboxing


If you want to store value types in an ArrayList, the items must be boxed when they
are added to the collection and unboxed when they are retrieved. Boxing and
unboxing
Th
i
incurs a large computational cost andTcan
hi significantly slow your
sd sd
oc oc
applications,
ma
u me especially when you iterate over large ma collections.
um
en
By contrast, you can
rta n tb r tb
.ba types elo t a .ba elo
add Nvalue rbo to
ng generic lists without boxing and No unboxing
rbo ngthe value.
ou s st 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
The following example op
ies s shows
s .co
sathe difference between generic
. o p ies
and s non-generic
s.co
os
a.
all m all m
collections with regard ow to boxing and unboxing:
ed
ow
ed
! !

Boxing and Unboxing: Generic vs. Non-Generic Collections

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

Constraining Type Parameters by Interface

public class CustomList<T> where T : IBeverage


{
}
Th Th
is is
do d oc
cum um
ma e
nt ma en
rta b a.b rt tb
.ba elo elo
n arb ng
You can
N o u apply r bos the sfollowing
g
to
six types of constraint
N o un
to typeo sa parameters:
st
na a@ M @ 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.
ies .co . ies .co
Constraint all
ow
m Description all
ow
m
ed ed
! !
where T : <name of interface> The type argument must be, or implement, the specified interface.

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:

Apply Multiple Type Constraints

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!

Using Generic List Collections

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
! !

The List<T> Class


The List<T> class provides a strongly-typed alternative to the ArrayList class. Like
the ArrayList class, the List<T> class includes methods to:
Th Th
is is
do d oc
cum um
ma e ma en
• Addrtan
a.b item.
nt
be rt a.b tb
elo
a lon arb ng
No rbo gs No os st
un sa to un a oM
au @ Ma au @
• Remove tho an item.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.
• Insert an item ats aallowspecified om index. sa
llo
we
om
ed d!
!
• Sort the items in the collection by using the default comparer or a specified
comparer.

• Reorder all or part of the collection.


Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt be t
TheNfollowing
.ba
r b
example
lon
gs
shows how to use the List<T>
N arbclass.lon
g
ou os t 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
Using the List<T> d r d r
pie Class
co ab os co ab os
ss a. pie ss a.
sa .co sa .co
llo m llo m
we we
d! d!

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!

// Write the collection to a console window.


foreach(String coffeeBeverage in coffeeBeverages)
{
Console.WriteLine(coffeeBeverage);
Th Th
} is is
do oc d
c um um
ma nt e ma en
Console.ReadLine
rta
. be ("Press Enter to continue");
rta
.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 b s os
pie s.c . pie s.c a.
sa om sa om
Other Generic List Classes llo
we
d!
llo
we
d!

The System.Collections.Generic namespace also includes various generic


collections that provide more specialized functionality:

• The LinkedList<T> class provides a generic collection in which each item is


Th Th
is to the previous item in the collection andis the next item in the collection.
linkeddo do
c um c um
ma e m en
Eachrta itemntin
be the collection is represented by aaLinkedListNode<T>
rta tb
e object, which
. ba lon . ba lon
No rbo gs No rbo gs
contains
un
au
aavalue
s
@ tof
o M type T, a reference to the parentun
a
LinkedList<T>
s a@ to
Ma instance, a
tho pri art uth pri rta
m a o m
referencerizetod c the previous
av
era Ba item in the collection, and ria
rbo ze reference
dc
av
era toBathe rbo next item in
op b s sa o p bs sa
s . s .
the collection. ies al .co
m
ies
a llo
.co
m
low we
ed d!
!
• The Queue<T> class represents a strongly typed first in, last out collection of
objects.

• 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

Using Generic Dictionary Collections

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:

Using the Dictionary<TKey, TValue> Class


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
// NCreate r bo a new gs dictionary of strings Nwith a r bstring ng keys.
ou s t o un o s st
na a@ oM a @ oM
uth pri at a uth pri art
var coffeeCodes
ori ma = rnew a B Dictionary<String, String>(); ori ma aB
ze ve a rbo ze ve arb
dc rab dc rab os
// Add some oentries pie ss to sthe a . dictionary. o p ies s s a.
sa .co .co
llo m a llo m
coffeeCodes.Add("CAL", we "Café Au Lait"); we
d! d!
coffeeCodes.Add("CSM", "Cinammon Spice Mocha");
coffeeCodes.Add("ER", "Espresso Romano");
coffeeCodes.Add("RM", "Raspberry Mocha");
coffeeCodes.Add("IC", "Iced Coffee");
// TThis
his Th
statement would result in an ArgumentException
is because the
do do
cu cu
key malready me exists. m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/71
10/25/2019 20483A - Programming in C# | Skillpipe
y y
// coffeeCodes.Add("IC", "Instant Coffee");
// To retrieve the value associated with a key, you can use the
indexer.
// This will throw a KeyNotFoundException if the key does not exist.
Console.WriteLine("The value associated with the key \"CAL\" is
{0}",
T Th
his is
do do
cu
coffeeCodes["CAL"]); cu
ma me m me
rta n tb a r nt
.ba elo t a.b bmethod.
elo
// Alternatively,
rbo ng you can use the TryGetValue a r ng
No s N o b o st
un sa to un sa oM
// This au returns @ M
true if the key exists and au false @ if the key does not
tho prim a rta tho p rim art
riz av B r a aB
ed era arb ized vera arb
exist. co bs os co bs os
pie s.c a. pie s.c a.
s om sa om
string csmValueallo=w ""; llo
we
ed d!
!

if(coffeeCodes.TryGetValue("CSM", out csmValue))


{
Console.WriteLine("The value associated with the key \"CSM\" is
{0}", csmValue);
Th Th
is is
} do d oc
cum um
ma ent ma nt e
else rta.b be
lon a.b rt be
lon
No arbo gs No a 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 Ba
ize
Console.WriteLine("The ve arb key \"CSM\" was not ize found"); ve
dc rab os d r ab rbo
op s a co s sa
ies s.c . pie s.c .
} all om sa om
o llo
we we
d! d!
// You can also use the indexer to change the value associated with
a key.
coffeeCodes["IC"] = "Instant Coffee";

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

Using Collection 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 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!

The System.Collections.Generic namespace provides a range of generic


collections to suit various scenarios. However, there will be circumstances when you
will want to create your own generic collection classes in order to provide more
specialized functionality. For example, you might want to store data in a tree structure
T
his Th
or create do a circular linked list.
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
Whereunshould
au
sa you start
@ t o Ma
when you want to create a
u nacustom s a @ collection
oM class? All
tho p rim rta u tho p rim art
aB
collections have riz
ed certain
av
era things
Ba
rbo in common. For example,
riz you awill
ed ve typically
rab arb want to be
co b s s c o s os
pie s.c a . pie s.c a .
able to enumerate s the
all items om in the collection by using a foreach s a loop, om and you will
ow llo
ed w
need methods to add items, ! remove items, and clear the list. The epicture d! on the slide
shows that the .NET Framework provides a hierarchical set of interfaces that define
the characteristics and behaviors of collections. These interfaces build on one
another to define progressively more specific functionality.

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.

The ICollection<T> Interface


The ICollection<T> interface defines the basic functionality that is common to all
generic
Th collections. The interface inherits from IEnumerable<T>,
is
Th
is which means that if
do do
um c u c
you want
ma to eimplement
n ICollection<T>, you must
ma alsomeimplement
n the members
rta tb rta tb
ba .lon e .baelo
defined
No by rbIEnumerable<T>
os gs and IEnumerable.
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 b sadefines co bs os
The ICollection<T> pie
sa
interface
s s.c
om
. the following methods: pie
sa
s.c
om
a.
llo llo
we we
d! d!

Name Description

Add Adds an item of type T to the collection.

Clear Removes all items from the collection.


Th Th
is is
do do
Contains cum Indicates whether the collection contains a specific cu
me value.
ma en ma nt
rta t be rta be
.ba lon .ba lon
CopyTo
No rbo Copies
gs the items in the collection to anNoarray. 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 Ba
Remove ize Removes
ve aarspecific object from the collection. ize ve rbo
dc rab bo dc rab
op s s.c s a o pie s s.c sa
ies . sa .
all om om
ow llo
ed w
The ICollection<T> interface ! defines the following properties: ed!

Name Description

Count Gets the number of items in the collection.


Th Th
is is
d
IsReadOnlyoc Indicates whether the collection is read-only. do
um cu
ma en ma me
rta tb r nt
.ba elo t a .ba be
ng lon
No rbo s No rbo gs
The IList<T> Interface
un
au
s a@
pri
t oM
art
un
a uth
s a@
pri
to
Ma
tho ma aB ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
The IList<T> interface c op
ies ssdefines
.co
sa the core functionality for generic
. op
ies list ss classes.
.co
sa
. You
all m all m
should implement this ow interface if you are defining a linear collection ow
ed ed of single values.
! !
In addition to the members it inherits from ICollection<T>, the IList<T> interface
defines methods and properties that enable you to use indexers to work with the
items in the collection. For example, if you create a list named myList, you can use
myList[0] to access the first item in the collection.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 46/71
10/25/2019 20483A - Programming in C# | Skillpipe

The IList<T> interface defines the following methods:

Name Description

Insert Inserts an item into the collection at the specified index.

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.

The IDictionary<TKey, TValue> Interface


The IDictionary<TKey, TValue> interface defines the core functionality for generic
Th
dictionary Th
classes. You should implement this interface if you are defining a collection
is is
do do
um c cu
of key-value
ma enpairs. In addition to the members it minherits
t a
me from ICollection<T>, the
nt
rta belo r t a be
.ba .ba lon
IDictionary<T>
No rbo
sa
interface
n gs
to
defines methods and Nproperties
o r b o sa
that gs are specific to working
to
un @ M un @ Ma
au pri art a uth pri
with key-value
tho
riz pairs.
m av aB ori
ze
m a
rta
Ba
ed era arb 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
The IDictionary<TKey, we TValue> interface defines the following methods: we
d! d!

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.

The IDictionary<TKey, TValue> interface defines the following properties:

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.

Keys Returns the keys in the collection as an ICollection<T> instance.


Th Th
is is
Values do Returns the values in the collection as an ICollection<T> do instance.
cu cu
ma me m me
rta n tb a 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
Reference
au
tho primLinks: a rta For comprehensive informationau
tho and p rimexamples art
aB
of all of the
riz av B arb r iz a v arb
genericedinterfaces
co
era
bs covered os in this topic, see the System.Collections.Generic
ed
co
era
bs os
pie s.c a. pie s.c a.
Namespaces page all at
om http://go.microsoft.com/fwlink/?LinkID=267802. sa
l l
om
ow ow
ed ed
! !

Creating Enumerable Collections

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.

The IEnumerator<T> interface defines the following methods:


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 48/71
10/25/2019 20483A - Programming in C# | Skillpipe

Name Description

MoveNext Advanced the enumerator to the next item in the collection.

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

Default and Alternative Enumerators

class CustomCollection<T> : IEnumerable<T>


{
public IEnumerator<T> Backwards()
Th Th
is is
{ doc do
cu
um me
ma en ma nt
rta// This tb method returns an alternative
r t a. enumerator.
be
.
ba e lon ba lon
No rb gs No rbo gs
un // oThe sa
@ t
implementation
o M details are u not
n s
shown.
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
co b s s a. c o b s sa
pie s.c pie s.c .
#region IEnumerable<T> sa om Members sa om
llo llo
we we
public IEnumerator<T> d! GetEnumerator() d!

{
// 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! !

throw new NotImplementedException();


}
#endregion
}
Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
.ba lon elo
TheNfollowing example shows how you can useNa a
o udefault bo enumerator or an alternative
r b gs r ng
ou os to s st
na a@ M na a@ oM
uth pri art uth pri art
enumerator ori to iterate
ma through
aB a collection: ori ma aB
ze ve arb ze ve arb
dc rab os dc rab os
op ss a. op s s a.
ies .co ies .co
all m all m
ow ow
Enumerating a Collection ed
!
ed
!

CustomCollection<Int32> numbers = new CustomCollection<Int32>();


// Add some items to the collection.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 50/71
10/25/2019 20483A - Programming in C# | Skillpipe

// Use the default enumerator to iterate through the collection:


foreach (int number in numbers)
{
// …
}

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

public void FillList(params T [] items)


{
foreach (var datum in items)
data.Add(datum);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
Th Th
is is
{ doc d oc
um um
ma ent ma en
rta foreach be (var datum in data) rt a.b tb
.ba lon elo
No rbo gs No arb ng
os st
un
au
{ sa@ to
Ma un
au a @ oM
tho pri rta tho p rim art
riz m av Ba riz av aB
ed yield era return rbo datum; 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!

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.

Lab: Adding Data Validation and Type-Safety to the


Th Th
Application
is
do
cu
m
is
do
cu
m
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 52/71
10/25/2019 20483A - Programming in C# | Skillpipe

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.

• Write data validation code and unit tests.

• 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!

• Virtual Machine: 20483A-SEA-DEV11-04, MSL-TMG1

• User Name: Student

• 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

Exercise 1: Implementing the Teacher, Student, and Grade Structs


as Classes

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

Task 2: Convert the Students and Teachers structs into classes


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
. elo
1. Convert
No
b ar bo the l on Students
gs struct into a class. 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
m a o m aB
2. Createriza ed write-only
av
era Ba
password
rbo property that generates riz
e d a av
newe r ab GUID arb for
os
the
co bs sa co s a.
pie s.c . p ies s.co
default value. allo s o m all
ow
m
we ed
d! !
3. Create a VerifyPassword method that uses the String.Compare method to
check that the password passed to it as a parameter matches the stored

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

o LastName: an empty string

o TeacherID: an empty string


Th Th
is is
6. Convert
do
c
the Teachers struct into a class. d oc
um um
ma e nt ma en
rta be a.brt tb
.ba lon elo
7. NoCreate r bo a write-onlygs password property that a
Nogeneratesr bo angnew GUID for a default
un s t u s st
a @ o M n a @ oM
au a
value tho and pa
riz av
art
rimVerifyPassword
aB method that usesuththe pri
ori String.Compare
ma
art
aB method to
ed era arb ze ve arb
os d r ab
check thatcopthe bs
ies password s.c a.passed to it as a parametercomatches pie ss the ostored
sa
.
o s .co
all m all m
ow ow
password. ed
!
ed
!

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!

o UserName: an empty string

o Password: an empty string

Tho FirstName: an empty string Th


is is
do d oc
cu um
ma me ma en
nt
orta.b LastName: be
lon
an empty string rt a.b tb
elo
No a rbo gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
o t oClass: an tho rim
av empty Ba string
h m rta aB
riz 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!

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.

6. Verify that you can log on as a student.

7. Close the application.


Th Th
is is
do do
8. mIn Visual c cu
u me Studio, close the solution. ma me
art nt rta nt
a.b be .ba be
a lon 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
s s sa
Results: After pcompleting ies s.c
om
thisa . exercise, the Teacher, Student, pie
sa
and s.c Grade
om
. structs
all llo
will be implemented was o
ed classes and the VerifyPassword method we will be called
d!
!
when a user logs on.

Exercise 2: Adding Data Validation to the Grade Class


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt
a.b tb
.ba lon elo
Scenario
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 will define Ba riz av
In this exercise, ed you era rbo a public list of strings called e d Subjects
e r ab
ato
rbo hold the
co bs sa co s sa
pie s.c . p ies s.co .
names of each subject sa
llo thatom can be assessed and then populate a lloit with m valid subject
we we
d! d!
names. You will then add validation logic to the Grade class to ensure that the
subject name appears in the list you created and that the assessment date and
assessment grade contain allowed values. Finally, you will create a unit test project to
verify that your validation code functions as expected.

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

1. Create a list of valid subject names

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.

• If the date is valid, then save it in the appropriate format.

• If the date is not in a valid format, throw an ArgumentException exception.


Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
2. Add .bavalidation code to the Subject property elo that the following
N to ensure
lon arb ng
No rbo gs ou os st
un sa t o na a@ oM
@ Ma met:
requirements
au
tho pri are
m rta uth
ori
pri
ma
art
aB
riz av Ba ze ve arb
ed era rbo dc rab
co b s sa op s os
pie s.c . i s. a.
• Check thats athe llo
specified
om subject is in the list that you shave e
all defined.
com
we ow
d! ed
!
• If the subject is valid, store the subject name.

• If the subject is not valid, then throw an ArgumentException exception.

3. Add validation to the Assessment property to ensure that the following


Th Th
requirements
is
do are met: is
do
cu cu
ma m en ma me
rta t r nt
belo the grade is in the range A+ to E-. t a be
No
• Verify
.ba
rbo thatn gs No
.ba
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
co b os d co r ab
pie s s.c a pie s s.c sa
Note: s a You will . .
om need to use the following regulars expression: a om
llo llo
we we
d! d!

Match matchGrade = Regex.Match(value, @"[A-E][+-]?$");

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:

• Init: to call the CreateData method to initialize the DataSource

• 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

3. Build the solution and resolve any compilation errors.


Th Th
is is
do oc d
cum um
4. mRun
art all tests
e
nt and verify that they all pass. m a rta
en
tb
a.b be . elo
a l on b a ng
No rbo gs No rbo st
un sa t o u na s a oM
5. Closeau Test @ Explorer Ma and then close the solution. 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
d! d!
Results: After completing this exercise, the Grade class will contain validation
logic.

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.

The application currently displays students in no specific order when logged on as a


teacher, but you now want them to be displayed in alphabetical order of last name
and Tfirst name. To achieve this, you decide that Tthe Student class should implement
his his
do
the IComparable<> do of student data. You can then
interface to enable comparison
cu cu
m m e m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 61/71
10/25/2019 20483A - Programming in C# | Skillpipe

add code to the CompareTo method in the Student class, enabling students to be
sorted based on their last name and first name.

Currently, Students are stored in a non-type-safe ArrayList collection. You decide to


modify this so they are stored in a type-safe List collection. Finally, you will sort the
Students data and then run the application to verify that the students are retrieved
Th Th
sd i sd i
and displayed
oc
u
in alphabetical order of their last name oc and first name.
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 o to
The main
na tasks
uth
a @ for
pri thisM exercise
art are as follows: 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 .
1. Run the application a llo m
and verify that the students are not displayed
a llo m in any specific
we we
d! d!
order when logged on as a teacher

2. Implement the IComparable<Student> interface to enable comparison of


students

3. ThChange the Students ArrayList collection into


is
Th a List<Student> collection
is
do do
cu cu
ma m en ma me
nt
4. Sort
rta the data
.ba
t belo in the Students collection r t a .ba be
lon
No rbo n gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
t pri art pri
5. Verifyorthat
h
ize Students
m ave
a Bare retrieved and displayed oin r izeorder m a of
ve
their
rta first name
Ba and
dc rab arb d r rbo
o os co ab sa
last name pies s s.c
om
a . pie
sa
s s.c
om
.
all llo
ow we
ed d!
!

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. !

4. Close the application.

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

Task 2: Implement the IComparable<Student> interface to enable comparison


of students

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!

Task 3: Change the Students ArrayList collection into a List<Student>


collection

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!

Task 4: Sort the data in the Students collection

1. ThIn MainWindow.xaml.cs, in the MainWindow


is
Th
is
constructor, after calling the
do do
cu cu
mDataSource.CreateData
art
me
nt
method, add a method
ma mcall
en to sort the data in the
a.b be rta tb
lon .ba elo
NoStudents ar bo collection.
gs No 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
co bs sa co ab os
pie s.c . p ies s s a.
sa om .co
llo a llo m
we we
d! d!
Task 5: Verify that Students are retrieved and displayed in order of their first
name and last name

1. Build the solution and resolve any compilation errors.


Th Th
is is
2. Run
do the application without debugging.
cu
d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 63/71
10/25/2019 20483A - Programming in C# | Skillpipe

3. Log in as vallee with a password of password.

4. Verify that the students are displayed in order of ascending last name.

5. Close the application.

6. ThIn Visual Studio, close the solution. 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
No rbo st N ou r b os gs
un sa o n a to
au @ M au @ Ma
Results: thoAfterprcompleting
riz
im
av
art
a Ba
this exercise, the application t h o riz
will
pri display
m av
rta the students
Ba
in
ed era r e e rbo
alphabetical order co
pie
of b last
s s.c
name
bo
s a.
and then first name. dc
o pie
rab
s s.c sa
sa sa .
om om
llo llo
we we
d! d!

Exercise 4: Enabling Teachers to Modify Class and Grade Data

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.

The main tasks for this exercise are as follows:


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 64/71
10/25/2019 20483A - Programming in C# | Skillpipe

1. Change the Teachers and Grades collections to be generic List collections

2. Add the EnrollInClass and RemoveFromClass methods for the Teacher class

3. Add code to enroll a student in a teacher’s 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
! !

Task 1: Change the Teachers and Grades collections to be generic List


collections

1. In Visual Studio, from the E:\Labfiles\Starter\Exercise 4 folder, open the


Th Th
is is
do
GradesPrototype.sln solution. d oc
cu um
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a ng
2. NoIn therbData
o folder,
gs in the DataSource.cs code,
No rbo
change the
s t Teachers collection
un sa t o u na s a oM
au @ Ma u @
tho p rim rta tho p rim art
to be arizegeneric av List Bcollection.
a riz
ed
av aB
arb
dc era rbo era
op b s s c o b s os
ies s.c a . pie s.c a.
all o m s all o m
3. Change the Grades ow
ed
collection to be a generic List collection. ow
ed
! !

4. In the CreateData method, modify the creation of the Teachers collection to


create a new generic List collection.

5. In the CreateData method, modify the creation of the Grades collection to


Thcreate a new generic List collection. 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
ed rbo e e rb
Task 2: Add the co EnrollInClass
pie
rab
ss sa and RemoveFromClass d cmethods
op
rab
ss forosthe a.
Teacher
sa .c . i e sa . c
class om om
llo llo
we we
d! d!

1. In the Data folder, in the Grade.cs code, in the Teacher class, implement the
EnrollInClass method as follows:

• Verify that the student is not already enrolled in another class.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 65/71
10/25/2019 20483A - Programming in C# | Skillpipe

• If the student is not in another class, set the TeacherID property of the
student to the current TeacherID.

• If the Student is in another class, throw an ArgumentException exception to


show that the student is already assigned to a class.

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 !

exception to show that the student is not assigned to this class.

3. In the Teacher class, implement the AddGrade method as follows:

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.

TaskT 3: Add code to enroll a student in a teacher’s


T class
his his
do do
cum cu
ma e ma me
rta nt rt nt
.ba belo a .ba be
ng lon
1. NoIn therbControls
un o s s t
folder, in the AssignStudentDialog.xaml.cs
N o un
r b o s
gs
to
code, in the
a@ oM a@ M
au a
tho
Student_Click
riz
pri
ma method,
ve
art
aB write code as follows:uthoriz primav arta B
ed rab a rbo ed era arb
co ss sa co bs os
pie .co . p ies s.co a.
sa
• Add a try block. llo
we
m a llo
we
m
d! d!

• 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.

• Add a catch block to display a message to the user if an exception occurs.

2. In the Refresh method, write code as follows:


Th Th
•is dFind
oc
all unassigned students with a TeacherID is
do of zero.
um cu
ma en ma m en
rta tb rta tb
. e . elo
No• If athere
b lare
on no unassigned students, show the ba txtMessage ng box and hide the
rbo gs No rbo st
un sa to un sa oM
alist
uth control. @ M au @
pri art tho pri art
ori ma aB r ma aB
ze ve arb ized vera arb
dc rab o co bs os
op s s sa p s a.
ies .co . ies .co
• If there are aunassigned llo m students, hide the txtMessageallbox ow
and
m show the list
we ed
control bound tod! the list of unassigned students. !

3. In the StudentsPage.xaml.cs code, in the EnrollStudent_Click method, add


code to use the AssignStudentDialog to display the unassigned students.
Then refresh the display to show any newly enrolled students.
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 arbng
un sa to un osst
@ a @ oM
a
Task 4: Add codepri toMenable a teacher to removeauthe student from a B the assigned
uth art tho p rim art
ori m av aB riz av
ze era a ed era arb
class dc
op bs
rbo
sa co b s os
a.
ies s.c . pie s.c
all om sa om
ow llo
ed we
! d!
1. In the StudentProfile.xaml.cs code, in the Remove_Click method, write code
as follows:

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.

• Add a catch block to display a message to the user if an exception occurs.

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

Task 5: Add code to enable a teacher to add a grade to a student

1. In the StudentProfile.xaml.cs code, in the AddGrade_Click method, write


code to add a grade to a student as follows:

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
!

• Save the grade to the list of grades.

• Add the grade to the current student.

• 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

1. Build the solution and resolve any compilation errors.

2. ThLog in as vallee with a password of password.


is
Th
is
do do
cu cu
ma m en ma me
rta a student tb r nt
3. Add .ba elo
ng
with the following details: t a .ba be
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
• First name: Darren llo
we
llo
we
d! d!

• Last name: Parker

• 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

4. Verify that Darren Parker is added to the student list.

5. Remove the student Kevin Liu from the student list.

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

7. Verify that the grade information is added to the Report Card.


Th Th
is is
do d
oc
cum um
8. mLog
art on e as
nt the student Darren Parker and verify
ma rta
that
en the grade information from
tb
a.b be . elo
a l on b a ng
Nothe previous
rbo gsteps
s is displayed in the Report
No Card. rbo 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
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
Note: A username llo
we
is generated by taking a user’s last llo name and the first
we
d! d!
initial of their first name. The username for Darren Parker is parkerd.

9. Close the application.

10. ThIni Visual Studio, close the solution. Th


is
sd 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
un s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho
Results: After riz
ed
completing
m av a Ba this exercise, the application o riz will enable
e
m av a Bteachers
arb
to add
era rbo d e r ab
and remove students co bsfrom theirsa classes, and to add grades co to students. s os
pie s.c . p ies s.co a.
sa om a m
llo llo
we we
d! d!

Module Review and Takeaways

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#.

Test Your Knowledge

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?

Select the correct answer.

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!

Test Your Knowledge

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 the correct answer.


Select Th
is is
do oc d
cum um
ma e nt m art en
rpublic
ta. class
be DoubleEndedQueue<T> : IEnumerable<T> a tb
elo
ba lon . ba
No rbo gs No rbo ng
un sa to un sa st
@ M @ oM
au
public class p DoubleEndedQueue<T>
a : ICollection<T> au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
ed era ed era
co DoubleEndedQueue<T>
bs o sa co bs os
public class pie s.c . : IList<T> pie s.c a.
sa om sa om
llo llo
we we
public class DoubleEndedQueue<T> d! : IList<T>, IEnumerable<T> d!

public class DoubleEndedQueue<T> : IDictionary<TKey,TValue>

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

Module 5: Creating a Class Hierarchy by Using


Inheritance

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!

Lesson 2: Extending .NET Framework Classes

Lab: Refactoring Common Functionality into the User Class

Module Review and Takeaways


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
sa to os st
Module Overview
un
au
tho
riz
@
pri
m av
Ma
rta
Ba
un
au
tho
riz
a @
p rim
av
oM
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
The concept of inheritance d! is central to object-oriented programming d! in any

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

• Create base classes and derived classes by using inheritance.

• Create classes that inherit from .NET Framework classes.

Lesson 1 : Creating Class Hierarchies


Th Th
is is
do d oc
cum um
ma nte ma en
rta b a rt tb
Rather e elo
No than
. ba creating lon new classes from nothing,N in many . ba cases ng you can use an
rbo gs o r b o st
un sa t o u s a oM
existingaclass
uth @
aspri a base Ma for your new class. This isnaknown u @
as
p inheritance.
art Your class
ori ma r taB t h ori r ima aB
ze ve arb zed vera arb
inherits all thed membersco
pie
rab from
ss os the base class, and you simply
a co include
p bs
s
the os functionality
a.
sa .c . i e sa . c
om om
that you want to add oto l l we the base class’s capabilities. This way, your
l l ow class becomes a
ed
d! !
more specialized version of the base class. This concept of inheritance is one of the
main pillars of object-oriented programming.

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!

• Create base classes.

• Create base class members.

• Create classes that inherit from base classes.


Th Th
is is
do d oc
umc um
• Call
ma base enclass methods and
tb
constructors from
ma within
en a derived class.
t
rta elo rta be
.ba .ba lon
No r bo ng No rbo gs
un s st un sa 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
What Is Inheritance? pie
sa
s.c
om
a. pie
sa
ss
. com
sa
.
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/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.

Inheritance enables you to build hierarchies of progressively more specialized


classes.
Th Rather than creating a class from nothing,
Th you can inherit from a more
is is
oc d oc d
general
m
base
um class to provide a starting point for your
e m
umfunctionality.
e
art nt art nt
a.b be a.b be
a lon arb lon
No rbo gs No gs os
un sa to un
a@ to
a @ Ma a class a Ma
For example,
uth
ori
you
pri define
m rta named Beverage, uas
tho shown pri below:
m rta
ze ave 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
llo
The Beverage Classwed o we
d!
!

public class Beverage


{
Tprotected
his int servingTemperature; Th
is
do do
public c u string Name { get; set; } cu
ma m en ma me
rta tb r nt
. elo t a . be
b b lon
Npublic
ou
arb bool
os
ng IsFairTrade { get; set;
s N o
} arb
o gs
na a@ t oM un s a@ to
public uth intpri GetServingTemperature()
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
ies .co . ies .co .
all m all m
return servingTemperature;o we o we
d! d!
}
}

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!
!

public class Coffee : Beverage


{
public string Bean { get; set; }
public string Roast { get; set; }
Th Th
is is
do
public string CountryOfOrigin { get; set;do }
cu cu
ma m en ma me
rta tb rta nt
} .ba elo .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 rim rta tho
riz av Ba av Ba riz
ed e rab rbo era rbo ed
co s s a co b s sa
pie s.c . pie s.c .
Note: In object-oriented
sa
llo
om programming, the terms derives s a and inherits
llo
om are used
we we
interchangeably. Saying d! that the Coffee class derives from the d! Beverage

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:

Calling Base 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/43
10/25/2019 20483A - Programming in C# | Skillpipe

Coffee coffee1 = new Coffee();


// Use base class members.
coffee1.Name = "Fourth Espresso";
coffee1.IsFairTrade = true;
int servingTemp = coffee1.GetServingTemperature();
// Use derived class members.
Th Th
sd i is
coffee1.Bean
oc = "Arabica"; d oc
u me um
ma nt ma en
rta
coffee1.Roast be = "Dark"; rt a.b tb
.b l on elo
No arb g No ng arb
un sa o st un st os
coffee1.CountryOfOrigin
@ oM = "Columbia"; 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
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we
As shown in the above dexample,
! you can call members of a baseweclass d! in the same
way that you call members of the class itself.

Creating Base 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!

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.

The following example shows how to declare an abstract class:


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/43
10/25/2019 20483A - Programming in C# | Skillpipe

Declaring an Abstract Class

abstract class Beverage


{
}
Th Th
is is
do d oc
c um um
ma nt e ma en
rta b a.brt tb
.ba elo elo
n arb ng
The abstract
N ou r bos keyword g st indicates that the class cannotN o un
beo sa instantiated
st directly; it exists
na a@ oM @ oM
uth pri art au p a
solely to defineori ormaimplement aB members for derived classes. tho riIf
mayou attempt
rta to
ze ve a riz ve Ba
dc rab rbo e dc rab rbo
op sa sa
instantiate an abstract ies sclass
s.c you . will get an error when youopbuild ies your
ss
.co code. .
all om all m
ow ow
ed ed
! !
An abstract class can contain both abstract and non-abstract members. Abstract
members are also declared with the abstract keyword and are conceptually similar to
interface members, in that abstract members define the signature of the member but
do not provide any implementation details. Any class that inherits from the abstract
classThmust
is
d
Th
provide an implementation for the abstract
is
d
members. Non-abstract
oc oc
me u me u
members,
ma
r
however,
nt can be used directly by derived
ma
r
classes.
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 pri
tho rta
The following riz example
ed
m av
era
illustrates
Ba the difference between
riz abstract
ed
m av
era
and Ba non-abstract
rbo rbo
co b s sa co b ss sa
members: pie
sa
s.c
om
. pie
sa . co
m
.
llo llo
we we
d! d!

Abstract and Non-Abstract Members

abstract class Beverage


Th Th
{ is is
do d oc
c um um
ma Non-abstract
// nt e
members. ma en
rt
a.b b a.b rt tb
elo elo
N// ar bo n gclasses No a r bowithout ng
o u Derived s a@
st
oM can use these members
un s a
s t modifying
oM them.
na a @
uth pri art uth pri art
o
publicrizestring m av Name a Ba { get; set; } o riz m av aB
dc e rab rbo e dc e rab arb
op s sa o s os
public bool s
ies IsFairTrade.co . { get; set; } p ies s.co a.
all m all m
ow ow
// Abstract members. ed ed
! !
// Derived classes must override and implement these members.
public abstract int GetServingTemperature();
}

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

public sealed class Tea : Beverage


{ Th
is is
Th
do do
// … u c cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
} N n lon
ou r bos g st N o r b o gs
na a@ oM un sa to
uth a uth @ Ma
pri art pri 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 . .
You can apply the sealed all ommodifier to classes that inherit froms other all om
classes and
ow ow
ed ed
classes that implement interfaces. ! You cannot use the sealed modifier ! and the
abstract modifier on the same class, as a sealed class is the opposite of an abstract
class—a sealed class cannot be inherited, whereas an abstract class must be
inherited.

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.

The following example shows how to create a virtual method in a class:

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 modifiers for class members:

Access Details
Modifier

public The member is available to code running in any assembly.


Th Th
is is
do do
protected um c The member is available only within the containing cu class or in classes derived from
ma en ma me
rta tb r nt
.ba elo the containing class. t a.b b elo
No rbo ng No arb ng
un sa s to un o sa st
@ M @ oM
a
internal th u p The amember is available only to code withina u the p
current art
assembly.
ori r i ma r taB t h ori r ima aB
ze ve arb zed v era arb
dc rab o co bs os
op s s sa p s a. to types
protected internal ies The member .co is available to any code within the current
. ies assembly, .co and
all m all m
ow
derived ow
ed from the containing class in any assembly. ed
! !

private The member is available only within the containing class.

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:

Declaring a Class that Inherits 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

public class Coffee : Beverage


{
}

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
! !

Because GetServingTemperature is a virtual method, you can override it in a


derived class. To override a virtual method in a derived class, you create a method
with the same signature and prefix it with the override keyword.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/43
10/25/2019 20483A - Programming in C# | Skillpipe

The following example shows how to override a virtual method in a derived class:

Overriding a Virtual Method by Using the override Keyword

public class Coffee : Beverage


Th Th
is is
{ do d oc
cum um
ma nt e ma en
rta
protected be bool includesMilk; rt a.b tb
.b l on elo
No arb g No ng arb
un o st
sa int servingTempWithMilk; un st os
private @ oM a @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
privateed int servingTempWithoutMilk;
era
o
ed era
os
co bs sa co bs a.
pie s.c . pie s.c
public override sa om GetServingTemperature()
int sa om
llo llo
we we
d! d!
{
if(includesMilk) return servingTempWithMilk
else return servingTempWithoutMilk;
}
}
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt
a.b tb
.ba lon elo
a ng
You Ncan
o u use rbo the same
s a
gs
t o
approach to override properties,
No
u
rbo indexers,
s a
st
oM
and events. In each
na @ Ma na @
uth pri rta u tho member p rim a rt
case, you can ori
ze
only ma override
ve Ba a base class member if the riz av is amarked Ba as virtual
dc rab rbo ed era rbo
op You scannot sa c op b ss sa
in the base class. ies s.c
om
override
. constructors. ies .co .
all all m
ow ow
ed ed
! !
You can also override a base class member by using the new keyword:

Overriding a Virtual Method by Using the new Keyword

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.

ThReference Links: For a detailed explanation Th of the differences in behavior


is is
do do
betweencu
me
the override keyword and the new keyword,
cu
me
see Knowing When to
ma n m a n
Use
rta Override
.ba
tb
elo and New Keywords (C# Programming rta
.ba
t b Guide) at
elo
No rbo ng N r b ng
http://go.microsoft.com/fwlink/?LinkID=267803.
un sa
@
s to o un o sa
@
st
oM
au p M 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
Sealing Overridden Members we
d!
we
d!

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.

Calling Base Class Constructors and Members

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.

• You want to call a base class method from a property accessor.

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

The following example shows how to call base class constructors:

Calling Base Class Constructors

public class Beverage


Th Th
is is
{ do d oc
cum um
ma nt e ma en
rta
public Beverage()
be rt a.b tb
.b l on elo
No arb g No arbng
o
sa st st
os
{ una @ oM un
au a @ oM
uth pri art tho p rim art
ori ma aB riz av aB
z
// Implementation
ed v era arb details not shown. 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!
public Beverage(string name, bool isFairTrade, intd!servingTemp)
{
// Implementation details are not shown.
}
// Other class members are not shown.
Th Th
is is
} do d oc
cum um
ma n e ma
en
publicrta class t be Coffee : Beverage a.b tb
rt
.ba lon elo
No rbo gs No a rbo ng
un sa t u s st
{ au @ o Ma na a @ oM
tho prim rta u tho p rim art
aB
publicrizeCoffee()
dc
av
era B a rbo
riz
ed
av
era arb
op b s s c o b s os
ies s.c a . pie s.c a.
{ all o m s all o m
ow ow
ed ed
!
// This constructor implicitly calls the default ! Beverage

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!

// This calls the Beverage(string, bool, int) constructor.


// You can include additional code here:
Bean = bean;
Roast = roast;
Th Th
} is do
c
is
d oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 14/43
10/25/2019 20483A - Programming in C# | Skillpipe

public string Bean { get; set; }


public string Roast { get; set; }
public string CountryOfOrigin { get; set; }
}

Th previous example shows, you must call the


As the Th base class constructor from your
is is
d oc d oc
u
medeclaration. You cannot call the base meconstructor from within your u
constructor
ma
r nt maclass
r nt
ta. be ta. be
ba lon ba lon
constructor
N ou r bomethod
s
g s t body. You can use the named N o u parameters
r b os gs from your constructor
to
na a @ o M na a @ Ma
uth pri art uth pri
declarationorias ze
arguments
ma
ve
a B to the base class constructor. ori
ze
ma
ve
rta
Ba
dc rab a rbo dc rab rbo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
ow ow
Calling Base Class Methods from a Derived Class
ed
!
ed
!

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: Calling Base Class Constructors


In this
Th demonstration, you will step through the T
execution
h
of an application. The
is is
oc d oc d
solution
m
includes
um
e
a class named Coffee that inherits
m
from
um
e
a class named Beverage.
ar nt ar nt
ta. be ta. be
TheNCoffeeba class
rb
lon includes two constructors—one that
g N
ba implicitly
rb
lon
g
calls the default base
ou os st ou os st
na @ a o na @ base a o
class constructor,
uth pri and
m
Maone that explicitly calls an alternative
rta uth pri
m
Maclass constructor.
rta
ori av Ba ori av Ba
ed z z
The application p
era
cocreates
s
rbo
bs instances
sa of the Coffee class byedusing
co
p
era
both r o
bs of bthese
s sa
ies .co . ies .co .
m
all cases, m
all constructors
constructors. In both ow
e
you can observe how derived class ow
e
call
d! d!
base class constructors. You will also see how derived class constructors pass
argument values to base class constructors.

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
! !

Note: If necessary, click Switch User to display the list of users.

4. Switch to the Windows 8 Start menu.


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/43
10/25/2019 20483A - Programming in C# | Skillpipe

5. Click Visual Studio 2012.

6. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.

7. In the Open Project dialog box, browse to E:\Democode, click


ThBaseConstructors.sln, and then click Open. Th
is is
do do
cu cu
mIn me m me
8. art Solution
a.b
nt
b Explorer, double-click Beverage.csa r t a.b
and nt review the contents of the
be
elo lon
No arbo ng N a r b gs
class.
un sa
@
st
o ou
n
os
a @ to
au pri M art au pri Ma
tho m a t h o m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
9. Note that cthe op Beverage
ies
bs
s .co
s class
a .
contains a default constructor
c o p ies
b sand
s.co
ansa.alternative
all m all m
constructor. ow
ed
ow
ed
! !

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

constructor unless you specify an alternative base class constructor.

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.

30. Press F5 to run the remainder of the application.

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!

Lesson 2: Extending .NET Framework Classes

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.

• Create classes that inherit from generic types.

• Create extension methods for .NET Framework types.


Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
Inheriting from .NET Framework Classes
No
.ba
rbo
s
lon
Nogsarb
os
elo
ng
s
un 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 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

the class is not sealed or static.

• 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!

You should consider creating a custom exception type when:

• 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!

Creating Custom Exception Types


All exception classes ultimately derive from the System.Exception class. This class
provides a range of properties that you can use to provide more detail about the error
condition.
Th
is For example: Th
is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon on el
arb
• The
No Message
un
rbo
sa property
gs
to
enables you to provide
No moreo information
u s
gs
t
about what
@ M na oM
a@
au uth
happened tho aspra im text astring.
rta ori
pri
m
art
aB
riz av Ba ze av arb
ed era rbo dc era
co b s sa op b s os
pie s.c . ies s.c a.
sa om o m
• The InnerException llo
we property enables you to identify another a llo Exception
we instance
d! d!
that caused the current instance.

• 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:

1. Create a class that inherits from the System.Exception class.

2. Map your class constructors to base class constructors.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 23/43
10/25/2019 20483A - Programming in C# | Skillpipe

3. Add any members if required.

The following example shows how to create a custom exception class:

Creating a Custom Exception Type


Th Th
is is
do d oc
cum um
ma e
nt en ma
rta b a.b tb rt
.ba elo elo
No rbo ng N arb ng
un System; sa s to o un o sa st
using @ M @ oM
au p a au p art
tho rim rta tho rim aB
riz av B arb r iz a v arb
public class ed LoyaltyCardNotFoundException
era
o
: Exception
ed era
os
co bs sa co bs a.
pie s.c . pie s.c
{ sa om sa om
llo llo
we we
d! d!
public LoyaltyCardNotFoundException()
{
// This implicitly calls the base class constructor.
}
public LoyaltyCardNotFoundException( string message) :
Th Th
is is
do
base(message) d oc
c um um
ma ent nt ma e
{ rta.b be
lon a.b be
lon
rt
No arbo gs No a rbo gs
} una sa to un sa to
uth @ M a uth @ Ma
pri art pri rta
ori m a aB ori m a BException
publiczeLoyaltyCardNotFoundException(string
dc
ve
rab arb ze message,
d
ve
r ab
arb
op s os co s os
ies s.c a . pie s.c a.
inner) : base(message, all o m s all o m
o we o we
d! d !
inner)
{
}
}

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)
{

Th throw new LoyaltyCardNotFoundException("The


T card number
is his
do do
provided cu was not
me
cu
me
ma nt ma nt
rta be rt a.b be
found"); .ba lon arb lon
No rbo gs No os gs
un s a@ to un a@ to
a}uth pri Ma au pri Ma
ori ma rta tho ma rta
ze ve Ba riz ve Ba
else d co rab rbo ed rab rbo
ss sa co ss sa
pie .c . pie . c .
sa om sa om
{ llo
we
llo
we
d! d!
return customer.TotalPoints;
}
}
// Other class members are not shown.
} 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/43
10/25/2019 20483A - Programming in C# | Skillpipe

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.

• Specify a type argument for the base type.

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: ! !

Inheriting from a Generic Base Type Without 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:

Inheriting from a Generic Base Type by Specifying a Type Argument

public class CustomList : List<int>


hiT Th
is
{ } s docu d
um
oc
ma m en ma en
rta tb 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 r t h r
In the above riz example,
ed
av when
taB
arb
you instantiate the CustomList ori
zed
imaclass,
v
ayouBa do not need
era era rbo
co bs o sa co bs sa
to specify a type iparameter.
p es s .co Any base class methods or properties
. p ies s .that
co referenced
.
all m all m
ow o
the type parameter are ednow strongly typed to the Int32 type. For wexample, ed the
! !
List.Add method will only accept arguments of type Int32.

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!

Inheriting from a Base Type with Multiple Type Parameters

// Pass all the base type parameters on to the derived class.


T
his his T
public do class CustomDictionary1<TKey, TValue>
do : Dictionary<TKey,
cu cu
m me m me
TValue>
art { }n tb art nt
a.b elo a . be
arb ng b arb lon
No o s N o o gs
// Provide
un s a@an argument
t oM for one of the base
un types a@ parametersto and pass
au pri art a uth pri Ma
tho r ta
the otherrizeonemato ve theBar
a ori
ze
ma
ve Ba
rbo
dc rab bo dc rab
op ss sa op ss sa
derived class.s a i e .c . i e sa . c .
om om
llo llo
we we
public class CustomDictionary2<TValue> d! : Dictionary<int, d! TValue> { }
// Provide arguments for both of the base type parameters.
public class CustomDictionary3 : Dictionary <int, string> { }

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

As an alternative to using inheritance to extend a type, you can create extension


methods. When you create extension methods, you are creating methods that you
can call on a particular type without actually modifying the underlying type. An
extension method is a type of static method. To create an extension method, you
create a static method within a static class. The first parameter of the method
specifies the type you want to extend. By preceding the parameter with the this
Th Th
is is
keyword,do you indicate to the compiler that your method
cu
do
cu is an extension method to
m me ma me
art
that type. nt rt nt
a.b be a.b be
arb lon arb lon
No os gs No os gs
un a @ to un to a@
au pri Ma au pri Ma
tho m rta thom rta
riz av Ba riz av
The following edexample era shows rbo how to create an extensioned method era forBathe rbo
co b s sa co bs sa
pie s.c . pie s.c .
System.String type: sa
llo
om sa
llo
om
we we
d! d!

Creating an Extension Method

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
!

Bringing an Extension Method Into Scope

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:

Calling an Extension Method


Th Th
is is
do d oc
cum um
ma e
nt ma en
rta be rt tb
Console.WriteLine("Please
.ba lon type some text a.that
ba contains
elo
n
numbers and
No rbo gs No rbo gs
sa to sa to
then unpress
au
tho
@Enter");
pri Ma un
au
tho
@
pri Ma
m rta m rta
riz av Ba riz av Ba
e e
string textd c = Console.ReadLine();
rab rbo ed era rbo
op s sa co b s sa
ies s .co . pie s.c .
a m sa om
if(text.ContainsNumbers) llo
we
llo
we
d! d!
{
Console.WriteLine("Your text contains numbers. Well done!");
}
else
{
Th Th
is is
do
Console.WriteLine("Your text does not docontain numbers. Please try
cu cu
ma m en ma me
rta tb rta nt
again.");.ba elo .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
} au @
p M 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 .co . pie s.c .
sa m sa om
llo llo
we we
d! d!

Demonstration: Refactoring Common Functionality into the


User Class Lab
In this demonstration, you will learn about the tasks that you will perform in the lab for
this module.
T Th
his is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
Lab: Refactoring Common Functionality
No
un
.ba
rbo
s a@
No
lon
un
gs
to o s a
elo
ng into the User
st
oM
arb
au au Ma @
pri pri art
Class tho
riz
ed
co
ma tho
ve riz
rab
rta
ed Ba
c
mav
rbo era
aB
arb
o
pie ss sa op bs sa
.c . ies s.c .
sa om all o m
llo ow
we ed
d! !
Scenario
You have noticed that the Student and Teacher classes in the Grades application
contain some duplicated functionality. To make the application more maintainable,
you decide to refactor this common functionality to remove the duplication.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/43
10/25/2019 20483A - Programming in C# | Skillpipe

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:

• Use inheritance to factor common functionality into a base class.


Th Th
is is
do oc d
• Implement
m
um polymorphism by using an abstract method.
c
m
um
art en art en
a.b tb a.b tb
elo elo
No arbo ng No arb ng
• Create
un a custom
sa s t exception class. 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 b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
Estimated Time: 60 minutes d! d!

• Virtual Machine: 20483A-SEA-DEV11-05, MSL-TMG1

• User Name: Student


Th Th
is is
do d
• Password: cu
me
Pa$$w0rd oc
um
ma 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
Exercise 1: Creating and Inheriting from the User Base Class
ed
co
pie
rab
ss
rbo
sa
ed
co
pie
era
bs os
a.
.c . s.c
sa om sa om
llo llo
we we
d! d!

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. Run the application and test the log on functionality

TaskTh1: Create the User abstract base class Th


is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
NoStart rthe a rbo ng
1. un
bo MSL-TMG1
sa
gs
t o virtual machine if it is
Nonot already
u s a
running.
st
oM
au @ Ma na @
tho p rim rta u tho p rim art
riz av B riz av aB
e era a rbo ed era arb
2. Start thed 20483A-SEA-DEV11-05
co
pie b s s.c s a virtual machine and c o log
pie
on b s as
s.c
Student
os
a. with
sa . sa
om om
the password Pa$$word. llo
we
llo
we
d! d!

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
! !

Task 3: Run the application and test the log on functionality

1. ThBuild the solution and resolve any compilation


is
Th
is errors.
do do
cu cu
ma m en ma me
r t r nt
2. Run.bathe application.
t a belo 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
3. Log onrizeas vallee m av (aa Bteacher)
arb
with a password of opassword.
r ize
m a ve Ba
dc era d r ab rbo
op bs os co s sa
ies s.c a . pie s.c .
a om sa om
4. Verify that a listlloof we students for this teacher appears in The llo School of
we Fine Arts
d! d!
window.

5. Select student Kevin Liu and verify that the report card listing the grades for this
student appears.

6. ThLog off and then log on as liuk (a student)Twith


is his a password of password.
do do
cu cu
ma me ma me
rta nt r nt
7. Verify.ba that b the
elo report card for Kevin Liu is displayed
t a .ba bagain.
elo
No rbo ng No rbo ng
un s s t u s st
a @ o M n a @ oM
au pri art a uth pri art
tho
8. Log offrizeand then m av close
a Ba the application o riz
e
m av aB
arb
dc e rab rbo dc e rab
op s sa o s os
ies s .co . p ies s .co a.
a m a m
9. In Visual Studio, llo close the solution.
we
llo
we
d! d!

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

Exercise 2: Implementing Password Complexity by Using an


Abstract Method

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.

The main tasks for this exercise are as follows:

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
! !

5. Run the application and test the change password functionality

TaskTh1: Define the SetPassword abstract method


Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 35/43
10/25/2019 20483A - Programming in C# | Skillpipe

1. In Visual Studio, open the GradesPrototype.sln solution from the


E:\Labfiles\Starter\Exercise 2 folder.

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!

Match numericMatch = Regex.Match(pwd, @".*[0-9]+.*[0-9]+.*");

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

Task 3: Set the password for a new student

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.

The ChangePasswordDialog window looks like this:


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 37/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 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.

6. Implement the logic for the ok_Click method:

a. Get the details for the current user.


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be Note: You can use the SessionContext.UserRole rt
a.b tb
.ba
rbo
lon a rbo
elo
ng property to
No gs No s
sa to sa or a student
to
un
au @ determine Ma if the current user is a uteacher
na
uth @ Ma and then use
tho pri rta pri rta
m o m
ed either ve theBaCurrentTeacher property orizCurrentStudent rbo property of
riz a r a ve Ba
rab rbo ed rab
co s s co s sa
pthe
ies SessionContext object to access the user s a details.
s.c a . pie s.c .
all om om
ow llo
ed we
! d!

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

1. Build the solution and resolve any compilation errors.

2. Run the application.

3. ThLog on as vallee (a teacher) with a password


is
Th of password99.
is
do 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 s
Note: a The o passwords for all teachers have
n changed
a to to password99 to
au @ M au @ Ma
tho pri art t h pri rt
m a o m av Thea password
ensure
riz
ed
athat
ve
rab
theyBa meet the complexity requirements.
rbo
riz
e dc e rab
Ba
rbo for all
co s s a. o s sa.
students pie is still
sa
s.c password.
om
pie
sa
s.c
om
llo llo
we we
d! d!

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.

8. In Visual Studio, close the solution.

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!

Exercise 3: Creating the ClassFullException Custom Exception

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

Task 1: Implement the ClassFullException class


Th Th
is is
do do
c
um cu
1. mIn msolution
art Visual en Studio, open the GradesPrototype.sln
t be
ma
rta
en
tb from the
a.b l . b e l
arb on arb on
NoE:\Labfiles\Starter\Exercise
os gs 3 folder. No os 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 rbo
2. Review the co ClassFullException
pie b s os
a
class in the Services d co folder.
pie
r ab Notice
s sa that the
s.c . s.c .
sa om sa om
class inherits from llo
we the Exception class, but most of the functionality
llo
we has yet to
d! d!
be defined.

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

parameter containing the exception message. This constructor should also


delegate its functionality to the equivalent constructor in the Exception class.

6. Add a public constructor to the ClassFullException that takes a string


Thparameter holding the exception messageTand
his an Exception object containing
is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/43
10/25/2019 20483A - Programming in C# | Skillpipe

an inner exception. Like the previous constructors, this constructor should


delegate its functionality to the equivalent constructor in the Exception class.

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
!

Task 2: Throw and catch the ClassFullException

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).

3. Students are enrolled in a class by using the AssignStudentDialog window.


ThOpen the AssignStudentDialog.xaml.cs Tfile his and review the code in the
is
do do
cu cu
Student_Click
ma m en method. This method runs when
ma mthe
en user selects a student to
rta tb r t a tb
.ba elo .ba elo
Noadd toboa class.
r n gs Notice that the try block inNthis o method
r bo nincludes
gs the following
un s a t o u n s a to
au @ M a uth @ M
statement:
tho pri art 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
d! d!
SessionContext.CurrentTeacher.EnrollInClass(student);

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

Task 3: Build and test the solution

1. Build the solution and resolve any compilation errors.


Th Th
is is
do d oc
2. Run cuthe application.
me um
ma nt ma en
rta be rt a.b tb
.ba lon elo
No rbo gs No arbng
3. Log
un on sas valleeto (a teacher) with a password un of password99.
o sa st
a @ Ma @ oM
au pri au p art
tho m rta tho rim aB
riz av Ba riz av arb
ed era rbo ed era
4. Create four co new bstudents.
s sa co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we we
d d
5. Try to enroll all four! students in the class for Esther Valle; this !teacher currently
has five students, so attempting to add the final student should fail with a
ClassFullException exception.

6. Log off and then close the application.


Th Th
is is
do do
7. In Visualcu
m Studio, close the solution. 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
ed era arb ze ve rbo
os d r ab
Results: Aftercopcompleting ies
bs
s.c thisa . exercise, you should have cocreated
pie s s.c new
a sa custom
.
all om sa om
exception class and wused it to report when too many students are l
o
ed
l o we enrolled in a
! d!
class.

Module Review and Takeaways


Th Th
is is
do d oc
cum um
ma ent ma en
rta be rt a.b tb
Module Review
No
.ba
rbo
lon
gs No arb
elo
os
ng
st
un s a@ to un a oM
au Ma au @
tho pri rta tho pri art
ma m aB
In this module, riz
ed you vehave
rab
Blearned
arb how to use inheritance riz and aextension
ed ve
r arb methods to
co o sa co ab os
pie ss . pie ss a.
extend the functionality sa of
.co existing
m types. sa .co
m
llo llo
we we
d! d!

Test Your Knowledge

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?

Select the correct answer.

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!

Test Your Knowledge

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!

The first parameter of the method must be a String.

The class must inherit from the String class.

The method declaration must include String as a type argument.


Th T
is The method declaration must be preceded by String.his
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
ed rab rbo e dc e rab rbo
co ss s a. 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 43/43
10/25/2019 20483A - Programming in C# | Skillpipe

Module 6: Reading and Writing Local Data

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
! !

Lesson 3: Performing I/O by Using Streams

Lab: Generating the Grades Report

Module Review and Takeaways


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
Module Overview
au
tho
riz
ed
pri
m av
era
rta
Ba
rbo
au
tho
riz
ed
p rim
av
era
art
aB
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!
Reading and writing data are core requirements for many applications, such as a text
file editor saving a file to the file system, or a Windows service writing error messages
to a custom log file. The local file system provides the perfect environment for an
application to read and write such data, because access is fast and the location is
readily available. The Microsoft .NET Framework provides a variety of I/O classes
Th Th
is is
d
that simplify do
um the process of implementing I/O functionality in your applications.
oc cu
ma en ma me
rta tb rta n tb
.ba elo .ba elo
No r bo n gs No r bo ng
u s t u s st
In this module,
n a @you will o M learn how to read and write n data a
by@ using o M atomic file system
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arband how to
I/O operations, e d c how to
op
e rab serializerbo
sa
and deserialize data to the
e d c file system,
o
e rab os
ies s s . p ies s s a.
.co .co
read and write dataalto low the file
m system by using streams. a llo
we
m
ed d!
!

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.

• Manipulate file and directory paths by using the Path class.

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:

1. Acquire the file handle.


Th Th
is is
do oc d
c
um um
2. mOpen
art antstream
e
b
to the file. 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
3. Buffer
au
tho the data
prim from
M a rta the file into memory. au
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.
4. Release the file s a handle
llo
om so that it can be reused. sa
llo
om
we we
d! d!

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 !

string settings = File.ReadAllText(filePath);

• 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.

string filePath = "C:\\fourthCoffee\\settings.txt";

string[] settingsLineByLine = File.ReadAllLines(filePath);


Th Th
is is
• d
The ReadAllBytes
o method enables you to read dothe contents of a file as binary
cu cu
ma me m me
r n t a r nt
data aand
t .ba store belo the data in a byte array. The following t a.b
a
code
be
lon example shows how to
No rbo ng N r b gs
un the contentssa s to o un o sa to
read au
tho
@
pri of
M artthe settings.txt file into a byte au
t
array @ named
pri Ma rawSettings.
m a 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
string filePathpi= es "C:\\fourthCoffee\\settings.txt";
s .co a . p ies s.co .
all m all m
ow ow
ed ed
! !
byte[] rawSettings = File.ReadAllBytes(filePath);

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 following list describes some of these methods:

• 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 filePath = "C:\\fourthCoffee\\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.

string filePath = "C:\\fourthCoffee\\hosts.txt ";


Th
string[] Th
hosts = { "86.120.1.203", "113.45.80.31",
is is
do do
c
um cu
"168.195.23.29"
ma en }; ma me
rta tb rt nt
.ba elo a.b be
ng arb lon
File.WriteAllLines(filePath,
No rbo st hosts);
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
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
• The WriteAllBytes llo method enables
we you to write the contentsllowof a byte array to a
d! ed
!
binary file. The following code example shows how to write the contents of a byte
array named rawSettings to a new file named settings.txt.

string filePath = "C:\\fourthCoffee\\setting.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

string filePath = "C:\\fourthCoffee\\settings.txt";

string settings = "companyContact= Dean Halstead";

File.AppendAllText(filePath, settings);

Th AppendAllLines method enables you toThwrite the contents of a string array to


• Theis is
do do
u c um c
maend mof
the en an existing file. The following codemexample
a en shows how to write the
rta t be t rta be
.b
arb of a ostring l ab on l .b
contents
No os
ng
st array named newHosts Nto
o the rexisting
os gshosts.txt file.
t
un a @ o Ma u na a @ oM
au pri uth pri art
tho ma r taB ori ma 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.
string filePath sa o "C:\\fourthCoffee\\hosts.txt s"; om
llo = m all
ow
we ed
d! !
string[] newHosts = { "97.11.1.195", "203.194.40.177" };
File.WriteAllLines(filePath, newHosts);

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.

File Manipulation by using the File Class


The File class provides static methods that you can use to perform basic file
manipulation.
Th
is The following list describes someTof
his these methods:
do do
cum cu
ma e m me
rta n tb a r nt
.ba elo t a.b be
n a lon
• The
N o u Copy r bos method
a
g s t enables you to copy an existing
o
N ou r file
b os to a
a
gsdifferent directory on
to
na @ M na @ Ma
uth pri art uth pri
the file system.
ori maThe following
aB code example shows orhow macopyrtathe
to Ba settings.txt file
ze ve arb ize ve
dc rab o dc rab rbo
op s sa op s sa
from the C:\fourthCoffee\ ies s .co directory
. to the C:\temp\ directory. ies s.co .
all m all m
ow ow
ed ed
! !

string sourceSettingsPath = "C:\\fourthCoffee\\settings.txt";


string destinationSettingsPath = "C:\\temp\\settings.txt";
bool overWrite = true;
File.Copy(sourceSettingsPath, destinationSettingsPath,
Th Th
is is
do
overWrite); 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
au @ Ma u @
tho p rim rta tho p rim art
riz av B riz av aB
Note: ed The overwrite
co
era a rbo parameter passed to the Copy ed
c
method
era acall
rbo indicates
pie b s s a o pie b s sa
s.c . s.c . the
that the copy s a process om should overwrite an existing file s aif it exists
om at
llo llo
destination path. we we
d! If you pass false to the Copy method call, d! and the file
already exists, the Common Language Runtime (CLR) will throw a
System.IO.IOException.

• 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

string filePath = "C:\\fourthCoffee\\settings.txt";


bool persistedSettingsExist = File.Exists(filePath);

• 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.

string filePath = "C:\\fourthCoffee\\settings.txt";


FileInfo settings = new FileInfo(filePath);
Th Th
is is
doc
settings.Delete(); do
um 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
• The DirectoryName
r i ze
dc
ve
rab
property
a rbo enables you to get the zedirectory
dc
ve rab
path Ba to the
rbo file. The
op ss sa op ss sa
following code example i . i .
esa .c omshows how to get the path to the settings.txt e sa . com file.
llo llo
we we
d! d!

string filePath = "C:\\fourthCoffee\\settings.txt";


FileInfo settings = new FileInfo(filePath);
string directoryPath = settings.DirectoryName; // returns
C:\\fourthCoffee
T Th
his is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 9/62
10/25/2019 20483A - Programming in C# | Skillpipe

• 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.

string filePath = FourthCoffeeDataService.GetDataPath();


FileInfo
Th settings = new FileInfo(filePath);
Th
is is
do do
string u cextension = settings.Extension; 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
• The Length ed property era enables
arb you to get the length ofze the file ve in bytes. rbo The
co b os d co r ab
pie s s.c a pie s s.c sa
sa . .
following code example omshows how to get the length of thes settings.txt a om file.
llo llo
we we
d! d!

string filePath = "C:\\fourthCoffee\\settings.txt";


FileInfo settings = new FileInfo(filePath);
long length = settings.Length;
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
Manipulating Directories
tho
riz
ed
ma
ve
rab
rta
Ba
rbo
tho
riz
ed
m av
era
aB
arb
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 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.

Manipulating Directories by using the Directory Class


Similar to the File class, the Directory class provides static methods that enable you
T
his hi T
to interact
do with directories, without instantiating a sdirectory-related
do object in your
cu cu
m m
code.maThe en
rta following
tb list describes some of thesemstatic
art
a
emethods:
nt
b
.ba elo .ba elo
No rbo ng No rbo ng
un sa s t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
• The CreateDirectory
riz
ed
av
era method
B a rbo enables you to create riza newavdirectory
ed era arb on the file
co b s s c o b s os
pie s.c a . pie s.c a.
system. The following sa
llo
oexample
m shows how to create the C:\fourthCoffee\tempData
s a llo
o m
we we
directory. d ! d!

string directoryPath = "C:\\fourthCoffee\\tempData";


Directory.CreateDirectory(directoryPath);
Th Th
is is
do d oc
cum um
ma ent ma en
• The tDelete
r a.b bmethod enables you to delete a directory rt
a.b tat
be a specific path. The
elo lon
No ar bo n gs No a r bo gs
following
un s
code
a@ example t oM shows how to delete the s
un C:\fourthCoffee\tempData
a@ to
au pri art a uth pri Ma
tho ma aB ori ma rta
riz Ba
directory, and e d c all its
v e rab contents.
a rbo ze dc
ve rab rbo
op ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
string directoryPath = "C:\\fourthCoffee\\tempData";
bool recursivelyDeleteSubContent = true;
Directory.Delete(directoryPath, recursivelyDeleteSubContent);

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

Note: The recursivelyDeleteSubContent parameter passed into the


Delete method call indicates whether the delete process should delete any
content that may exist in the directory. If you pass false into the Delete
method call, and the directory is not empty, the CLR will throw a
System.IO.IOException.

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!

bool tempDataDirectoryExists = Directory.Exists(directoryPath);

• 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 DirectoryInfo class acts as an in-memory representation of a directory. Before


you can access the properties and execute the methods that the DirectoryInfo class
exposes, you must create an instance of the class.

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

Note: The recursivelyDeleteSubContent parameter passed to the Delete


method call indicates whether the delete process should delete any content
that may exist in the directory. If you pass false to the Delete method call,
and the directory is not empty, the CLR will throw a
System.IO.IOException.

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!

DirectoryInfo directory = new DirectoryInfo(directoryPath);


bool tempDataDirectoryExists = directory.Exists;

• 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

string tempDirectoryPath = "C:\\fourthCoffee\\tempData";


if (!Directory.Exists(tempDirectoryPath))
Directory.CreateDirectory(tempDirectoryPath);

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
! !

Getting the Path to the Windows Temporary Directory

string tempDirectoryPath = Path.GetTempPath();


Th Th
is is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
ng arb
The Path
N ou class
r bos
a@
includes
gs
to many other static methods
No
u
that
os provide
a
s t a good starting point
o
na Ma na @ Ma
uth pri tho u
rim require. p
for any custom ori I/Oma typertafunctionality
Ba that your application
riz may av
rta
Ba These
ze ve rbo ed era rbo
dc rab co bs
o s sa sa
methods includepithe es following:
s .co . pie
sa
s.c
o
.
all m llo m
ow we
ed d
! !
• The HasExtension method enables you to determine if the path your application
is processing has an extension. This provides a convenient way for you to
determine if you are processing a file or a directory. The following example shows
how to check whether the path has an extension.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
string .ba settingsPathlon = "..could be anything a
ehere..";
lon
No r bo gs No r bo gs
s
un hasExtension a@ t oM un s a@ to
bool au
tho pri art = Path.HasExtension(settingsPath);
a uth pri Ma
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
w we
• The GetExtension emethod d! enables you to get the extension from d! a file name.
This method is particularly useful when you want to ascertain what type of file your
application is processing. The following code example shows how to check
whether the settingsPath variable contains a path that ends with the .txt
extension.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 16/62
10/25/2019 20483A - Programming in C# | Skillpipe

string settingsPath = "..could be anything here..";


string pathExt = Path.GetExtension(settingsPath);
if (pathExt == ".txt")
{
// More processing here.
}
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
• TheunGetTempFileName
sa
@
s to enables you to createuna newsatemp
o o
@
s file
to in your local
au p M a au p Ma
tho rim rta tho rim rta
Windowsriztemporary
ed
av
era directory
Ba
rbo
in a single atomic operation
riz
ed folder.
av
era This
Ba
rbo
method then
co b s s a. c o b s s
returns the absolute pie spath pie s.c Theafollowing
m to that file, ready for further processing.
sa .co sa .
om
llo llo
w w
code shows how to einvoke d! the GetTempFileName method. ed!

string tempPath = Path.GetTempFileName();


// Returns C:\Users\LeonidsP\AppData\Local\Temp\tmp1C79.tmp

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!

Demonstration: Manipulating Files, Directories, and Paths


In this demonstration, you will use the File, Directory, and Path classes to build a
utility that combines multiple files into a single file.
Th Th
is is
do d oc
cum um
ma e ma en
Demonstration
rta
.b be
l
Steps nt rt a.b elo
tb
arb on arb ng
No o gst No os st
un sa o u n a oM
au @ M a uth @
tho pri art pri art
m
riz MSL-TMG1 av a o riz m av aB
1. Start the ed era Ba virtual machine if it is not already
rbo e d running.
e r ab
arb
co bs sa co s os
pie s.c . p ies s.co a.
sa om a m
llo llo
2. Start the 20483A-SEA-DEV11-06we
d! virtual machine. we
d!

3. Log on to Windows 8 as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 17/62
10/25/2019 20483A - Programming in C# | Skillpipe

4. Switch to the Windows 8 Start window.

5. Open File Explorer and browse to the E:\Democode\Data\Logs folder.

6. In the E:\Democode\Data\Logs folder, double-click each of the text files, and


view the contents in Notepad.
Th Th
is is
7. d
Close do
o cu NotePad. cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
8. NoSwitch rbo to the sWindows 8 Start window. N ou r b os gs
un sa t 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 r e e rbo
9. Click Visual co Studio
pie b s s.c
2012.bo
s a.
dc
o pie
rab
s s.c sa
sa sa .
om om
llo llo
we we
10. In Visual Studio, on d! the File menu, point to Open, and then click d!

Project/Solution.

11. In the Open Project dialog box, browse to


E:\Democode\Starter\FourthCoffee.LogProcessor folder, click
ThFourthCoffee.LogProcessor.sln, and then click
is Open.
Th
is
do do
cu cu
ma m en ma me
t n
12. r
In Visual
t a.ba bStudio,
elo on the View menu, click Task.baList.t belo
r t a
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 r t h r
13. In the rTask ize List
av window,
taB
a
in the Categories list, click ori
zed
Comments.
im av aB
arb
dc era rbo era
op b s s c o b s os
ies s.c a . pie s.c a.
a o m s a o m
14. Double-click the llo TODO: 01: Ensure log file directory exists.
we
llo task.
we
d! d!

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:

return Directory.GetFiles(this._logDirectoryPath, "*.txt");

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:

var logText = File.ReadAllText(logPath);


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/62
10/25/2019 20483A - Programming in C# | Skillpipe

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.

31. Open File Explorer and browse to the E:\Democode\Data\Logs folder.


Th Th
is is
do do
32. Double-click
cu
m
CombinedLog.txt, verify that the cfile
um contains a heading, and then
ma en ma en
rta t rta tb
verify.ba thebecontents
lon of each log file. .ba elo
ng
No rbo gs No rbo st
un sa t o u na s a oM
au @ Ma u @
tho prim rta tho p rim art
33. Close riNotepad,
ze av close
era B a File
rbo
Explorer, and then close riz Visual
ed
av Studio.
era
aB
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
! !

Lesson 2: Serializing and Deserializing Data

Serialization is the process of converting data to a format that can be persisted or


transported.
Th
is
Deserialization is the process of converting
Th
is
serialized data back to
do do
c cu
objects.
m
um
ent ma me
nt
art be rt be
a.b l a . b lon
arb o ng arb
No o s N o o gs
un s a@ t oM un s a@ to
au p a a u p Ma
In this lesson,
t ho
riz
you r im will learn
av
r ta
B
how to serialize objects to t ho binary,
r
r im XML,
a
rta and JavaScript
Ba
ed era arb ize ve
o dc rab rbo
Object Notationop(JSON),c ss andshow to create a custom serializer ies sossthat .co you
b a. op sa can
ies .co .
all m all m
serialize objects into any o we format you choose. o we
d! d!

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.

• Create a custom type that is serializable.

• Serialize an object as binary.

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

the common formats available.

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.

To create a serializable type, perform the following steps:

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

public class ServiceConfiguration


{
public ServiceConfiguration()
{
...
Th Th
is is
do } d oc
cu um
ma me ma en
}rta. nt rt tb
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
riz m av Ba riz av aB
ed era rbo ed era arb
co b co bs os
2. Decorate the pie class s s.cwith sthe
a. Serializable attribute provided pie in sthe
. c System
a.
sa om sa om
llo llo
namespace. we we
d! d!

[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

4. Define a deserialization constructor, which accepts SerializationInfo and


StreamingContext objects as parameters. This constructor enables you to
rehydrate your object during the deserialization process.

[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
! !

Note: The BinaryFormatter and SoapFormatter classes implement the


IFormatter interface. You can also implement the IFormatter interface to
create your own custom serializer.
Th Th
is is
do d oc
cum um
ma ent nt ma e
Serialize
rta
.ba anbeObject
lo
by Using the BinaryFormatter
a.b
a
be
lo
Class rt
No rbo ng No rbo ng
un sa st un st sa
@ oM oM @
au au
To serializetho an object
riz
p rim
av
by
art using the
aB BinaryFormatterthclass,
ori
p rperform
im av
art the following
aB
ed era arb ze era arb
os dc os
steps: c op
ies
b s s.c a. op
ies
b s s.c a.
all o m all o m
ow ow
ed ed
! !
1. Obtain a reference to the object you want to serialize.

2. Create an instance of the BinaryFormatter that you want to use to serialize


your type.
Th Th
3. Create
is
do a stream that you will use as a buffer is to store the serialized data.
do
cu cu
ma m en ma me
rta tb r nt
. elo t a . be
4. NoInvoke
barb the BinaryFormatter.Serialize
ng method,
N
b apassing
r b
lon in stream that the
gs
un o s s t o un o s to
a@ oM a@ M
a
serialized
uth pdata will
a be buffered to, and the object a u you pwant toartserialize.
ori r im r ta t ho r im aB
ze a ve B a r iz a v arb
dc rab 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 following code example shows how to use the BinaryFormatter class to
serialize an object as binary.

BinaryFormatter Serialize Example


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 28/62
10/25/2019 20483A - Programming in C# | Skillpipe

// Create the object you want to serialize.


ServiceConfiguration config = ServiceConfiguration.Default;
// Create the formatter you want to use to serialize the object.
IFormatter formatter = new BinaryFormatter();
// Create the stream that the serialized data will be buffered to.
FileStream buffer = File.Create("C:\\fourthcoffee\\config.txt");
Th Th
is is
// Invoked o the Serialize method. do
cu cu
ma me m me
r n t a r nt
t a.b b
formatter.Serialize(buffer,
elo config); t a.b be
a ng a lon
No rbo st N ou r b os gs
una s a o na a to
// Close uth the @
pri stream. M art uth @
pri Ma
ori ma aB ori ma rta
z e v e a ze ve Ba
buffer.Close(); 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
! !

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!

1. Create an instance of the BinaryFormatter that you want to use to deserialize


your type.

2. Create a stream to read the serialized data.


Th Th
is is
do do
c
um cu
3. mInvoke e the BinaryFormatter.Deserialize method,
m me passing in stream that
art n tb art nt
a.b elo a . be
arb ngserialized data. b arb lon
Nocontains o the 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 B
4. Cast thedresult e
co rof
ab the rBinaryFormatter.Deserialize
bo e d method
c
e rab callaintorbo the type of
pie ss sa op ss sa
sa .c . i e sa . c .
om om
object that youlloare we expecting. llo
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

BinaryFormatter Deserialize Example

// Create the formatter you want to use to serialize the object.


IFormatter formatter = new BinaryFormatter();
// Create the stream that the serialized data will be buffered too.
Th Th
is is
FileStream
do
c
buffer = File.OpenRead("C:\\fourthcoffee\\config.txt");
do
c
um um
m
art nthe e ma en
// Invoke
a. tb Deserialize method. rt a.b tb
e
ba lon elo
No rbo gs No arb
ng
sa to o sa st
ServiceConfiguration
un
a @ M config = formatter.Deserialize(buffer)
un
au @ oM as
uth pri art tho p rim art
ori ma aB riz av aB
z
ServiceConfiguration;
ed v era arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
// Close the stream. sa om sa om
llo llo
we we
buffer.Close(); d! d!

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.

Serialize an Object by Using the SoapFormatter Class


The process for serializing data as XML is similar to the process of serializing to
Th Th
is sd i
binary, with
do
cu the exception that you use the SoapFormatter
oc
u
class.
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/62
10/25/2019 20483A - Programming in C# | Skillpipe

The following code example shows how to use the SoapFormatter class to serialize
an object as XML.

SoapFormatter Serialize Example

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"); !

// Invoke the Serialize method.


formatter.Serialize(buffer, config);
// Close the stream.
buffer.Close();
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 a rbo ng
un sa t u s st
@ o Ma na a @ oM
Deserialize an Object by Using the SoapFormatter Class
au
tho
riz
p rim
av
rta
B
u 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.
The process for deserializing sa
llo
om data from XML to an object is identical
sa
llo
oto
m the process of
we we
deserializing binary data, d! with the exception that you use the SoapFormatter d! class.

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.

FileStream buffer = File.OpenRead("C:\\fourthcoffee\\config.xml");


// Invoke the Deserialize method.
ServiceConfiguration config = formatter.Deserialize(buffer) as
ServiceConfiguration;
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/62
10/25/2019 20483A - Programming in C# | Skillpipe

// Close the stream.


buffer.Close();

Serializing Objects as JSON


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!

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
! !

To serialize an object by using the DataContractJsonSerializer class, perform the


following steps:

1. Obtain a reference to the object that you want to serialize.


Th Th
is is
do do
uc cu
2. Create
ma m enan instance of the DataContractJsonSerializer
ma me
nt
class that you want to
rta tb r t a b
.ba elo elo
Nouse to rboserialize ng
s your type. The constructorNoalso.barequires rbo ng you to pass in a Type
st
un s a t o u n s a oM
au @ M a @
object,tho representing
riz
pri
m av
art the type of object you want
a
uthto serialize.
o riz
pri
m av
art
aB
ed era Ba e e arb
rbo d r ab os
co bs sa co s a.
pie s.c . p ies s.co
3. Create a stream s o
all thatmyou will use as a buffer to store the aserialized m data.
ow llo
ed we
! d!

4. Invoke the DataContractJsonSerializer.WriteObject method, passing in


stream that the serialized data will be buffered too, and the object you want to
serialize.

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

The following code example shows how to use the DataContractJsonSerializer


class to serialize an object as JSON.

DataContractJsonSerializer Serialize Example

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!

3. Invoke the DataContractJsonSerializer.ReadObject method, passing in the


stream that contains the serialized data.

4. Cast the result of the DataContractJsonSerializer.ReadObject method call


Th Th
into
is
do the type of object you are expecting. is
d
cu oc
me um
m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/62
10/25/2019 20483A - Programming in C# | Skillpipe

The following code example shows how to use the DataContractJsonSerializer


class to deserialize JSON data to an object.

DataContractJsonSerializer Deserialize Example


Th Th
is is
do d oc
cum um
ma e
nt maen
rta b a.b rttb
.ba elo elo
// NCreate r b a ng
DataContractJsonSerializer N object arb that ng you will use to
ou os st o un o sa st
na a@ oM @ oM
u p a au p art
tho
// deserialize rim thertaJSON. tho rim aB
riz av B arb r iz a v arb
ed era ed era
co
DataContractJsonSerializer bs o sa jsonSerializer co bs os
pie s.c . pie s.c a.
sa om sa om
llo llo
we
= new DataContractJsonSerializer(typeof(ServiceConfiguration)); we
d! d!
// Create a stream that will read the serialized data.
FileStream buffer = File.OpenRead("C:\\fourthcoffee\\config.txt");
// Invoke the ReadObject method.
ServiceConfiguration config = jsonSerializer.ReadObject(buffer) as
Th
ServiceConfiguration; Th
is is
do d oc
c
um the stream. um
// Close
ma en ma en
rta tb rt a.b tb
.ba elo elo
buffer.Close();
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 b s os co b s os
pie s.c a. pie s.c a.
sa om sa om
llo llo
we we
Creating a Custom Serializer 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
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

To create your own formatter, perform the following steps:

1. Create a class that implements the IFormatter interface.

2. Create implementations for the SurrogateSelector, Binder, and Context


properties.
Th Th
is is
do oc d
3. Create
ma
um implementations for the Deserialize and
e
c
m
Serialize
um
e
methods.
rta nt art 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
riz m av Ba riz m av Ba
ed era rboshows a ed era rbo and
The following code co
pie
example
b s s.c sa custom formatter thatco can serialize
pie b s s.c sa
sa . sa .
om om
deserialize objects toowthe l l
ed
.ini format. llo
we
! d!

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 static readonly char[] _delim = Tnew char[] { '=' };


is his
do do
public
c um ISurrogateSelector SurrogateSelector
cu
me { get; set; }
ma en ma nt
rta tb r
public
.ba elo SerializationBinder Binder t{ a.b get;belset; }
on
No rbo n gs a No rbo g
un sa to sa
un st
apublic
uth @
pri Ma
StreamingContext
rta
Context { get;
au
tho
@
set;pri }o Mar
ori ma riz m ta
ze ve Ba av Ba
public d c IniFormatter()
rab rbo ed era rbo
op ss sa co b ss sa
ies .co . pie . c .
a m sa om
{ llo
we
llo
we
d! d !
this.Context
= new StreamingContext(StreamingContextStates.All);
}
public object Deserialize(Stream serializationStream)

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!

// Create dictionary to store the variable names and any


serialized data.
Dictionary<string, object> serializedMemberData
= new Dictionary<string, object>();
Th Th
is is
// Read the serialized data, and
do do extract the variable names
cum cu
ma e ma me
rta nt and values as strings.
// rt nt
.ba be a .ba be
lon lon
No rbo gs No rbo gs
un while
sa
@ (buffer.Peek()
to
M
>= 0) 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 .
string
sa line
om = buffer.ReadLine(); sa om
llo llo
we we
string[] d! sarr = line.Split(_delim); d!

// key = variable name, value = variable value.


serializedMemberData.Add(

sarr[0].Trim(), // Variable name.

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!

// Get the field data.


object[] fieldData = FormatterServices.GetObjectData(graph,

allMembers);

Th // Create a buffer to write the


T serialized data too.
is his
do do
c
umStreamWriter sw = new StreamWriter(serializationStream); cu
me
ma en ma nt
rta tb r t
.ba // Write elo the name of the class to a .bathe bfirstline.
elo
No rbo ng No rbo ng
un s s t u s st
a @ o M n a @ oM
au sw.WriteLine("@ClassName={0}",
pri art graph.GetType().FullName);
a uth pri art
tho m a o m aB
riz av Ba riz av arb
e
// d Iterate e rab the rb field data. e d e r ab
co ss os co s os
pie .co a . p ies s.co a.
sa m a m
for (intllowi = 0; i < fieldData.Length; ++i) llow
ed ed
! !
{
sw.WriteLine("{0}={1}",
allMembers[i].Name, // Member name.
fieldData[i].ToString()); // Member value.

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!

Demonstration: Serializing to XML


In this demonstration, you will serialize and deserialize a custom type to XML by
usingThithe
s SoapFormatter class. Th
is
do d oc
cum um
ma e nt ma en
rta be rt a.b tb
.ba lon elo
Demonstration Steps
No
un
rbo
sa
gs
to
No
un
arb
os
a
ng
st
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
1. Switch to the pie Windows
sa
s.c
om
8 .Start window. pie
sa
s.c
om
a.
llo llo
we we
d! d!
2. Click Visual Studio 2012.

3. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.

4. ThIn the Open Project dialog box, browse to Th


is is
do do
cu cu
E:\Democode\Starter\FourthCoffee.ExceptionLogger,
ma m en ma me
nt
click
rta tb r t a b
.ba elo .ba elo
NoFourthCoffee.ExceptionLogger.sln,
rbo ng
s
and then
No click rboOpen. 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
5. In Visuald Studio,
e
co
e rab on the
rb os
View menu, click Task List. e d co
e r ab
arb
os
pie ss a . p ies s s a.
sa .co .co
llo m a llo m
6. In the Task List wwindow, ed
! in the Categories list, click Comments. we
d!

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:

Tha. Title: Critical database error Th


is is
do do
cu cu
ma m en ma me
b.rta. Details: tb
elo
Could not find database server r t a .ba
nt
be
ba ng lon
No rbo s No rbo gs
un s a@ t oM un s a@ to
au p a a u p Ma
22. In the t ho SaveimSuccessful
riz
r
av
r ta
B
message box, click OK. t ho The exception
r
r im
a
rta entry
Ba
has now
ed era arb ize ve
o dc rab rbo
been serialized. c op b ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
23. Close the Exception Logger application.

24. Open File Explorer and browse to the E:\Democode\Data\Exceptions folder.

25. In the E:\Democode\Data\Exceptions folder, double-click the Exception_<date


Thand time>.txt file. Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 40/62
10/25/2019 20483A - Programming in C# | Skillpipe

26. In Notepad, find the Title and Details XML elements.

27. Switch to Visual Studio, and on the Debug menu, click Start Without
Debugging.

28. In the Exception Logger window, in the File list, click


ThE:\Democode\Data\Exceptions\Exception_<date Th and time>.txt, and then click
is is
do do
Load. cu The ExceptionEntry object has now been
me
cu deserialized.
me
ma n m a nt
rta tb r t a.b be
.ba elo lon
No rbo ng N a r b gs File Explorer.
29. Close
un the
sa application,
@
st
o close Visual Studio, oand
u n
then os close
a @ to
au pri M art au pri Ma
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 .
sa om sa om
llo llo
we we
Lesson 3: Performing I/O by Using Streams d! d!

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
!

What are Streams?

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:

• Reading chunks of data into a type, such as a byte array.

• Writing chunks of data from a type to a stream.


Th Th
is is
do d oc
c
um um
• Querying
ma enthe current position in the stream and
ma modifying
en a specific selection of
rta tb rta tb
.ba elo .ba elo
bytes
No atrbthe
o sa
current
ng
st position. No rbo
sa
ng
st
un @ oM un @ 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
llo llo
Streaming in the .NET Framework we
d!
we
d!

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

Stream class Description

NetworkStream Enables you to establish a stream to a network location in


memory. The NetworkStream class handles operations
such as opening and closing a connection to the network
location, and provides access to the network location
through a raw sequence of bytes.
Th Th
is is
do oc d
cum um
ma e
nt is established by using a FileStream, m en
A streamrta that
.ba belo
art MemoryStream,
a.b tb
elo or
No rbo ng N arb ng
st o ubytes. os If the ssource
NetworkStream
un
au
sa
@ object o M is just a raw sequence of na a@ to
Ma data is
tho prim a rta u tho pri r t
ma aB
structured, ryou ize must
dc
av convert
era Ba the byte sequence into the
rbo
riz appropriate
ed ve
r a
types.
arb This can
op bs sa co bs os
ies s .
.c error-prone task. However, the .NET p ies Frameworks .co a .
be a time-consuming all andom all m contains
ow ow
ed ed
classes that you can use! to read and write textual data and primitive ! types in a

stream that you have opened by using the FileStream, MemoryStream, or


NetworkStream classes. The following table describes some of the stream reader
and writer classes.

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!

• Binary data is not human readable.

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.

Initializing a BinaryReader and BinaryWriter Object


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 filePath s t u s st
string au a @ o =M "C:\\fourthcoffee\\applicationdata\\settings.txt";
n a a @ oM
tho pri art uth pri art
riz file m av = new a Ba FileStream(filePath); rize o m av aB
FileStream ed era rbo d e r ab
arb
co bs sa co s os
pie s.c . p ies s.co a.
... sa om a m
llo llo
we we
d! d!
BinaryReader reader = new BinaryReader(file);
...
BinaryWriter writer = new BinaryWriter(file);

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

advance the stream to the next byte.

• 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; !

// Create an array to store each byte from the file.


byte[] dataCollection = new byte[length];
int returnedByte;
while ((returnedByte = reader.Read()) != -1)
Th Th
is is
{ do
c oc d
um um
ma e n ma en
//
r ta. Set bthe t value at the next index. ta. r tb
ba elo b elo
No r bo n gs No a r bo ng
s t s st
dataCollection[position]
un
au a @ o M = (byte)returnedByte;
u n a a @ oM
tho pri art uth pri art
riz m a
avour position Ba o riz m av aB
// Advance ed era rbo variable. e d e r ab
arb
co bs sa co s os
pie s.c . p ies s.co a.
position += s a sizeof(byte);
om a m
llo llo
we we
} d! d!

// Close the streams to release any file handles.


reader.Close();
sourceFile.Close();
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 47/62
10/25/2019 20483A - Programming in C# | Skillpipe

Writing Binary Data


The following code example shows how to use the BinaryWriter and FileStream
classes to write a collection of four byte integers to a file.

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
! !

byte[] dataCollection = { 1, 4, 6, 7, 12, 33, 26, 98, 82, 101 };


// Create a FileStream object so that you can interact with the file
// system.
FileStream destFile = new FileStream(
Th T
is
destinationFilePath,
do // Pass in thehis destination
do path.
cu cu
m
mFileMode.Create,
en ma m en file.
art tb // Always create rta new tb
a.b elo . b elo
arbo
No FileAccess.Write); n gs No a rbo ng
un sa t // Only performu writing. s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
// Createrizea BinaryWriter av
era B a object passing in the
riz
ed
FileStream
av
era arb object.
dc rbo os
o b ss sa c op b ss a.
BinaryWriter pwriter ies .co= new
m
. BinaryWriter(destFile); ies .co
m
all all
ow ow
// Write each byteed!to stream. ed
!
foreach (byte data in dataCollection)
{
writer.Write(data);
}
Th T
is
// Close do both streams to flush the datahis todo the file.
cu cu
ma me ma me
writer.Close();
rta n tb r t
nt
be
.ba elo a .ba lon
N r b ng N r b gs
destFile.Close();
ou os
a
s t o o u o s a to
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 ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !

Reading and Writing Text Data by Using Streams

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!

Initializing a StreamReader and StreamWriter Object

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!

Demonstration: Generating the Grades Report Lab


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 52/62
10/25/2019 20483A - Programming in C# | Skillpipe

In this demonstration, you will learn about the tasks that you will perform in the lab for
this module.

Lab: Generating the Grades Report

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.

Estimated Time: 75 minutes

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!

Exercise 1: Serializing Data for the Grades Report as XML

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.

The Tmain tasks for this exercise are as follows: T


his his
do do
cum cu
ma e ma me
rta nt rt nt
belo user for a filename and retrieve the.b grade a be
1. Prompt
No
.ba
rbo the n gs No a rbo
lodata
ng
un sa t u s st
@ o Ma na a @ oM
au p u p art
tho rim rta tho rim aB
2. Serialize riz the agrade v data
B a to a memory stream 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.
sa om sa om
llo llo
3. Debug the application we
d!
we
d!

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

display a SaveFileDialog to the users, with a default filename of Grades.xml,


and with XML documents (*xml) displayed in the Save as type box.

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! !

Task 2: Serialize the grade data to a memory stream


Th Th
is is
do do
c
um cu
1. mIn
art StudentProfile.xaml.cs
en
t
code file, locate the
ma FormatAsXMLStream
me
nt method.
a.b be rta be
arb l on . b arb l on
No os gs No os gs
un a t o u a to
2. Add au code
tho
@ to save
pri M artthe XML document to a MemoryStream
na
uth @
pri Mobject
art by using an
riz m av aB ori m a aB
ed object. era arb ze ve arb
XmlWriter co b s os dc
o
rab
s os
pie s.c a . pie s.c a.
sa om sa om
llo llo
we we
3. Add code to create d! the root node of the XML document in the d!following format:

<Grades Student="Eric Gruber">

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.

8. Delete the line of code that throws a NotImplementedException exception.

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.

3. Debug the application.

4. Log in as vallee with a password of password99.


Th Th
is is
do do
5. ViewcumKevin Liu’s report, and then click Save Report cu
me to generate the XML
ma en ma n
rta t be rta t be
document.
No
.ba
rbo
lon
gs No
.ba
rbo
lon
gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
m aB o m
6. Add code r ize to save
dc
a ve
rab
thearfile
bo
in the default location. ized r a ve
r
Ba
rbo
op s co ab sa
ies s s.c a . pie s s.c .
all om sa om
ow llo
ed we
! d!
Note: You will write the code to actually save the report to disk in
Exercise 3 of this lab.

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.

Exercise 2: Previewing the Grades Report


Th Th
is is
do d oc
cum um
ma e
nt ma en
rta be rt a.b tb
.ba elo
Scenario
No rbo
lon
gs No arb ng
un sa to un os st
@ Ma a @ oM
au pri au p art
tho m rt tho rim
In this exercise, av will awrite aB
ed you code to display a previewrizeof the
riz Ba avreport to
arb the user
era rbo dc era
co b s s op bs os
before saving it. pies a s.com a. ies
all
s.c
om
a.
llo ow
we ed
d! !

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:

1. Display the string to the user in a message box

2. Build a string representation of the XML document


Th Th
is is
do do
3. mRun the c cu
ume application and preview the data. m me
art n tb art nt
a.b elo a . be
arb ng b 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
riz ve a z v Ba
ed rbto e e rbo
Task 1: Display co therastring
pie b ss o sa the user in a message box dc
op
rab
ss sa
sa .c . i e sa . c .
om om
llo llo
we we
d! d!

1. In Visual Studio, from the E:\Labfiles\Starter\Exercise 2 folder, open the


GradesPrototype.sln solution.

2. In StudentProfile.xaml.cs, in the SaveReport_Click method, add code to the


Thend of the if block that calls the FormatXMLData
Th method, passing the
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 57/62
10/25/2019 20483A - Programming in C# | Skillpipe

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!

5. Delete the line of code that throws a NotImplementedException exception.

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! !

Exercise 3: Persisting the Serialized Grade Data to a File


Th Th
is is
do do
um c cu
Scenario
ma en ma me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
sa to na onsathe to
In thisuexercise,
na
uth @ you
pri will
M art write the grade data to a ufile
uth @
pri local Madisk.
ori m aB ori m rta
ze a ve arb ze a ve Ba
dc rab os d r ab rbo
op s a co s sa
ies s.c . pie s.c .
om sa om
You will begin by modifying a llo
we
the existing preview dialog box to askllo the user
we
if they
d! d!
wish to save the file. If they wish to save the file, you will use a FileStream object to
copy the data from the MemoryStream to a physical file.

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

Task 1: Save the XML document to disk

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

1. In Visual Studio, from the E:\Labfiles\Starter\Exercise 3 folder, open the


GradesPrototype.sln solution.

2. In StudentProfile.xaml.cs, in the SaveReport_Click method, locate the line of


code that displays the report data to the user in a message box.

3. ThModify this line of code as follows: Th


is is
do do
cu cu
ma. me m me
art
a.b
Savent
b
the return value of the MessageBox.Show
a r t a.b
nt
be
method in a
elo l o
No arbo ng No a rbo ng
un MessageBoxResult
sa st
oM variable 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
b. Set the co caption
pie bs
s.c of sthe
o
a. message box to Save Report? co
pie bs
s.c
os
a.
sa om sa om
llo llo
we we
d! d!
c. Include Yes and No buttons in the message box.

d. Display a question mark image.

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

1. Build the solution and resolve any compilation errors.

2. ThRun the application.


is
Th
is
do do
cu cu
ma m en ma me
3. Logrta on as t b vallee with a password of password99. 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 M
4. ViewhoKevin
t r imLiu’s report
r ta card and then click Save t ho Report r im toagenerate
rta the XML
riz av B arb r ize a ve Ba
ed era dc rab rbo
co b o sa sa
document. pies ss
.co . op
ies ss
.co .
all m all m
ow ow
ed ed
! !
5. Specify to save the file in the Documents folder by using the default name.

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.

9. In Visual Studio, close the solution.

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.

The BinaryReader and BinaryWriter classes.

The FileStream, StreamReader and StreamWriter classes.

Th The MemoryStream, StreamReader and StreamWriter Th classes.


is is
do do
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 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
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 62/62
10/25/2019 20483A - Programming in C# | Skillpipe

Module 7: Accessing a Database

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
! !

Lab: Retrieving and Modifying Grade Data

Module Review and Takeaways

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!

• Query data by using LINQ.

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!

After completing this lesson, you will be able to:

• Describe the ADO.NET Entity Framework.

• 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
! !

Introduction to the ADO.NET Entity 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 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.

The ADO.NET Entity Framework provides the following:

• 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.

These components enable you to:


Th Th
is is
do do
c cu
• Write
ma code
um en against a conceptual model that includes
ma me types that support inheritance
nt
rta t b r t a be
.ba elo .ba lon
and
No relationships.
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
• Update applications
ed
co
era to target
b
arb
os
a different storage model ze without
d co
ve rewriting
r ab rbo or
pie s s.c a pie s s.c sa
. .
redistributing alls aof llo yourmdata access code.
o sa
llo
om
we we
d! d!

• 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

Additional Reading: For more information about the ADO.NET Entity


Framework, see the ADO.NET Entity Framework page at
http://go.microsoft.com/fwlink/?LinkID=267806.

Using the ADO.NET Entity Data Model Tools


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!

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!

Demonstration: Creating an Entity Data Model


In this demonstration, you will use the Entity Data Wizard to generate an EDM for an
Th Th
is is
existingdodatabase.
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
s
Demonstration Steps
un
au
tho
a@
pri
to
Ma
rta
un
au
tho
a @
pri
oM
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
1. Start the MSL-TMG1 llo
we
virtual machine if it is not already running. llo
we
d! d!

2. Start the 20483A-SEA-DEV11-07 virtual machine.

3. Log on to Windows® 8 as Student with the password Pa$$w0rd.

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

4. Switch to the Windows 8 Start window.

5. Click Visual Studio 2012.

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.

23. On the Build menu, click Build Solution.

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.

28. In Solution Explorer, expand FourthCoffeeEmployeesModel.edmx, expand


FourthCoffeeEmployeesModel.Context.tt, and then double-click
Th Th
is is
FourthCoffeeEmployeesModel.Context.cs.
do
cu um
d oc
ma me ma en
rta nt rt tb
.ba be a.b elo
lon a
29. NoIn thebcode
r o s
editor,
gs
t
review the code in the FourthCoffeeEntities
No r bo
s
ng
st partial class.
un a @ o M u n a @ oM
au pri art a uth pri art
tho ma aB ori ma aB
riz ve a z v arb
30. In Solution e d c Explorer, expand e
FourthCoffeeEmployeesModel.tt, e and
op
rab
s
rbo
sa
dc
o
rab
s os then
ies s .co . p ies s .co a.
double-click Employee.cs. a llo m a llo m
we we
d! d!

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

Customizing Generated Classes

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!
!

public virtual Branch Branch1 {get; set; }


public virtual JobTitle JobTitle1 {get; set; }
}
}
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 8/33
10/25/2019 20483A - Programming in C# | Skillpipe

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.

Adding Business Logic in 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!

Reading and Modifying Data by Using the 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 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!

public partial class FourthCoffeeEntities : DbContext


{
Thpublic FourthCoffeeEntities() : Th
is is
do do
cu
base("name=FourthCoffeeEntities") 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
a
} uth pri art a uth pri Ma
ori ma aB ori ma rta
ze ve a ze ve Ba
public d DbSet<Branch> rab rbo Branches { get; set; d} rab rbo
co ss sa c op ss sa
pie .c . i e . c .
sa om sa om
public DbSet<Employee> llo Employees { get; set; } llo
we we
d! d!
public DbSet<JobTitle> JobTitles { get; set; }
}

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 !
}

The DbSet(TEntity) class implements the IEnumerable interface which provides a


number
Th of extension methods that enable you to
Th easily locate specific data in the
is is
d
oc example, the First extension method locates
oc d
source. For
um um the first match for the
ma en ma en
ta. r be t ta. r tb
specified
N
bcondition,
ar lon such as a last name of Prescott.
g N
ba
r
elo
ng
ou bo s o bo 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 zed era arb
The following dcode co
pie
example
b s s.c
shows
s a how to use the First extension
c o pie b s method
s.c
os
a. to locate
sa . sa
om om
an employee and then llo how to update the data by using standard
we
llo dot notation.
we
d! d!

Locating and Modifying Data

// 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!

Additional Reading: For more information about the DbSet(Entity) class,


see the DbSet(Entity) Class page at http://go.microsoft.com/fwlink/?
LinkID=267809. For more information about the Enumerable methods, see
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 11/33
10/25/2019 20483A - Programming in C# | Skillpipe

the Enumerable Methods page at http://go.microsoft.com/fwlink/?


LinkID=2678010.

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!

1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20483A-SEA-DEV11-07 virtual machine.


Th Th
3. is
Log is
do on to Windows® as Student with the password do Pa$$w0rd.
cu cu
ma m en ma m 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 Note: pri If necessary,
art a
click Switch User to udisplay prithe list artof users.
tho m a tho 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!
4. Switch to the Windows 8 Start window.

5. Click Visual Studio 2012.

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

7. In the Open Project dialog box, browse to the


E:\Democode\Demo2\FourthCoffee.Employees folder, click
FourthCoffee.Employees.sln, and then click Open.

8. In Solution Explorer, expand FourthCoffee.Employees, and then double-click


Program.cs.
Th Th
is is
do do
9. Review cu
me the definition of the DBContext variable. 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 uses the DBContext
10. Review
un sathe code
@
st
o in the PrintEmployeesListo u method
n
os
a @
that to
au pri M art au pri Ma
tho m a t h o m rta
variable riz to access
ed
av
era the Ba data in the EDM.
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
11. Review the code l l ow in the Main method that uses the First extension l l ow method to
ed ed
! !
retrieve an employee and then modifies that employee’s LastName property.

12. On the Debug menu, click Start Without Debugging.

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!

Lesson 2: Querying Data by Using LINQ

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.

• Query data by using anonymous types.

• Force query execution.

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:

from <variable names> in <data source>

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

Using a select Clause

IQueryable<Employee> emps = from e in DBContext.Employees


select e;

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.

Using a where Clause


Th Th
is is
do d oc
c um um
ma e nt ma en
rta be rt a.b tb
string .ba_LastName
lon = "Prescott"; elo
No rbo gs No arb ng
un s t un os st
a@ oM a @ oM
IQueryable<Employee>
au
t pr ar emps = from e in DBContext.Employees
au
tho p rim art
ho im ta aB
riz av B arb riz av arb
ed e rab ed era where
co ss os co b s os
pie .co a. pie s.c a.
sa m sa om
e.LastName == _LastName
llo
we
llo
we
d! d!
select e;

Filtering Data by Column


Th Th
is is
d
The following do
um code example shows how to declare acunew type in which to store a
oc
ma en ma me
tb n t
subsetrtof
a.b columns
a
elo that the query returns; in this case, rta
.ba justbethe lon FirstName and
No r bo n gs No r bo gs
sa to of the Employee entity. sa to
LastName
un
au properties @
pri M art
un
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
Using a New Class to
llo
we
Return a Subset of Columns llo
we
d! d!

private class FullName


{
public string Forename { get; set; }
Th Th
is is
do
public string Surname { get; set; } docu
cu
m me m m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/33
10/25/2019 20483A - Programming in C# | Skillpipe

}
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.

2. Start the 20483A-SEA-DEV11-07 virtual machine.

3. Log on to Windows 8 as Student with the password Pa$$w0rd.


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/33
10/25/2019 20483A - Programming in C# | Skillpipe

Note: If necessary, click Switch User to display the list of users.

4. Switch to the Windows 8 Start window.

5. Click Visual Studio 2012.


Th Th
is is
do oc d
6. In Visual
ma
um c
e
Studio, on the File menu, point tomOpen,um and then click
e
rt nt art nt
a.b elo b a.b be
N Project/Solution.
arb ng lon
arb
ou os st No os gs
na a @ o u na a @ to
uth pri M art uth pri Ma
ori ma aB ori ma rta
7. In the Open ze
dc Project
ve
rab dialog
a rbo box, browse to the ze
dc
ve
rab
Ba
rbo
op s s s a o p s s sa
ies .co . ies .c .
E:\Democode\Demo3\FourthCoffee.Employees
all m folder, allclickom
ow ow
ed ed
FourthCoffee.Employees.sln, ! and then click Open. !

8. In Solution Explorer, expand FourthCoffee.Employees, and then double-click


Program.cs.

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!

13. Repeat step 12 for each of the following methods:

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!

Querying Data by Using Anonymous Types

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!

Using an Anonymous Type to Return a Subset of Columns

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

Using a group Clause

var emps = from e in DBContext.Employees


group e by e.JobTitle into eGroup
select new { Job = eGroup.Key, Names = eGroup };
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
Aggregating Data
au
tho
riz
prim
av
a rta
au
tho
r
p rim
a
art
aB
ed era B arb ized vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
The following codes aexample om shows how to use a group clause sa with om aggregate
an
llo llo
we we
function to count the number d! of employees with each job title. d!

Using a group Clause with an Aggregate Function

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

Demonstration: Querying Data by Using Anonymous Types


In this demonstration, you will use LINQ to Entities to query data by using
anonymous types.
Th Th
is is
do d oc
cum um
Demonstration
rt
ma
nt
b
Steps e ma
rt
en
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 r t h r
1. Start the riz MSL-TMG1
ed
av
ta B virtual machine if it is not already
arb
ori
zed
imrunning.
a v
aB
arb
era era
co bs o sa co bs os
pie s.c . pie s.c a.
sa om sa om
2. Start the 20483A-SEA-DEV11-07
l l ow
ed
virtual machine. l l ow
ed
! !

3. Log on to Windows 8 as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.


Th Th
is is
do d oc
cum um
ma ent ma en
ta.r b rt a.b tb
4. N
Switch
ba to ethe
r
lon Windows 8 Start window.
g No arb
elo
ng
ou bo st os st
na sa oM un a oM
uth @ au @
pri art tho p rim art
m aB aB
5. Click oVisual
riz
ed Studio
av
era 2012.
arb 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
6. In Visual Studio, won
ed the File menu, point to Open, and then wclick
ed
! !
Project/Solution.

7. In the Open Project dialog box, browse to the


E:\Democode\Demo4\FourthCoffee.Employees folder, click
FourthCoffee.Employees.sln, and then click Open.
Th Th
is is
do oc d
cum um
8. mIn
art Solution e
n t Explorer, expand FourthCoffee.Employees,
m a r
en
tb and then double-click
a.b be ta. elo
arb l ong b arb ng
NoProgram.cs. os st No os 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
ed era r e e
9. Review the co LINQbscode oin
pie
b
sa each of the methods.
d co
p
r ab
s os
a.
s.c . ies s.co
sa om a m
llo llo
we we
10. On the Build menu, d! click Build Solution. d!

11. On the Debug menu, click Start Without Debugging.

12. In the console window, review the output of the UsingAnonymousTypes


method, and then press Enter.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/33
10/25/2019 20483A - Programming in C# | Skillpipe

13. Repeat step 12 for each of the following methods:

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!

IQueryable<Employee> emps = from e in DBContext.Employees


select e;
foreach (var emp in emps)
Th Th
is is
{ do
c
d oc
um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/33
10/25/2019 20483A - Programming in C# | Skillpipe

Console.WriteLine("{0} {1}", emp.FirstName, emp.LastName);


}

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

IList<Employee> emps = (from e in DBContext.Employees


select
Th Th
is is
do
e;).ToList() d oc
c um um
ma e
nt ma en
rta (var
foreach be emp in emps) rt a.b tb
.ba lon elo
No rbo gs No arb ng
un s to un os st
{ au a@ Ma au a @ oM
tho pri rta tho pri art
r ma Ba riz m av aB
i ze
Console.WriteLine("{0} ve {1}", emp.FirstName, ed emp.LastName);
era arb
dc rab rbo os
op ss sa co bs a.
ies .co . pie s.c
} all m sa om
ow llo
ed we
! d!

Demonstration: Retrieving and Modifying Grade Data Lab


In this demonstration, you will learn about the tasks that you will perform in the lab for
Th Th
is is
this module.
do
cu
d oc
um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/33
10/25/2019 20483A - Programming in C# | Skillpipe

Lab: Retrieving and Modifying Grade Data

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!

Estimated Time: 75 minutes

• 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.

The main tasks for this exercise are as follows:

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

1. Start the MSL-TMG1 virtual machine if it is not already running.


Th Th
is is
do do
c cu
2. Start
ma
umthe
en 20483A-SEA-DEV11-07 virtual machine
ma meand log on as Student with
nt
rta t b r t a be
.ba elo .ba lon
the
No password
rbo n gs Pa$$w0rd. 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
3. Start Visual ed
co
Studio,
era
b
and
arb from the E:\Labfiles\Starter\Exercise
os
ze
d co
ve
r ab 1 folder,
rbo open the
pie s s.c a pie s s.c sa
. .
GradesPrototype.sln sa
llo
omsolution. sa
llo
om
we we
d! d!

4. Add a new class library project named Grades.DataModel to the solution.

5. Add a new ADO.NET Entity Data Model named GradesModel to the


Grades.DataModel project.
Th Th
6. Generate
is
do the model from the SchoolGradesDB is
do database on the
cu cu
ma m e ma me
(localdb)\v11.0
rta n tb
elo
server and include the following r t a tables:
nt
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 ori ma rta
riz ve a z v Ba
ed rab rbo e dc e rab rbo
co ss sa op ss sa
pie . i .
• Grades sa .c om e sa . com
llo llo
we we
d! d!
• Students

• 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.

8. ThBuild the solution. 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 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
Task 2: Review co the generated
pie b s s.c sa
.
code co
pie bs
s.c
os
a.
sa om sa om
llo llo
we we
d! d!

1. In the designer window, review the entities that the wizard generated.

2. Review the properties and navigation properties of the Grade entity.

3. Review the mapping details for the Grade entity.


Th Th
is is
do do
c
um cu
4. mIn me
art the GradesModel.Context.tt
en
t be
folder, in GradesModel.Context.cs
ma
rta nt
be
file, review the
a.b l . b l
o on
Nocodearforbo thengSchoolGradesDBEntities
st DbContext
No arb
os object. gs
un sa o u na a to
au @ M uth @ Ma
tho pri art pri rta
riz m av aB ori m a Ba
e e arb ze ve
5. In the GradesModel.tt
d co rab
s
folder,
os
a
in the Grade.cs file, review d co ther ab properties
s
rbo
sa of the
pie s.c . pie s.c .
sa om sa om
Grade entity. llow llo
we
ed d!
!

6. Save all of the files, and then close the solution.

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

2. Display the subject name in the UI

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.

2. Set the GradesPrototype project to be the startup project.

3. ThIn the Views folder, in StudentProfile.xaml.cs, Th in the Refresh method, add


is is
do do
cu cu
mcode
art
mtoentthe end of the method to: ma me
nt
a.b be rta be
arb l o . b arb lon
No ng N gs
un o s s t o un context o s to
a. a@ through oM a@ object
au Iterate pri art the grades in the session a uth pri Ma and, if they belong
tho ma aB ori ma rta
riz ve a z v Ba
to thee d c current
op
rab student, rbo
sa
add them to a new list eofd c grades.
op
e rab rbo
sa
ies ss . ies ss .
.co .co
all m all m
ow ow
b. Use data binding ed to display the list of grades in the studentGrades ed
! !
ItemsControl control.

4. Build the solution and resolve any compilation errors.

5. Run the application.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 26/33
10/25/2019 20483A - Programming in C# | Skillpipe

6. Log on as vallee with a password of password99.

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!

1. In StudentProfile.xaml.cs, in the AddGrade_Click method, add code to:

1. Create and display a new instance of the GradeDialog view.


Th Th
is is
2. If the
do user clicks OK in the GradeDialog view,
cu
do retrieve the data they have
cu
ma me m me
entered
rta ntand use it to create a new Grade object.
art nt
.b be a.b be
arb l on arb lon
No o gst No os gs
un sa oM un a@ to
au @ au Ma
pri art p
3. Save thothe grade
riz m av and a Brefresh the display so that tthe
ho newimgrade
riz
r
av
rtaappears.
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!

Task 4: Run the application and test the grade-adding functionality

1. Build the solution, and then resolve any compilation errors.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/33
10/25/2019 20483A - Programming in C# | Skillpipe

2. Run the application.

3. Log on as vallee with a password of password99.

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!
!

• Comments: Well done!

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!

Exercise 3: Extending the Entity Data Model to Validate Data


Th Th
is is
do d oc
cum um
ma ent maen
Scenario r ta.
ba
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 uth
In this exercise,
tho
riz
pryou
im
av
will
art update the application to validate
a Ba o riz
data
pri
m av
thatart the user enters.
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
First, you will add code we to check whether a class is full before enrolling
d!
we
d! a student and
throw an exception if it is.

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.

The main tasks for this exercise are as follows:

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

1. In Visual Studio, open the GradesPrototype.sln solution from the


E:\Labfiles\Starter\Exercise 3 folder.
Th Th
is is
do do
2. Set cthe um GradesPrototype project to be the startup cu project.
me
ma en ma nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
3. Add
un a new
au
sa
@ class to named customTeacher.csunto thesaGrades.DataModel
M a @ to
Ma
project.
tho pri art uth pri r t
riz m av aB ori m av aB
ed era arb ze era arb
o dc os Teacher.
4. Modify theopclass c
ies
bdeclaration
s s.c s a . to make it a public partial o class
pie bnamed
s s.c a.
all o m s all o m
ow ow
ed ed
5. !
Add a private integer constant named MAX_CLASS_SIZE with ! a value of 8 to

the Teacher class.

6. Add an EnrollInClass method that takes a Student object as a parameter and


returns void.
Th Th
is is
do do
7. In the cu EnrollInClass method, add code to:
m
cu
me
ma en ma nt
rta tb r t a be
.ba elo .ba lon
No rbo ng No rbo gs
•un Use saa@LINQtoquery s
M
to determine how manyun students s a@ are to currently in the class.
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
Note: You l l
l o we can execute a Count query of the students l o we in a particular
d! d!
class by selecting only those students with a TeacherUserId property
equal to the contents of the UserId variable.

8. If the class is full, throw a new ClassFullException exception.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/33
10/25/2019 20483A - Programming in C# | Skillpipe

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.

10. Otherwise, throw a new ArgumentException exception.

11. TIn the Views folder, in the AssignStudentDialog.xaml.cs,


T locate the
his his
do do
Student_Click
cu
m method. cu
me
ma en ma nt
rta tb rta be
.ba elo .ba lon
No rbo ng No rbo gs
12. Towards
un sa the end
@
st
o M of the method, before the call
un to the sa Refresh
@ to method, add
au p art au pri Ma
tho rim aB tho ma r taB
code to: riz
ed
av
era arb riz
ed ve arb
co bs os co r a bs os
pie s.c a. pie s.c a.
sa om sa om
a. Call the EnrollInClass l method to assign the student oto l
l ow
ed
l we this teacher’s
! d!
class, passing the student as a parameter.

b. Save the updated student/class information back to the database.

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.

3. Add a ValidateAssessmentDate method that takes a DateTime object as a


parameter and returns a boolean.
Th Th
4. Inisdthe
oc
ValidateAssessmentDate method, add
is code to:
do
um cu
ma en ma me
rta tb r nt
e t a be
Noa. arIf the DateTime object passed to theN method arb is later than the current date,
. b l o . b lon
bo ng gs
un s s t o u o s t
a @ o Ma ArgumentOutOfRangeException n a @ o Ma
au throw pria new au pexception.
tho ma rta tho rim 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 . . i e . .
b. Otherwise, s a return
llo
c om true. sa
llo
com
we we
d! d!
c. Bring the System.Text.RegularExpressions namespace into scope.

d. Add a ValidateAssessmentGrade method that takes a string as a


parameter and returns a boolean.

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-.

Note: The pattern that you will need to use is:

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!

8. In the Views folder, in the GradeDialog.xaml.cs class, locate the ok_Click


method.

9. In this method, add code to:


Th Th
is is
do do
a. ucCreate a new Grade object. cu
ma m en ma me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
b. sa the ValidateAssessmentDate sa
au Call method, passing
un @ to un @ tothe selected date in
pri M art a uth pri Ma
tho m aB ori m rta
riz av a Ba
theedassessmentDate
co
era arb
os
date picker control. ze
d co
ve
r ab rbo
pie b s a pie s sa
s.c . s.c .
sa om sa om
llo llo
we
c. Call the ValidateAssessmentGrade method, passingwthe ed text in the
d! !
assessmentGrade text box control.

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.

5. ThClick Kevin Lui, and then add a new grade


T for him by using the following
is his
do do
information:
cu
me
cu
me
m m
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/33
10/25/2019 20483A - Programming in C# | Skillpipe

• Date: tomorrow’s date

• 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. !

7. Modify the new grade date by using the following information:

• 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+

• Comments: Well done!

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.

11. In Visual Studio, close the solution.

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

Module 8: Accessing Remote Data

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
! !

Lab: Retrieving and Modifying Grade Data in the Cloud

Module Review and Takeaways

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.

• Access data by using WCF Data Services.


Th Th
is is
do d oc
c 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

Lesson 1 : Accessing Data Across the Web

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.

• Send and receive data.

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.

FtpWebResponse A derivative of the WebResponse class that provides functionality to


process any FTP response.

FileWebRequest A derivative of the WebRequest class that provides functionality for


Th requesting files. Th
is is
do do
umc cu
FileWebResponse
ma en A derivative of the WebResponse
ma me that provides functionality to
class
rta t r nt
.ba belo t a .ba be
n process a file response. 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
Depending on cwhether op bs you want
s.c
os
a to send a request to a d
web co service
pie
r ab
s s.c
byrbousing
sa HTTP
ies . s .
o o
or you want to download all
ow
ed
am file from an FTP site, the .NET Framework all
ow
ed
m
provides the
! !
necessary classes for you to consume these remote data sources in your
applications.

Additional Reading: For more information about the System.Net


Thnamespace, see the System.Net NamespaceTh page at
is is
do do
m
http://go.microsoft.com/fwlink/?LinkID=267811.
c um
e m
c um
e
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 Ba riz Ba
Defining a Data Contract
ed
co
pie
ve
rab
ss
rbo
sa
ed
co
pie
ve
rab
ss
rbo
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/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!

public class SalesPerson


{
[DataMember()]
public string FirstName { get; set; }
Th Th
is
[DataMember()] is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 5/50
10/25/2019 20483A - Programming in C# | Skillpipe

public string Surname { get; set; }


[DataMember()]
public string Area { get; set; }
[DataMember()]
public string EmailAddress { get; set; }
}
Th Th
is is
do d oc
cum um
ma ent ma en
rta b a.b rt tb
.ba elo elo
No rbo ng N arb ng
Additional
un sa s
Reading:
to For more informationo uabout o sthe st
DataContract and
@ M n a @ oM
au p a au p art
tho rim rta tho rim
DataMemberriz
ed
av attributes,
era Ba see the DataContractAttribute riz
ed
aClass
ve
apage
Ba at
rbo r a rbo
co bs
http://go.microsoft.com/fwlink/?LinkID=267812.
sa co bs sa
pie s.c . pie s.c .
sa om sa om
llo llo
we we
d! d!

Creating a Request and Processing a Response

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!

Note: Similar to creating a request object, you create a response object


by invoking the GetResponse method on the WebRequest object, and
you then cast to the type of response you require.

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.

Handling Network Exceptions


When consuming any remote resources, whether an FTP site or an HTTP web
service,
Th you cannot guarantee that the resourceThis online and listening for your
is is
do do
cu cu
request.
ma If m you
en try to send a request to a web service
ma by
me using the HttpWebRequest
n
rta tb rta tb
.b e .ba
lon service is not online, the GetResponse lomethod e
class
No andathe
rbo web gs No rbo ng
s call will throw a
un sa to un sa to
au @ M au @ Ma
WebException
tho
r
prexception
im
a
art
a B with the following message:tho
r
pri
ma rta
Ba
ize ve arb ize ve
dc rab os dc rab rbo
op s s a. op s s sa
ies .co ies .co .
all m all m
WebException – Theowremoteed
!
server returned an error: (404) NotowFound. ed
!

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.

Authenticating a Web Request


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!

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.

Digest Enables users to authenticate by using a user name and password,


but unlike basic authentication, the credentials are encrypted.
Th Th
is is
do do
uc cu
Windows
ma m en Enables clients to authenticate
ma meby using their Windows domain
rta t r nt
.ba belo t a .ba be
rbo n credentials. Windows authentication
rbo
louses
ng either hashing or a
No gs No s
un sa to un authenticate
Kerberos token to securely sa tusers.
oM Windows
au @ Ma au @
tho pri rta tho pri art
riz m av Ba r m a a Ba sign-on (SSO)
ed era rbo
authentication is typically usedizto ed provide ve a single rbo
co b co rab
pie s s.c s a experience in organizations. pie s s.c sa
sa . sa .
om om
llo llo
we we
Certificate d! Enables only clients that have the correct certificate d! installed to
authenticate with the service.

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.

Authenticating Users by Using Credentials


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/50
10/25/2019 20483A - Programming in C# | Skillpipe

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
! !

Authenticating users by using basic or Windows authentication is common, but it


does require users to remember and provide credentials. Alternatively, you may
choose to authenticate clients by using an X509 certificate.
Th Th
is is
do d oc
c um um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 10/50
10/25/2019 20483A - Programming in C# | Skillpipe

Additional Reading: For more information about the NetworkCredential


class, see the NetworkCredential Class page at
http://go.microsoft.com/fwlink/?LinkID=267813.

Authenticating Users by Using an X509 Certificate


Th Th
is is
do do
You can use cu
me
an X509 certificate as a security token to
cu authenticate users. Instead of
me
ma n m a nt
rta tb r t
users having.ba toelospecify
ng
credentials when they access a.b the
a
bremote
elo
ng
data source, they
No rbo s N o r b o s
un sa to un sa to
will automatically
au
tho
@ gain
pri Maaccess as long as the request
r
au that
t
@is sent
pri Mincludes
art the correct
m ta h o m a
riz av Ba riz av Ba
X509 certificate. ed
co To the
era users,
b
rbo this means they need the
s
ecorrect
dc
o
eraX509
b
rcertificate
bo
sa
in
pie s s.c a. pie s s.c .
sa om sa om
their certificate store lloon the
we
computer where the client application llo is running.
we
d! d!

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
! !

Each derivative of the WebRequest and WebResponse classes enables you to


send and receive data by using the specific protocol that the class implements. For
example, the HttpWebRequest class enables you to send requests to a web service
by using
Th the HTTP protocol. Th
is is
do d oc
cum um
ma ent enma
rta be a.b tb
rt
. elo
TheNWebRequest
barb l on base class includes the following members
gs No a rbo ng that you can use to
ou os t u s st
na a o na a oM
send data uth to a@remote
pri Madata source:
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
• ContentType. This ow property enables you to set the type of data ow that the request
ed ed
! !
will send. For example, if you are sending JSON data by using the
HttpWebRequest class, you use the application/json content type.

• 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.

The WebResponse class provides the GetResponseStream method, which enables


you to
T access and stream data from the response.
T
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 12/50
10/25/2019 20483A - Programming in C# | Skillpipe

Sending Data to a Remote Data Source


Whether you are sending data to a web service or uploading a file to an FTP site, the
process for creating the request remains the same:

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.

Uploading a File to an FTP Site

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!

Receiving Data from a Remote Data Source


To get data that a response might contain, you use the GetResponseStream method
of the
Th response object. The GetResponseStream
is
Th method returns a stream, which
is
do do
cu cu
you can
ma read
me to get the data.
n ma me
nt
rta tb rt a.b be
.ba elo lon
No r bo ng No arb gs
un s st un os to
a @ oM a@ Ma
au pri art au p
The following
tho
riz code m avexample aB shows how to use the GetResponseStream
t ho
riz
r im
av
rta
Ba
method to
ed era arb ed era rbo
co bs os co bs
access the response pie data.
s.c a. pie s.c sa
.
sa om sa om
llo llo
we we
d! d!
Reading Data from the Response

var request = WebRequest.Create(uri) as HttpWebRequest;


...This Th
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

var response = request.GetResponse() as HttpWebResponse;


var stream = new StreamReader(response.GetResponseStream());
// Code to process the stream.
stream.Close();

Th you have acquired the response stream, Tyou


When his must then verify that the data is
is
d oc d oc
u
me format. For example, if the response meis returned is in the JSON u
in themacorrect
r nt ma that
r nt
ta. be ta. be
ba lon ba lon
format,
N o u you ocan
r b
s useg s t the DataContractJsonSerializer N ou r bclass
os to
gs serialize the raw
to
na a @ o M na a @ Ma
uth pri art uth pri
JSON dataoriinto ze
anma object
ve
a Bthat you can consume in your ori code.
ze
ma Alternatively,
ve
rta
Ba if the data
dc rab a rbo dc rab rbo
is in the XML format, op
ies ss cansause
you . the SoapFormatter class op to deserialize
ies ss sa the data or
.
.co .co
all m all m
Language-IntegratedowQuery ed
!
(LINQ) to XML to manually parse the ow
eXML.
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
! !

Note: If necessary, click Switch User to display the list of users.

3. ThSwitch to the Windows 8 Start window. Th


is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 15/50
10/25/2019 20483A - Programming in C# | Skillpipe

4. Click Visual Studio 2012.

5. In Visual Studio, on the File menu, point to Open, and then click
Project/Solution.

6. In the Open Project dialog box, browse to E:\Democode\Starter\Fourth Coffee


ThContact Finder folder, click Fourth Coffee Contact Th Finder.sln, and then click
is is
do do
Open. cu
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
7. Inun the Solution
sa
@
s t Explorer window, expand the
o o u FourthCoffee.DataService
n
os
a @ to
au pri M art au pri Ma
tho m a t h o m rta
project, riz and then
ed
av
era double-click
Ba
rbo
ISalesService.cs. rize av
e Ba
rbo
co b dc rab
pie s s.c s a. o pie s s.c sa
sa sa .
om om
8. In the code editor, l ow review the signature of the GetSalesPerson l
ed operation,
l l ow
ed
! !
which accepts an email address in the form of a JSON string and returns a
SalesPerson object.

9. In the Solution Explorer window, expand the FourthCoffee.Infrastructure


project, expand the Models folder, and then double-click SalesPerson.cs.
Th Th
is is
do do
c
um cu
10. mIn
art the code
en
t
editor, review the DataContract ma andmDataMember
en
tb
attributes that
a.b be rta e
arb l on . b arb l on
Nodecorate os thegstype and type members. No os 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
11. In Microsoft e e
co Visual ab Studio®, on the View menu, clickcoTask aList.
d r os d r rbo
pie s a pie b s sa
s.c . s.c .
sa om sa om
llo llo
we we
12. In the Task List window, d! in the Categories list, click Comments. d!

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:

var response = this._request.GetResponse()


as HttpWebResponse;
Th Th
is is
do d oc
cum um
ma ent ma en
25. rta
In the.ba Task belo List window, double-click the TODO: a.b 07:t bCheck
rt elo to see if the
No rbo ng No arb ng
un sa s to un o sa s to
response
au
tho
@contains
pri Ma any data. task.
r
au
t
@
pri Ma
rta
m ta h o m
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s s a c o b s sa
26. In the code ieditor, p es s .click
co in the blank line below the comment,
. p ies s
and
.co then . type the
all m all m
ow ow
following code: ed! ed
!

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
! !

var stream = new StreamReader(response.GetResponseStream());


var result = SalesPerson.FromJson(stream.BaseStream);
stream.Close();
Th Th
is is
do d oc
cum um
ma e nt ma en
rta be a.b rt tb
.ba lon elo
a ng
29. NoOn the
un
r bo Build
s a
gsmenu, click Build Solution.No
t o u
r bo
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 r e e arb
30. In Solution co Explorer,
pie bs right-click
b os
a.
Fourth Coffee Contact d co Finder,
pie
r ab
ss and os then
a.
click
s.c .co
sa om sa m
Set as StartUpllowProject. llo
we
ed d!
!

31. On the Debug menu, click Start Debugging.

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.

35. On the Debug menu, click Stop Debugging.

36. Close Visual Studio.

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!

After completing this lesson, you will be able to:

• Describe the purpose of a WCF Data Service.

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!

• Retrieve and manipulate entities that a WCF Data Service exposes.

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.

Defining a WCF Data Service


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 21/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
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!

public class FourthCoffeeDataService : DataService<FourthCoffee>


{
...
Th Th
is is
} do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 22/50
10/25/2019 20483A - Programming in C# | Skillpipe

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
!

Exposing a Data Model by Using WCF Data Services

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

data service. This method takes a DataServiceConfiguration object, which has a


SetEntitySetAccessRule property that you use to define the access policy.

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!

Additional Reading: For more information about defining access rules in a


WCF Data Service, see the Configuring the Data Service (WCF Data
Services) page at http://go.microsoft.com/fwlink/?LinkID=267817.

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

Exposing Web Methods by Using WCF Data Services

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!

• IEnumerable<T> or IQueryable<T> (where T represents an entity type in the service


operation returns an enumerable collection based on an entity type that the service re
client application can perform queries by specifying HTTP URIs in the manner shown
previous topics in this lesson. Implementing an operation that returns an enumerable
Th Th
is is
do gives
this way do of the collection. It is the respon
you detailed control over the contents
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 25/50
10/25/2019 20483A - Programming in C# | Skillpipe

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

public class FourthCoffeeDataService : DataService<FourthCoffee>


{
Th public static void InitializeService( Th
is is
do d
cu DataServiceConfiguration config)ocu
ma me m me
rta nt art nt
. belo a.b be
b lon
No { rbo a ng
st N ou
a r b os gs
un sa o n a to
au @ M au @ Ma
tho ...prim art
a t h o
pri
m rta
riz av Ba riz av Ba
ed era rbo ed era rbo
co b
config.SetServiceOperationAccessRule("SalesPersonByArea",
s s a. c o b s sa
pie s.c pie s.c .
sa om sa om
l l ow
ServiceOperationRights.ReadMultiple); l l ow
ed ed
! !
}
...
[WebGet]
public IQueryable<SalesPerson> SalesPersonByArea(string area)
Th { Th
is is
do d
cu if (!String.IsNullOrEmpty(area))ocu
ma m en ma me
rta tb r nt
.ba { elo 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 return art from p in this.CurrentDataSource.SalesPerson pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
co b os
where String.Equals(p.Area, d co area) r ab
pie s s.c a pie s s.c sa
sa . sa .
om om
llo l l o
we select p; we
d! d!
}
else
{
throw new ArgumentException("Area must be specified", "a
Th } Th
is is
do d oc
} ume c um
ma nt ma en
rta be rt a.b tb
}N . b lon elo
arb gs No arbng
o
un os to u osst
a @ 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.
You can invoke this s all operation
ow
o m by using the following URI: all
ow
m
ed ed
http://<hostName>/FourthCoffee/FourthCoffeeDataService.svc/SalesPersonByArea?
! !

• 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

public class FourthCoffeeDataService : DataService<FourthCoffee>


{
public static void InitializeService(
DataServiceConfiguration config)
{

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.

public class FourthCoffeeDataService : DataService<FourthCoffee>


{ Th Th
is is
do do
cu
public static void InitializeService( cu
ma m en ma me
rta tb r nt
elo
.ba DataServiceConfiguration t a . be
ng config) b arb lon
N ou rb os st N ou os g st
na a@ oM na a@ oM
{ uth pri
ma
art
aB
uth pri
ma
art
aB
ori ori
ze ve a r ze ve arb
...d 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
config.SetServiceOperationAccessRule("SalesPersonCount",
we we
d! d!
ServiceOperationRights.ReadSingle);
}
...
[WebGet]
Th [SingleResult] Th
is is
do d oc
cu um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 27/50
10/25/2019 20483A - Programming in C# | Skillpipe

public int SalesPersonCount()


{
return (from p in this.CurrentDataSource.SalesPerson
select p).Count();
}
}
Th Th
is is
do d oc
cum um
ma nt e ma en
rta b a.b rt tb
.ba elo elo
r ng arb ng
• void.
N o u Not all bos operations
a@
st
oM
have to return a value.
N o un o sa st
oM
na 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.
ies .co . ies .co
all m all m
ow ow
ed ed
Additional Reading: ! For more information about service operations, ! see the
Service Operations (WCF Data Services) page at
http://go.microsoft.com/fwlink/?LinkID=267818.

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 Tclient library for a WCF Data Service consists


T of a class that is derived from the
his his
do do
DataServiceContext
c um type that exposes one or more cuDataServiceQuery objects as
me
ma en ma nt
rta tb r t
properties..ba Theelname o of this class is usually the same a .ba as bthe elo name of the DbContext
No rbo ng No rbo ng
un s s t u s st
a o a oM
object that
au is used
tho
@
pri by M the
art EDM on which the WCF n Data
a uth Service
@
pri isarbased. For
riz m a o r m ta
av B arb ize a ve Ba
example, theedFourthCoffeeDataService
co
era
b ss o sa WCF Data Service d c op
uses r a b a
ss
DbContext
rbo
sa
pie .c . i e . c .
sa om sa om
object called FourthCoffeeEntities llo
we
to connect to the underlying llo EDM, so the name
we
d! d!
of the DataServiceContext type that is generated for the client library is also
FourthCoffeeEntities.

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

exposes by using the DataServiceQuery properties. Each DataServiceQuery


property is a generic collection object that presents data from one of the underlying
entities that provides the data for the WCF Data Service.

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.

3. If the data service is part of the current solution, click Discover.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 29/50
10/25/2019 20483A - Programming in C# | Skillpipe

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
! !

Retrieving and Updating Data in a WCF Data Service

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.

2. Retrieve data by querying the appropriate DataServiceQuery collection in the


Th his T
is
DataServiceContext object. When you query
do doa DataServiceQuery collection,
cu c um
m me m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 30/50
10/25/2019 20483A - Programming in C# | Skillpipe

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.

Querying the FourthCoffeeDataService WCF Data Service

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.

Querying the FourthCoffeeDataService WCF Data Service by Using a Service


Operation
Th Th
is is
do d oc
cum 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

Querying the FourthCoffeeDataService

FourthCoffeeEntities context = new FourthCoffeeEntities (new Uri


("http://FourthCoffee.com/FourthCoffeeDataService.svc"));
foreach (SalesPerson person in context.Execute<SalesPerson>
Th Th
is is
(new
do
c
Uri("/SalesPersonByArea?area='snacks'",
do
c
UriKind.Relative)))
um um
ma en ma en
{ rta tb r t a.b tb
.ba elo elo
No rbo ng N arb ng
sa s toproduct.EmailAddress; o o sa st
var
un
au
email @ = M un
au @ 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
llo llo
we we
d! d!

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.

FourthCoffeeEntities context = new FourthCoffeeEntities (new Uri


Th Th
is is
do("http://FourthCoffee.com/FourthCoffeeDataService.svc")); do
cu cu
ma m en ma me
tb nt
...rta.b elo r t a . b
be
lon
No arb ng N arb gs
o s
un newSalesPerson s t o o s to
var au a@ oM = new SalesPerson una a@ 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 .
Area = "tea", om om
llo llo
we we
EmailAddress d=! "roy@fourthcoffee.com", d!

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!

Implementing Eager Loading of Entities


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 33/50
10/25/2019 20483A - Programming in C# | Skillpipe

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

of the DataServiceQuery collection property that holds the related data.

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

Explicit Loading of Entities

FourthCoffeeEntities context = new FourthCoffeeEntities (new Uri


("http://FourthCoffee.com/FourthCoffeeDataService.svc"));
foreach (var salesPerson in context.SalesPersons)
Th Th
is is
{ do
c
d oc
um um
ma ent ma en
...
rta be a rt tb
.
ba lon . ba elo
No rbo gs No rbo ng
sa to sa st
context.LoadProperty(salesPerson,
un
au @ M "Sales");
un
au @ oM
tho p rim a rta tho p rim art
r a B r a aB
foreach i z ed (var v era sale arbin salesPerson.Sales) ed iz vera arb
co bs o sa co bs os
pie s.c . pie s.c a.
{ sa om sa om
llo llo
we we
... d! d!

}
}

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!

Estimated Time: 60 minutes

• Virtual Machine: 20483A-SEA-DEV11-08, MSL-TMG1


Th Th
is is
do d oc
um c um
• User
ma Name: en Student ma en
rta tb rt a.b tb
.ba elo elo
No rbo ng No arb ng
u s st un os st
• Password:
na a Pa$$w0rd
@ 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!
Exercise 1: Creating a WCF Data Service for the SchoolGrades
Database

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.

The Tmain tasks for this exercise are as follows: T


his his
do do
cum cu
ma e m me
rta n tb a r nt
t a.b be
1. Create.ba the
rbo
eloGrades.Web project
ng 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
m a o m
2. Add aridata ze
dc
service
av
e rab
to
Ba the Grades.Web project
r
riz
e dc
av
e rab
Ba
rbo
bo
op s s s a o p s s sa
ies .co . ies .co .
all m all m
3. Specify the GradesDBEntities ow
ed data context for the data service ow
ed
! !

4. Add an operation to retrieve all of the students in a specified class

5. Build and test the data service

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

c. Project Url: http://localhost:1650/

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

e. Save all of the files.

Task 2: Add a data service to the Grades.Web project

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.
!

4. Add a reference to the EntityFramework assembly. This assembly is located in


the E:\Labfiles\Starter\Exercise 1\packages\EntityFramework.5.0.0\lib\net45
folder.

5. ThCopy the <connectionStrings> element from Th


is is the App.config file in the
do do
cu cu
m
mGradesPrototype
en project and paste it into the
ma Web.configme file in the Grades.Web
art t rta nt
a.b be . be
arb l on b arb l on
Noproject. os gs No os 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.c a . pie s.c .
sa om sa om
Note: The llo data service in the Grades.Web project needs
we
llo
we
to connect to
d! d!
the same data source that the data model uses.

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

SchoolGradesDBEntities class as the data source.

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.

2. In this operation, use a LINQ query against the CurrentDataSource object to


retrieve and return all of the students in the class.
Th Th
3. Inis
dthe
oc InitializeService method, set the accessis rule for the StudentsInClass
do
cu
um me
ma en ma nt
operation
rta
.ba
t b to ServiceOperationRights.AllRead.
elo r 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
Task 5: Build and test dthe
! data service d!

1. Build the solution, and then resolve any compilation errors.

2. View GradesWebDataService.svc in Windows Internet Explorer®.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 39/50
10/25/2019 20483A - Programming in C# | Skillpipe

3. Verify that Internet Explorer displays an XML description of the entities that the
data service exposes.

4. Close Internet Explorer.

5. In Visual Studio, close the solution.


Th Th
is is
do d oc
cum um
ma nte ma en
rta b a.brt tb
.ba elo elo
Results:
No rAfter
bo completing
ng
s this exercise, you should
N o
ahave
r b o
added
ng
st a WCF Data
un sa to un sa oM
Service @
au to the papplication M to provide remote access @
au to thep SchoolGrades
tho rim art tho rim art
riz av aB r a aB
arb iz v arb
database. ed c era
bs o sa
ed
co
era
bs os
op s . p s a.
ies .co ies .co
all m all m
ow ow
ed ed
! !

Exercise 2: Integrating the Data Service into the Application

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!

The main tasks for this exercise are as follows:

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.

2. In the GradesPrototype project, remove the reference to the Grades.DataModel


project.

3. ThAdd a service reference to http://localhost:1650,


is
Th
is using the namespace of
do do
cu cu
mGrades.DataModel.
art
me
nt ma me
nt
a.b be rta be
a lon .ba lon
No rbo gs No rbo gs
sa to sa to for the service
4. Update
un
au the
@ namespace
pri M art
declaration in the Reference.cs
un
a uth @
pri
file Ma
tho m aB ori m rta
riz av a
ze file isvegenerated Ba
reference ed to Grades.DataModel.
co
era
b
arb
os The Reference.cs d co r ab rbo in the
pie s s.c a pie s s.c sa
sa . sa .
om
Service References\Grades.DataModel\Reference.datasvcmap omfolder in
llo llo
we we
d! d!
Solution Explorer. You need to enable Solution Explorer to show all files to see
this 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

5. Add a new folder named DataModel to the GradesPrototype project.

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!

1. In the Grades.Web project, in the Services folder, in SessionContext.cs, modify


the DBContext declaration to pass a new Uri object pointing to
http://localhost:1650/Services/GradesWebDataService.svc to the
Th Th
is is
SchoolGradesDBEntities
doc
um
constructor. 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
thoNote: mThe
av DBContext object provides theoobject mcontext
aB rta for accessing
riz arb r ize a ve Ba
ed era dc rab rbo
the cdataop
ies
source.
b ss
.co
Previously
o sa
.
this object context retrieved
op
ies ss data
.co
sdirectly
a.
from a local a m
llo EDM. Now the data service provides this a m
llo object context, and
we we
d! d
the constructor requires the URL of the data service. !

2. Add the following static constructor to the SessionContext class.

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).

5. In LogonPage.xaml.cs, in the Logon_Click method, modify the statement that


loads teacher data to also load the user and student data for that teacher. As an
Th Th
is is
alternative
do
c to using the LoadProperty method do of the data context, use the
c
um um
ma en ma en
Expand
r ta.
ba
tmethod
be
lon
when the data is fetched by using r ta.
ba
the
t b LINQ query.
elo
No r bo gs No r bo ng
un s t u s st
a @ o M n a @ oM
au pri art a uth pri athe
6. In LogonPage.xaml.cs,
tho
riz m av a Ba
in the Logon_Click method, o riz modify
m av
rta statement
Ba
that
ed era rbo e dc e rab rbo
loads student c op data b ss to also sa load the user and grades data. op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
7. In the GradesPrototype solution, in the customTeacher.cs file, add a using
directive to bring the GradesPrototype.Services namespace into scope.

8. In the EnrollInClass method, modify the from statement to reference the


Students collection in the SessionContext.DBContext object.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 43/50
10/25/2019 20483A - Programming in C# | Skillpipe

9. In the AssignStudentDialog dialog, in the Refresh method, modify the code


that finds unassigned students to reference the
SessionContext.DBContext.Students collection rather than
SessionContext.DBContext.Students.Local. This change is necessary
because the data model implemented by the data service does not provide the
Local property. You should also use the Expand method to retrieve the User
Th Th
is is
and
do Grades information for the students.
cu
d
um
oc
ma me ma en
rta nt rt tb
.ba belo a.b elo
10. NoIn therbStudentProfile
ng view, in the AddGrade_Click
N arb method,
ng find the code that
un o sa s to o un o sa st
@ M @ oM
au pri au
uses thothe Add ma method
art
a B of the Grades collection tto ho addpra im grade art
a to
riz
ed v era arb r ized
a vera Ba a student.
o rbo
co bto sthe co bs sa class.
Modify this pcode
ies s s use
.co a . AddToGrades method of the
p ies DBContext
s .co .
all m all m
ow ow
This change is necessary ed
!
because the Grades collection implemented ed
!
by WCF
Data Services does not provide the Add method.

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

1. In the code for the AssignStudentDialog view, in the Student_Click method,


Th Th
add
is
do code to specify that the selected student
is has been changed before the call
do
cu cu
mto m me
art the SessionContext.Save
e n tb method. m art nt
be
a.b elo a . 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
Note:e d c WCF rab Data rboServices requires that you explicitly e e rabmark rban
op ss sa
dc
op ss os entity as
ies .co . ies .co a.
updated,allotherwise ow
m any changes will not be saved. all
ow
m
ed ed
! !

2. In the StudentProfile view, in the Remove_Click method, add code to specify


that the current student has been changed before the call to the
SessionContext.Save method.
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 44/50
10/25/2019 20483A - Programming in C# | Skillpipe

3. In the Controls folder, in ChangePasswordDialog.xaml.cs, in the ok_Click


method, add code to specify that the current user has been changed before the
call to the SessionContext.Save method.

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:

a. Remove Eric Gruber from the class.


Th Th
is is
do do
b.
ma
u Enroll
c
m en
Jon Orton into the class. ma
cu
me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
c.una Change sa
@ the
to password to password88,unand then
M a
sa
@ verifyto that you
Ma can log on
uth pri art uth pri rta
ori m a aB ori m a
withze the vnew
dc era password.arb ze
d
ve
r ab
Ba
rbo
op bs os co s sa
ies s.c a . pie s.c .
all om sa om
ow llo
d. Log on as grubere ed
!
with a password of password. we
d!

e. Verify that his student profile appears, and then log off.

4. Close the application.

5. ThIn Visual Studio, close the solution.


is
Th
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 p a a u p Ma
t
Results:hoAfter r
completing
im r ta this exercise, you should t hhave
ori r
updated
im rta the Grades
riz av B arb ze a ve Ba
ed era dc rab rbo
Prototype application c op b o
ssto usesathe WCF Data Service. op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !

Exercise 3: Retrieving Student Photographs Over the Web

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.

The Tmain tasks for this exercise are as follows: T


his his
do do
cum cu
ma e ma me
rta nt rt nt
b a be
1. Create
No
.ba the
rbo
eloImageNameConverter value converter
n gs No
.ba class
rbo
lon
gs
un sa to un sa to
au @ M a uth @ Ma
tho pri art pri rta
m aB o m
2. Add anizeImage
r
dc
a vecontrol
rab arbto the StudentsPage view and r ize bindveit to the
d
a
r
Ba ImageName
rbo
op os co ab sa
i s s a . p i s s .
property es
all
.co
m
es
all
. co
m
ow ow
ed ed
! !
3. Add an Image control to the StudentProfile view and bind it to the ImageName
property

4. Add an Image control to the AssignStudentDialog control and bind it to the


ImageName property
Th Th
is is
do oc d
cum um
5. mBuild
art andne
t test the application, verifying that
m student’s
a r
en photographs appear
tb in the
a.b be ta. elo
a l on b a ng
Nolist of bstudents
r o gs for the teacher 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
llo a llo m
Task 1: Create the ImageNameConverter we
d! value converter class we
d!

1. In Visual Studio, open the GradesPrototype.sln solution from the


E:\Labfiles\Starter\Exercise 3 folder.

2. ThIn the GradesPrototype


is project, in StudentsPage.xaml.cs,
Th
is create a new public
do do
cu cu
m me m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 46/50
10/25/2019 20483A - Programming in C# | Skillpipe

class named ImageNameConverter that implements the IValueConverter


interface.

3. In the ImageNameConverter class, define a string constant named webFolder


that contains the string “http://localhost:1650/Images/Portraits/”.

4. ThImplement the IValueConverter interface.Th


is is
do do
cu cu
mIn me m me
5. art the Convert
a.b
nt
b method, add code to check whether
a r t a.b
nt the value that is passed to
be
elo lon
arbo
Nothe method ng N a r b gwebFolder
un sa
@
contains
st
o a string, and if so, append
ou
n
it oto
s a the
@
st
oM string and
au p M a au p art
tho rim rta tho rim a B string.Empty.
returnrithe ze result. av
era If the Ba value passed to the method
rbo
riz is null,
ed
av return
era arb
dc bs co bs os
op s sa p s a.
There is no ineed es
all
to .coadd any code to the ConvertBackiemethod.
m
. sa . com
ow l l ow
ed ed
! !
6. Build the solution and resolve any compilation errors.

TaskT 2: Add an Image control to the StudentsPage


Th
view and bind it to the
his is
ImageNamedo
c property do
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
1. In atheuth XAML
ori
pri markup
m r taB
for the StudentsPage view, u t h add
ori
a
p r imreference art
aB
to the clr-
ze av a z av a
dc era rbo e era rb
namespace:GradesPrototype.Views
op bs
s.c sa
.
namespace.d Assign co
pie bthis
ss to oxmlns:local.
sa
.
ies om sa . co
all l m
This is the namespace o we that contains the ImageNameConverter l o we class.
d! d!

2. Add an instance of the ImageNameConverter class as a resource to the view.

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
!

Task 4: Add an Image control to the AssignStudentDialog control and bind it to


the ImageName
Th property Th
is is
do d oc
cum um
ma ent ma
en
rta be a.b tb
rt
.ba lon elo
a ng add a reference
1. NoIn therbXAML
un o sa
gsmarkup for the AssignStudentDialog
t o
No
u
rbocontrol,
s a
st
oM
to the
au @ Ma na @
t p r r u t p r art
clr-namespace:GradesPrototype.Views
h ori
ze
i m av
taB
a
namespace. h ori
z
imAssign
av a Bthis to
arb
dc era rbo ed era
o b s s c o b s os
xmlns:local. pie
sa
s.c
om
a . pie
sa
s.c
om
a.
llo llo
we we
d! d!
2. Add an instance of the ImageNameConverter class as a resource to the view.

3. At the top of the StackPanel control. As before, use the ImageNameConverter


to convert the value in the ImageName property into a URL and display the
image retrieved from this URL. Set the height of the Image control to 100.
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
Task 5: Build and m test athe application, verifying that o student’s
m photographs
aB
riz av Ba riz av arb
ed era rbo e d e r ab
appear in the clist op of students
ies
bs
s .co
sa for the teacher
.
co
p ies s s.co
os
a.
all m all m
ow ow
ed ed
! !

1. Build the solution, and then resolve any compilation errors.

2. Log on as vallee with a password of password88.

3. Verify that the students list now includes images.


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 48/50
10/25/2019 20483A - Programming in C# | Skillpipe

4. View George Li’s profile and verify that his image appears.

5. Remove George Li from the class.

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.

Test Your Knowledge


Th Th
is is
do d oc
cum um
ma e nt maen
rta be a.b rt tb
.ba l o elo
Question
No r bo n 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
m a o m aB
Which of therizfollowing
ed
av correctly
era Ba describes how to access data that
rbo
riz is provided
e d
av
e r inaan
rbo
co bs sa co ab sa
pie s.c . p i s s .
sa om e sa . com
llo llo
HTTP response? we we
d! d!

Select the correct answer.

Invoke the GetResponseStream static method on the HttpWebResponse class.

Read the ContentLength instance property on the HttpWebResponse object.


Th Th
is Invoke the GetRequestStream instance method on theis HttpWebResponse object.
do do
cu cu
m m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 49/50
10/25/2019 20483A - Programming in C# | Skillpipe

Question

Invoke the GetResponseStream instance method on the HttpWebResponse object.

Invoke the GetResponseStream instance method on the HttpWebRequest object.

Test TYour Knowledge Th


his is
do d oc
cum um
ma ent ma en
rta b a.b rt tb
.ba elo elo
n arb ng
Question
N ou r bos g st N o un o sa st
na a@ oM @ oM
uth pri art au p art
ori ma aB t h ori r ima a
When you create z ed a WCF v arb
eraData Service to provide remote access z
toedan EDM, verahow B arbyou specify
do
co bs o sa co bs os
pie s.c . pie s.c a.
which entity sets thes data all service om should make available to client applications? sa om
ow l l ow
ed ed
! !

Select the correct answer.

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

Module 9: Designing the User Interface for a Graphical


Application

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 2: Binding Controls to Data

Lesson 3: Styling a UI

Lab: Customizing Student Photographs and Styling the Application


Th Th
is is
do d oc
um Module Review and
c Takeaways 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 b os co b os
Module Overview pie
sa
llo
we
s s.c
om
a. pie
sa
llo
we
s s.c
om
a.

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!

• Bind a XAML control to data.

• Apply styles to a XAML UI.

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

Lesson 1 : Using XAML to Design a User Interface

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:

• Explain how to use XAML to define the layout of a UI.

• 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!

XAML enables you to define UI elements by using a declarative, XML-based syntax.


When
Th you use XAML in a WPF application, youThuse XML elements and attributes to
is is
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 2/64
10/25/2019 20483A - Programming in C# | Skillpipe

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.

The following example shows the basic structure of a XAML UI:


Th Th
is is
do d oc
cum um
ma nt e en ma
r tb rt
Defining t a.b a Button
arb
belo in XAML 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.
sa
<Window x:Class="MyNamespace.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"
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.

RadioButton Enables the user to select from a range of mutually exclusive


options.
Th Th
is is
do
TabControl do in a UI into a set of tabbed pages.
Organizes the controls
cu cu
ma me ma me
rta nt rt nt
. be a.bbe
TextBlock b lon Displays a read-only block lon
No arbo gs No a rbo of text. gs
un sa to un sa to
au @ Ma au @ Ma
tho pri rta tho pri
TextBox riz m av Ba Enables the user to enterrizand edit ma text. rta B
ed era rbo ed ve arb
co b co rab os
pie s s.c sa pie ss a.
sa . sa . c
om om
llo llo
we we
Setting Control Properties 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 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:

Using Property Element Syntax to Set Control Properties


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
u s t u s st
<Button
na Content="Geta @ o Ma Me a Coffee!" na a @ oM
uth pri r t u t h p r i art
ori m av aB ori mav aB
ze Margin="150,
era a rbo 130, 150, 130"> ed c z era arb
dc b b os
op s s.c s a o pie s s.c a.
ies . s
<Button.Background> all o m all o m
ow ow
ed ed
!
<LinearGradientBrush StartPoint="0.5, 0.5" EndPoint="1.5, ! 1.5"
>
<GradientStop Color="AliceBlue" Offset="0" />
<GradientStop Color="Aqua" Offset="0.5" />
</LinearGradientBrush>
Th Th
is is
d
</Button.Background>
oc do
um cu
ma en ma me
rta tb r nt
<Button.Foreground>
.ba elo t a .ba be
lon
No rbo ng No rbo gs
s
un <SolidColorBrush s t s to
au a@ oM Color="Black" /> una a@ Ma
tho pri art uth pri rta
riz ma aB ori ma Ba
</Button.Foreground>
ed ve a rbo ze ve rbo
co rab dc rab
pie ss sa op ss sa
sa .c . i e sa . c .
</Button> om om
llo llo
we we
d! d!

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.

The following example shows how to add content to a WPF control:

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

Creating Event Handler Methods

private void btnMakeCoffee_Click(object sender, RoutedEventArgs e)


{
lblResult.Content = "Your coffee is on its way.";
Th Th
is is
} do
c
d oc
um 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
@ M @ oM
au p a au p art
tho rim rta tho rim aB
Note:rizWPF ed uses
av
era the B concept
arb of “routed events”. r When
ized an
a vera event arbis raised,
co b s o s c o b s os
WPF will attempt pie sto
. run athe
. corresponding event handler pie for sthe . a.
control that
sa c om sa com
llo llo
has the focus. If there w ed
!
is no event handler available, then WPF wed will examine
!
the parent of the control that has the focus, and if it has a handler for the
event it will run. If the parent has no suitable event handler, WPF examines
the parent of the parent, and so on right up to the top-level window. This
process is known as bubbling, and it enables a container control to implement
default event-handling logic for any events that are not handled by its children.
ThWhen a control handles an event, the event Th is still bubbled to the parent in
is is
do do
case cu the parent needs to perform any additional
m
cu processing. An event handler
me
ma en ma nt
r
is passed t r
t a.ba beloinformation about the event in the RoutedEventArgs
t a .ba be
lon parameter. An
No rbo n gs No rbo gs
event
un
au
handler
sa
@ tocan use the properties in thisuparameter
Ma na sa
@ totodetermineMa
the
tho pri rta uth pri r t
source riz of theaveventB(the
ed
m
era arb control that had the focus
ori whena the event
ze
m
ve
aB
arb was
c b o dc rab os
raised). The op RoutedEventArgs
ies ss
.co
sa
. parameter also includes op a Boolean
ies ss
.co property
a.
all m all m
called Handled.owAn ed event handler can set this property to true
ow
ed to indicate that
! !
the event has been processed. When the event bubbles, the value of this
property can be used to prevent the event from being handled by a parent
control.

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.

Grid Child controls are added to rows and columns


within the grid.
Th Th
is is
do d oc
umc um are stacked either vertically or
StackPanel
ma en Childmcontrols e
rta tb art nt
.ba elo a.b be
r ng horizontally.
ar lon
No bo st No bo gs
un s a oM un sa to
au @ au @Ma
tho pri art t p r
ho are stacked
im rta vertically or
VirtualizingStackPanel
riz m av aB Child controls riz av either Ba
ed era arb ed era rbo
co bs os horizontally. At any coone time, b ss only child
sa items that
pie s.c a. pie . .
sa om sa com
llo are visible on the screenllare ow created.
we ed
d! !
WrapPanel Child controls are added from left to right. If there
are too many controls to fit on a single line, the
controls wrap to the next line.

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

Using a Grid Layout

<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!

<Label Content="This is Row 0, Column 0" Grid.Row="0"


Grid.Column="0" />
<Label Content="This is Row 0, Column 1" Grid.Row="0"
Grid.Column="1" />
Th Th
is
<Label Content="This is Row 1, Columnis 0" Grid.Row="1"
do do
cu cu
ma m en ma me
Grid.Column="0"
rta tb /> rta nt
.ba elo .ba be
ng lon
No rbo st No rbo gs
<Label
un saContent="This
oM is Row 1, Column sa
un 1" Grid.Row="1" to
au @ au @ Ma
tho prim art ptho rim rta
Grid.Column="1" riz av /> a Ba riz av Ba
ed era rbo ed era rbo
co bs sa co b s sa
pie s.c . pie s.c .
</Grid> sa om sa om
llo llo
we we
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
!

• The DockPanel Class page at http://go.microsoft.com/fwlink/?


LinkID=267824.

• The Grid Class page at http://go.microsoft.com/fwlink/?LinkID=267825.


Th Th
•is doThe StackPanel Class page at http://go.microsoft.com/fwlink/?
is
do
cu cu
ma LinkID=267826.
m en ma me
nt
rta t b r t a be
.ba elo .ba lon
No rbo n gs No rbo gs
•una ThesVirtualizingStackPanel
a@ to
M Class page atuna sa
@ to
Ma
uth pri art uth pri rta
ori m
http://go.microsoft.com/fwlink/?LinkID=267827.
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 .
om om
• The WrapPanel a llo
we
Class page at http://go.microsoft.com/fwlink/? llo
we
d! d!
LinkID=267828.

Demonstration: Using Design View to Create a XAML UI


Th Th
In thisisdemonstration,
do
c
is
you will create a simple WPF doapplication that contains a button
c
um um
ma en ma en
and a label.
r ta.
ba
When
t be
lon
you click the button, an event handler r ta.
ba
t bwill update the text on the
elo
No r bo gs No r bo ng
st
label. una s a@ t oM un
a
s a @ oM
uth pri art 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.
ies .co . ies .co
The demonstration aillustrates llo m various ways in which you can create
a llo and
m configure
we we
XAML files in Visual Studio. It illustrates how you can add controlsdto
d! ! the design

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

1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20483A-SEA-DEV11-09 virtual machine.

3. ThLog on to Windows 8 as Student with the Tpassword his


Pa$$w0rd.
is
do do
cu cu
ma me m me
rta n tb a r nt
.ba elo t a.b be
ng a lon
No rbo N r b gs list of users.
un Note:
sa
@
Ifs necessary,
t o click Switch Usero uto display
n
os
a @
the to
au pri M art au pri Ma
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 .
sa om sa om
llo llo
4. Switch to the Windows we 8 Start window. we
d! d!

5. Click Visual Studio 2012.

6. In Visual Studio, on the File menu, point to New, and then click Project.

7. ThIn the New Project dialog box, in the Templates


is
Th
is
list, click Visual C#, and then
do do
cu cu
min
art
the mProject
en Type list, click WPF Application. ma me
nt
a.b t be rta be
a lon .ba lon
No rbo gs No rbo gs
8. Inunathe sa
Name to
box, type DesignView. un sa to
uth @ M a uth @ Ma
pri art pri rta
ori m a aB ori m a Ba
ze ve arb ze ve rbo
dc rab os d co r ab
o s s sa
9. In the Location pie
sa text
s.c box, . set the location to E:\Democode,
om
a pie
sa ands.c then
om
. click OK.
llo llo
we we
d! d!
10. In the XAML pane, in the Window element, change the value of the Title
attribute to Order Your Coffee Here.

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

release the button.

14. In the XAML pane, in the Button element, change the value of the Content
attribute to Make Me a Coffee!

15. Change the value of the HorizontalAlignment attribute to Center.


T T
16. hChange
is
do the value of the Width attribute to hAuto.
is
do
cu cu
ma me ma me
rta nt rt nt
be
.ba Properties a.b be
17. NoIn the rbo
lon
gs window, ensure the button
No is selected,
a rbo
lon and then in
gs the Name
un sa to un sa to
@
au type btnGetCoffee. M au @ Ma
box, tho pri
ma
art
aB tho pri
m rta
riz v arb riz av Ba
ed era ed era rbo
co bs os co b s sa
pie s.c a. pie s.c .
18. In the Toolbox s a pane,
llo
om double-click Label. sa
llo
om
we we
d! d!
19. On the design surface, drag the label to anywhere in the lower row of the Grid.

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.

25. In the btnGetCoffee_Click method, add the following code:


Th Th
is is
do do
c
um cu
malblResult.Content
en = "Your coffee ma on mits
is en way.";
rta tb rta tb
.ba elo .ba elo
No rbo ng No rbo ng
un sa st u sa st
@ o M n @ 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
26. On the Debug co
pie menu, bs
s.c click sa Start Without Debugging. cop
.
ab
s s
os
a.
sa om ies .co
llo a llo m
we we
d! d!
27. In the Order Your Coffee Here window, click Make Me a Coffee!

28. Notice that the label displays a message.

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

Creating User Controls

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:

Creating a User Control in XAML


Th Th
is is
do d oc
cum um
ma ent en ma
rta be a.b tb rt
.ba lon elo
No r bo gs No a r bo ng
un s t u s st
<UserControl a @ o
x:Class="DesignView.CoffeeSelector"
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.
s all o
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
m all m
ow ow
ed ed
!
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" !

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!

<Label Content="Do you want milk?"/>


<RadioButton x:Name="radMilk" Content="Milk"
HorizontalAlignment="Left"
VerticalAlignment="Top" Margin="5,5,5,5"
Th Th
is
GroupName="Milk" is
do do
cu cu
ma m en ma me
rta tb IsChecked="True" r nt
Checked="radMilk_Checked" />
.ba elo t a .ba be
n lon
No r bo gs No r bo gs
un sa <RadioButton
to x:Name="radNoMilk"
un Content="No
sa to Milk"
au @ M a uth @ Ma
tho pri art pri r ta
riz ma aB ori ma Ba
HorizontalAlignment="Left"
ed ve
r arb ze
d
ve
r rbo
co ab o sa c op a b sa
pie ss . i ss .
sa .cVerticalAlignment="Top"
om e
Margin="5,5,5,5"sa . com
llo llo
w we
GroupName="Milk" ed! 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
!

Creating the Code-Behind Class for a User Control

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

public partial class CoffeeSelector : UserControl


{
public CoffeeSelector()
{
InitializeComponent();

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
!

xmlns:[your prefix]="clr-namespace:[your namespace],[your assembly name]"

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 add a user control in XAML:

Adding a User Control to a WPF Application


Th Th
is is
do d oc
cum um
ma ent en ma
rta be a.b tb rt
.ba l o elo
<Window
No rx:Class="DesignView.MainWindow"
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
riz av Ba riz av arb
ed era rbo e d e r ab
co bs sa
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" co s os
pie s.c . p ies s.co a.
sa om a m
llo llo
we
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" we
d! d!
xmlns:coffee="clr-namespace:DesignView"
Title="Order Your Coffee Here" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
Th
is
<RowDefinition Height="8*"Th/>
is
do do
cum cu
m e <RowDefinition Height="*" />
m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 19/64
10/25/2019 20483A - Programming in C# | Skillpipe
g /
</Grid.RowDefinitions>
<coffee:CoffeeSelector x:Name="coffeeSelector1" Grid.Row="0"
OrderPlaced="coffeeSelector1_OrderPlaced" />
<Label x:Name="lblResult" Margin="5,5,5,5" Grid.Row="1" />
</Grid>
</Window>
T Th
his is
do d oc
cum um
ma nte 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 au
When youthohave riz
pradded
im
av
a rthe
taB user control, you can handlet h ori events
p r ima and
art get or set
aB
ed era arb zed vera arb
property valuescoin o othe
pie thebsame way that you would for a built-in
ss sa co control. bs In sa previous
.c . p i e s. c .
sa om sa om
llo llo
example, the OrderPlaced we
d!
event of the CoffeeSelector control is we wired up to the
d!
coffeeSelector1_OrderPlaced method.

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!

In the previous code example, the coffeeSelector1_OrderPlaced method handles


the OrderPlaced event of the CoffeeSelector control. The method then retrieves the
orderT details from the control and writes them toT a label.
his his
do do
cum cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 20/64
10/25/2019 20483A - Programming in C# | Skillpipe

Lesson 2: Binding Controls to Data

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:

• Describe how data binding works in WPF.

• 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
! !

Introduction to Data Binding

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!

Note: A dependency property is a special type of wrapper around a regular


property. Dependency properties are registered with the .NET Framework
runtime, which enables the runtime to notify any interested parties when
Th
the value of the underlying property changes. Th
This ability to notify changes
is is
dois what makes data binding work. Most built-in
cu UI elements implement
do
cu
m
ma dependencyen m me
rta tb properties and will support data
art
a
binding.
nt
be For more information
.ba elo .ba lon
No about n
rbo dependency
gs properties, see the NDependency rbo gProperties Overview
un sa to ou sa st
@ M na @ oM
au
page
tho atprihttp://go.microsoft.com/fwlink/?LinkID=267829.
m
art
a
uth
o
pri
m
art
a
riz av Ba riz av Ba
ed era rbo ed era rbo
co b s sa co bs sa
pie s.c . pie s.c .
sa om sa o m
llo llo
we we
d! d !

The following example shows a simple data binding expression:

Simple Data Binding


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 Text="{Binding
gs No ngcoffee1}, arb
<TextBlock
un s to Source={StaticResource
u os st
a@ Ma na a@ oM
au p uth pri art
Path=Bean}"t ho r
/> im rta ori ma aB
riz av Ba ze ve arb
ed era rbo dc rab
co b ss sa op s os
pie . . ies s.co a.
sa c om
llo all m
we ow
d! ed
!
In this example, the Text property of a TextBlock is set to a data binding expression.
Note that:

• 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 Source property of the Binding object is set to {StaticResource coffee1}.


This is an object instance defined elsewhere in the solution.

• 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 binding target is the Text property of the TextBlock element.

• The binding object is defined by the expression in braces.


Th Th
is is
do d oc
c um um
ma ent ma
en
rta be a.b tb
rt
.ba lon elo
No rbo gs No a rbo ng
You canun alsosaconfigure the direction of the data binding. For st
@ example, you might want
t o u na s a oM
au @ Ma u
tho p rim rta tho p rim art
aB
to update the riz UI when
ed
av
era the Basource data is changed or you
rbo
riz might
ed
av want
era ato
rboupdate the
co b s s a c o b s sa
pie s.c . p s.c . of the
source data when sthe
all user om edits a value in the UI. To specifyiesthe all direction
om
ow ow
ed ed
binding, you set the Mode ! property of the Binding object. The Mode ! property can

take the following values:

Mode Value Details


T
his his T
TwoWay d Updates the target property when d the source property changes, and
oc oc
um u
metarget property changes.
ma ent updates the source property when
ma the n
rta be r ta. tb
.ba lon ba elo
No r bo gs No r bo ng
OneWay s Updates the target property when the s
source st
property
un a @ t o M u n a @ o M changes.
au pri art a uth pri art
tho m a o m aB
riz av Ba riz av arb
OneTime e d e r rb
Updates e d
the target property only when thecoapplication e r ab starts
co ab
ss os s osor when the
pie .co a . p ies s .co a.
sa DataContext
m property of the target is changed. a m
llo llo
we we
d! d!
OneWayToSource Updates the source property when the target property changes.

Default Uses the default Mode value of the target property.

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

Specifying the Binding Direction

<TextBox Text="{Binding Source={StaticResource coffee1}, Path=Bean,


Mode=TwoWay}" />

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

Binding an Individual Item to a Static Resource

<TextBlock Text="{Binding Source={StaticResource coffee1},


Path=Name}" />

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.

The following example shows how to specify binding paths in XAML:


Th Th
is is
do d oc
cum um
ma e
nt en ma
r tb rt
Specifying
t a.b
arb
Binding
belo Paths in XAML 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.
sa
<StackPanel x:Name="stackCoffee"> om sa om
llo llo
we we
d! d!
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Bean}" />
<TextBlock Text="{Binding Path=CountryOfOrigin}" />
<TextBlock Text="{Binding Path=Strength}" />
</StackPanel>
Th Th
is is
do d oc
cum um
ma ent ma en
rta be a.b rt tb
.ba lon elo
No example,rbo No each a rbo individual ng
In this un sa you
gs have set the binding path for
t o u s a
st
o M text block in XAML.
au @ Ma na @
tho p rim rta u tho p rim art
To complete riz the binding,
ed
av
era
all
B a you need to do is to set the riz DataContext
ed
av
era
a B property of the
arb
rbo os
co b s s a c o b s a.
parent StackPanel pie object
sa
s.c to the
om
. Coffee instance that you want pie
s a to display.
s.c
om
llo llo
we we
d! d!

The following example shows how to specify a DataContext property in code:

Specifying the Data Context Programmatically

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

Binding Controls to Collections

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:

Setting the DisplayMemberPath Property

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

<ListBox x:Name="lstCoffees" DisplayMemberPath="Name" />

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); !

// Set the ItemsSource property of the ListBox to the coffees


collection.
lstCoffees.ItemsSource = coffees;

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

Additional Reading: For more information about the


ObservableCollection<T> class, see the ObservableCollection(T) class at
http://go.microsoft.com/fwlink/?LinkID=267831. For more information
about the INotifyPropertyChanged interface, see the
INotifyPropertyChanged Interface page at http://go.microsoft.com/fwlink/?
LinkID=267832.
Th Th
is is
do d oc
cum um
ma ent ma en
tb
Creating Data Templates
No
rta
.ba
rbo
be
lon
gs No
rt a.b
arb
elo
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 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!
!

<ListBox x:Name="lstCoffees" Width="200">


<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
Th Th
is is
do <Grid.RowDefinitions> d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 31/64
10/25/2019 20483A - Programming in C# | Skillpipe

<RowDefinition Height="2*" />


<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Path=Name}" Grid.Row="0"
Th Th
is is
do
c
FontSize="22" Background="Black"
do
c
um um
m
art nt e ma en
Foreground="White"
a. be /> rt a.b tb
ba lon elo
No rbo gs No arb ng
sa <TextBlock
to o sa st
un
au @ Ma Text="{Binding Path=Bean}"
un
au @ Grid.Row="1"
oM />
tho pri r t tho p rim art
riz ma aB riz av aB
ed <TextBlock
ve
ra
arb Text="{Binding Path=CountryOfOrigin}"
ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
Grid.Row="2" /> sa om sa om
llo llo
we we
<TextBlock d! Text="{Binding Path=Strength}"d!Grid.Row="3"
/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
Th Th
is
</ListBox> is
do do
cu cu
ma m en ma me
rta t r nt
.ba b elo t a .ba be
n lon
No rbo gs No rbo gs
un sa to un sa to
au @ M a uth @ Ma
pri art pri
When youthoset riz the m ItemsSource
av aB property of this ListBox ori
ze
to a
m acollectionrta
Ba of Coffee
ed era arb ve rbo
co bs os d co r ab
objects, the data pitemplate
es s .co specifies
a . how the ListBox should p i render
es
ss each
. co
sa Coffee
.
all m all m
ow ow
object. In this example,edthe !
data template uses a simple grid layout ed and displays the
!
name of the coffee with a larger font and a contrasting background. However, you
can make your data templates as complex and sophisticated as you want.

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!

If you had to style a graphical application by setting properties on one control at a


time, the development process would quickly become laborious. It would also be
difficult to maintain your application, as you would often need to make the same
change in multiple locations. XAML enables you to define styles as reusable
Th Th
is i
do that you can apply to multiple controls. s do
resources c um c um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 32/64
10/25/2019 20483A - Programming in C# | Skillpipe

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!

Creating Reusable Resources 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!

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.

The following example shows how to create a brush as a window-level resource:


Th Th
is is
do d oc
c um um
Creating
ma
r
and
nt Using Resources
e en
tb
ma
rt
ta. be a.b elo
ba lon a ng
No rbo gs No rbo 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
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!
<Window x:Class="DataBinding.MainWindow" d!

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.

The following example shows how to reference a reusable resource in multiple


places:
Th Th
is is
do d oc
cum um
ma nt e ma en
rta rt tb
Referencing
.ba abeReusable
lon Resource 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 s sa co bs os
pie s.c . pie s.c a.
<StackPanel> s a o m sa om
llo llo
we we
d! d!
<Button Content="Click Me" Background="{StaticResource MyBrush}"
/>
<TextBlock Text="Foreground" Foreground="{StaticResource
MyBrush}" />
<TextBlock Text="Background" Background="{StaticResource
Th Th
is is
do
MyBrush}" /> d oc
cu um
ma me ma en
rta nt t bMyBrush}" /> rt
<Ellipse
.ba be Height="50" Fill="{StaticResource
a.b elo
lon a ng
No rbo gs No rbo st
u
</StackPanel>
na s a t o u na s a oM
u @ Ma u @
tho p rim rta p a 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
we
If you need to create several
d! reusable resources, it can be usefulweto d! create your
resources in a separate resource dictionary file. A resource dictionary is a XAML file
with a top-level element of ResourceDictionary. You can add reusable resources
within the ResourceDictionary element in the same way that you would add them to
a Window.Resources element.
Th Th
is is
do d oc
cum um
ma e nt en ma
Note: tfrom
ba You
be can create a WPF Resource Dictionary
lon the Add New Item
r ta. a.b be rt
lon a
No r bo gs No r bo gs
menu
un
au
in
sa Visual
@ to Studio.
M un
a
sa
@ 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
llo llo
In most cases, you make we we your application
d! a resource dictionary available for use in d!
by referencing it in the application-scoped App.xaml file. The following example
shows how to reference a resource dictionary in the App.xaml file:

Referencing a Resource Dictionary


Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 35/64
10/25/2019 20483A - Programming in C# | Skillpipe

<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

example, the Window.Resources collection or a resource dictionary).

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.

The following example shows how to apply a style to a control:

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:

Using a Property Trigger

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!

To apply an animation to an object, you need to wrap your animation in a Storyboard


element. The Storyboard element enables you to specify the object and the property
you want to animate. It does this by providing the TargetName and TargetProperty
attached properties, which you can set on child animation elements.
Th Th
is is
do d oc
cum um
ma e nt ma en
rta rt tb
3. Create
.ba a btrigger.
elo
n
a.b elo
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 b s os
pie s.c . pie s.c a.
sa om sa om
To trigger your animation llo
we
in response to a property change, youlloneed we
to wrap your
d! d!
storyboard in an EventTrigger element. The EventTrigger element specifies the
control event that will trigger the animation. In the EventTrigger element, you can
use a BeginStoryboard element to launch the animation.

You Tcan add an EventTrigger element containing


T your storyboards and animations
his his
do do
to the Triggers
c um collection of a Style element, or you ccan
um add it directly to the
ma en ma en
rta tb r ta. tb
Triggers.bcollection
a r
elo
n
of an individual control. b 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
riz m av a Ba o riz m av aB
ed era r e e arb
The following example co
pie bsshows b os how to use an animation to crotate
a.
d
op
r aand
bs expand
os
a.
an
s.c ies s .co
sa om all m
image when the userllowclicks on it: ow
ed ed
! !

Creating an Animation Effect

<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

<Setter Property="Height" Value="200" />


<Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
<Setter Property="RenderTransform">
<Setter.Value>

<RotateTransform Angle="0" />

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

Lab: Customizing Student Photographs and Styling the


Application

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!

• Use styles and animations.

Estimated Time: 60 minutes


Th Th
is is
do oc d
c um um
ma ent ma en
• Virtual
rta Machine:
.ba be
lon
20483A-SEA-DEV11-09, MSL-TMG1
r ta.
ba
tb
elo
No rbo gs No r bo ng
un sa to un s st
@ Ma a @ oM
au p au pri art
• User Name:t ho
riz Student
r im
av
rta
Ba
tho
riz m av aB
ed era rbo ed era arb
co b ss sa co bs os
pie . . pie s.c a.
sa c om sa om
• Password: Pa$$w0rd llo
we
llo
we
d! d!

Exercise 1: Customizing the Appearance of Student Photographs

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.

The main tasks for this exercise are as follows:


Th Th
is is
do do
1. Create
ma
uc
m en
the StudentPhoto user control ma
cu
me
rta t r nt
.ba belo t a .ba be
n lon
No rbo gs No rbo gs
2. Display
un
au
sathe students’
@ to
M photographs in the StudentsPage
un
a
sa
@ view
to
Ma
tho pri art uth pri rta
riz m av aB ori m a Ba
ed era arb ze ve rbo
c b os d c r ab
3. Enable the puser o
ies tos.cdisplay. the details for a student
s a o pie s s.c sa
.
all om sa om
ow llo
ed we
! d!
4. Add a Remove button to the StudentsPage view

5. Display all students for the current teacher

6. Build and test the application


Th Th
is is
do d oc
cum um
ma ent ma en
rta be the StudentPhoto user control a. rt tb
Task 1: Create
.ba
r
lon ba
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
riz m av a Ba o riz m av aB
ed era rbo e d e r arb
co bs sa co ab os
1. Start the MSL-TMG1 s
p ies s .co virtual . machine if it is not already ierunning. p
s
s.co a.
all m all m
ow ow
ed ed
! !
2. Start the 20483A-SEA-DEV11-09 virtual machine and log on as Student with
the password Pa$$w0rd.

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

4. Set the following projects to start without debugging at startup:

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!

<TextBlock Text="{Binding Name}" Style="{StaticResource


LabelCenter}"
FontSize="16" VerticalAlignment="Bottom" Margin="8,0,14.583,8"
/>
Th Th
is </Grid> is
do d oc
cum um
ma en ma en
</UserControl>
rta
.ba
t be a.b rt tb
elo
lon a ng
No rbo gs No rbo 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
ed era a rbo ed era arb
co b s s c o b s os
7. In StudentPhoto.xaml.cs,
pie
sa
s.c
om
a . remove the existing usingpdirectives ies s.c and
o
a. add using
llo a l m
directives to bring we the following namespaces into scope: lowe
d! d!

• System.Windows.Controls

• System.Windows.Media.Animation

8. ThChange the namespace of the control to Grades.WPF.


is
Th
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 2: Display e d c therastudents’ rbo photographs in the e
StudentsPage
dc e rab view
rbo
op b ss sa op ss sa
ies .co . ies .co .
all m all m
ow ow
ed ed
! !
1. In the Views folder, in StudentsPage.xaml, in the ScrollViewer element,
create an ItemsControl control named list. You will use this control to display
the list of photographs for students in a class. In a later step, you will use data
binding to associate the list of students with this control.
Th Th
is is
2. In dthe
oc ItemsControl
um
do
element, add an ItemsPanel
cu control that will be used to
m
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 45/64
10/25/2019 20483A - Programming in C# | Skillpipe

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
! !

4. In the ItemTemplate element, define a DataTemplate that displays the


StudentPhoto control in a grid with a Margin property of 8 points.

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

Note: Remember that the StudentPhoto control is defined in the


Grades.WPF namespace. The XAML markup for the StudentsPage
Th Th
is is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 46/64
10/25/2019 20483A - Programming in C# | Skillpipe

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"

You should refer to the StudentPhoto control as local:StudentPhoto.


Th Th
is is
do d oc
um c um
The
ma completed
en markup should look like the following:
ma en
rta tb rta tb
.ba elo .ba elo
No rbo ng No rbo ng
un sa st un sa st
@ oM @ oM
au p art au p art
tho rim aB tho rim aB
r
<ItemsControl i z a riz av
ed v erax:Name="list">
arb ed era arb
co bs os co bs os
pie s.c a. pie s.c a.
sa
<ItemsControl.ItemsPanel> om sa om
llo llo
we we
... d! d!

</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.

2. In the Student_Click method, raise the StudentSelected event.

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:

private void Student_Click(object sender, MouseButtonEventArgs e)


Th Th
{ is
do
is
d
c oc
um me u
ma e ma
rtaif (StudentSelected
nt
belo
!= null) r t a
nt
be
.ba .ba lon
No r b n g N r b gs
u
StudentSelected(sender,
o sa s to new StudentEventArgs((sender
o u o sa to as
na @ Ma na @ Ma
tho urim rta p uth pri rta
StudentPhoto).DataContext
riz av Ba ori ma Ba
e e r ze ve rbo
dc rab bo dc rab
op ss sa op s s.c sa
as LocalStudent));
ies .co . ies om
.
all m all
ow ow
} ed ed
! !

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:

<local:StudentPhoto Height="150" Width="127.5" Cursor="Hand"


Th Th
iMouseLeftButtonUp="Student_Click"/>
sd is
oc do
um cu
m e m me
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 48/64
10/25/2019 20483A - Programming in C# | Skillpipe

Task 4: Add a Remove button to the StudentsPage view

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

• ToolTipService.Tooltip: Remove from class

• 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:

<Grid VerticalAlignment="Top" HorizontalAlignment="Right"


Background="#00000000"
Opacity="0.3" Width="20" Height="20"
Th Th
iToolTipService.ToolTip="Remove
sd from is class"
oc do
um cu
maTag="{Binding}"
en m me
rta tb > a r nt
.ba elo t a.b be
ng Source="../Images/delete.png" a lon
No rb<Image
os st N ou r b gs
os Stretch="Uniform" />
un a @ o n a @ to
au pri M art au pri Ma
t
</Grid>h ori ma aB t h 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
! !
4. In StudentsPage.xaml.cs, in the Events region, add a private method named
RemoveStudent_MouseEnter that takes an object and a MouseEventArgs
parameter and returns void.

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
!

private void RemoveStudent_MouseEnter(object sender,


MouseEventArgs e)
{
Th Th
is Grid grid = (Grid)sender; is
do d oc
cum um
m e m e
https://skillpipe.com/#/reader/book/b449cdd9-afbb-4104-8a9b-297d55063872 50/64
10/25/2019 20483A - Programming in C# | Skillpipe

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

You might also like