of 88
8/12/2019 EntLib DevGuide PDC Preview
1/88
8/12/2019 EntLib DevGuide PDC Preview
2/88
COMMUNITY PREVIEW LICENSE
Thisdocumentisapreliminaryreleasethatmaybechangedsubstantiallypriortofinalcommercial
release.This
document
is
provided
for
informational
purposes
only
and
Microsoft
makes
no
warranties,
eitherexpressorimplied,inthisdocument. Informationinthisdocument,includingURLandother
InternetWebsitereferences,issubjecttochangewithoutnotice. Theentireriskoftheuseorthe
resultsfromtheuseofthisdocumentremainswiththeuser. Unlessotherwisenoted,thecompanies,
organizations,products,domainnames,emailaddresses,logos,people,places,andeventsdepictedin
exampleshereinarefictitious. Noassociationwithanyrealcompany,organization,product,domain
name,emailaddress,logo,person,place,oreventisintendedorshouldbeinferred. Complyingwithall
applicablecopyrightlawsistheresponsibilityoftheuser. Withoutlimitingtherightsundercopyright,
nopartofthisdocumentmaybereproduced,storedinorintroducedintoaretrievalsystem,or
transmittedinanyformorbyanymeans(electronic,mechanical,photocopying,recording,or
otherwise),or
for
any
purpose,
without
the
express
written
permission
of
Microsoft
Corporation.
Microsoftmayhavepatents,patentapplications,trademarks,copyrights,orotherintellectualproperty
rightscoveringsubjectmatterinthisdocument. Exceptasexpresslyprovidedinanywrittenlicense
agreementfromMicrosoft,thefurnishingofthisdocumentdoesnotgiveyouanylicensetothese
patents,trademarks,copyrights,orotherintellectualproperty.
2009MicrosoftCorporation. Allrightsreserved.
MicrosoftaretrademarksoftheMicrosoftgroupofcompanies.
Allothertrademarksarepropertyoftheirrespectiveowners.
8/12/2019 EntLib DevGuide PDC Preview
3/88
Table of Contents
Preface 1
Chapter1 MeettheLibrarian 8
Chapter2 MuchADOaboutDataAccess 30
Chapter3 ErrorManagementMadeExceptionallyEasy 63 includedinpreview
Chapter4 AsEasyAsFallingOffaLog
Chapter5 ACacheAdvanceforyourApplications
Chapter6 BanishingValidationComplication
Chapter7 RelievingCryptographyComplexity
Chapter8 AnAuthenticApproachtoTokenIdentity
8/12/2019 EntLib DevGuide PDC Preview
4/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 4
Preface
AboutThisGuide
Themostobviousinitialquestions,asyouidlypickupabookinyourlocalbookstoreorbrowsethe
seeminglyendlesscollectionavailablefromyourfavoriteWebsite,is"Whatdoesthisbookactually
cover?","WhatwillIlearnfromit?","Isthecontentlikelytobeinterestingandusefultome?",andof
course"Isitactuallyanygood?".We'llhaveagoatansweringthefirstthreeofthesequestionshere.
Thefinalquestionisonethatonlyyoucananswer.Andwewouldbepleasedtohearyouropinion
throughourcommunityWebsiteathttp://entlib.codeplex.com/.
WhatDoesThisGuideCover?
Asyoucanprobablytellfromthetitle,thisguideconcentratesonhowyoucangetstartedwith
EnterpriseLibrary.
It
will
help
you
to
learn
how
to
use
Enterprise
Library
in
your
applications
to
manage
yourcrosscuttingconcerns,simplifyandspeedupyourdevelopmentcycle,andtakeadvantageof
provenpractices.EnterpriseLibraryisacollectionofprewrittencodecomponentsthathavebeen
developedfinetunedovermanyyears.Youcanusethemofthebox,modifythemasrequired,
distributethemwithyourapplications,andevenuseEnterpriseLibraryasalearningresource.It
includesthesourcecodethatdemonstrates.NETprogrammingtechniques,andtheuseofcommon
designpatternsthatcanimprovethedesignandmaintainabilityofyourapplications.Bytheway,ifyou
arenotfamiliarwiththeterm"crosscuttingconcerns",don'tworrywe'llexplainitaswegoalong.
EnterpriseLibraryisanextensivecollection,withagreatmany"movingparts".Forbeginners,itcan
seem
overwhelming
and
confusing;
and
knowing
how
to
best
take
advantage
of
it
is
not
completely
intuitive.Therefore,inthisguide,we'llhelpyoutounderstandwhatEnterpriseLibraryis,whatit
contains,andhowyoushouldgetstartedusingit.YouwillseehoweasyitistoaddEnterpriseLibraryto
yourapplications,configureittodoexactlywhatyouneed,andthenbenefitfromthesimpletouseyet
extremelycompellingopportunitiesitprovidesforwritinglesscodethatachievesmore.
ThefirstchapterofthisguidediscussesEnterpriseLibraryingeneral,andprovidesdetailsofthe
individualpartssothatyoubecomefamiliarwiththeframeworkasawhole.Thisincludesunderstanding
thebasicprinciplesofeachoftheapplicationblocksinEnterpriseLibrary,andhowyoucanchoose
exactlywhichblocksandfeaturesyourequire.Thischapteralsodiscussesthefundamentalsofusingthe
blocks;suchashowyouconfigurethem,howyouinstantiatethecomponents,andhowyouusethese
componentsin
your
code.
Theremainingsevenchaptersdiscussindetailtheapplicationblocksthatprovidethebasiccrosscutting
functionalitysuchasdataaccess,caching,logging,andexceptionhandling.Thesechaptersexplainthe
conceptsthatdrovedevelopmentoftheblocks,thekindsoftasksthattheycanaccomplish,andtheway
thattheyhelpyoutoimplementmanywellknowndesignpatterns.And,ofcourse,theyexplainby
wayofcodeextractsandsimpleexampleapplicationshowyouactuallyusetheblocksinyour
8/12/2019 EntLib DevGuide PDC Preview
5/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 5
applications.Afteryoureadeachchapter,youshouldbefamiliarwiththeblockandabletouseitto
performarangeoffunctionsquicklyandeasily;inbothnewandexistingapplications.
YoucanalsodownloadandworkthroughtheHandsOnLabsforEnterpriseLibrary,whichareavailable
fromhttp://go.microsoft.com/fwlink/?LinkId=177393.
WhatThis
Guide
Does
Not
Cover
TheaimofthisguideistohelpyoulearnhowtobenefitfromthecapabilitiesofEnterpriseLibrary.It
doesnotdescribethecommondesignpatternsindepth,orattempttoteachyouaboutapplication
architectureingeneral.Instead,itconcentratesongettingyouuptospeedquicklyandwiththe
minimumfusstouseEnterpriseLibrarytomanageyourcrosscuttingconcerns.
Oneofthecoretenetsofmodernapplicationdesignisreducingthecouplingordependenciesbetween
componentsandobjects,andEnterpriseLibraryinversion5.0achievesthisthroughuseofthe
DependencyInjection(DI)designpattern.However,youdonothavetobeaDIexperttouseEnterprise
Library;allofthecomplexityismanagedinternallybythecoremechanismswithintheframework.While
wedo
show
and
explain
the
basic
usage
of
DI
in
terms
of
using
Enterprise
Library,
this
is
not
a
fundamentalfeatureofthisguide.Instead,wediscussDIindetail,andshowhowyoucanapplythisand
similardesignpatterns,inaseparateguidecalled"WhatevertheUnityBookIsCalled".
EnterpriseLibraryisdesignedtobeextensible.Youcanachievethissimplybywritingcustomplugin
providers,bymodifyingthecorecodeofthelibrary,orevenbycreatingentirelynewblocks.Inthis
guide,weprovidepointerstohowyoucandothis,andexplainthekindsofprovidersthatyoumaybe
temptedtocreate,butitisnotatopicthatwecoverindepth.Thesetopicsarediscussedmorefullyin
thedocumentationinstalledwithEnterpriseLibraryandavailableonlineat
http://msdn.microsoft.com/entlib,andinthemanyotherresourcesavailablefromourcommunityWeb
site
at
http://www.codeplex.com/entlib.
HowWillThisGuideHelpYou?
IfyoubuildapplicationsthatrunontheMicrosoft.NETFramework,whethertheyareenterpriselevel
businessapplicationsorevenrelativelymodestWindowsForms,WPF,WCF,orASP.NETapplications,
youcanbenefitfromconsideringEnterpriseLibrary.Thisguidewillhelpyoutoquicklygraspwhat
EnterpriseLibrarycandoforyou,seeexamplesthatshowitinaction,andmakeiteasierforyoutostart
experimentingwithEnterpriseLibrary.
Thesampleapplicationsareeasytoassimilate,fullycommented,andcontaincodethatdemonstratesall
ofthemainfeatures.Youcancopythiscodedirectlyintoyourapplicationsifyouwish,orjustuseitasa
guidewhenyouneedtoimplementthecommonfunctionalityitprovides.ThesamplesareConsole
basedapplicationsthatcontainseparateproceduresforeachfunctiontheydemonstrate.
Finally,andperhapsthemostimportantfeatureofthisguide,isthatitwillhopefullyallayanyfearsyou
mayhaveaboutusing"otherpeople'scode"inyourapplications.Byunderstandinghowyoucanselect
exactlywhichfeaturesyouneed,andinstalltheminimumrequirementstoimplementthesefeatures,
youwillseehowwhatmightseemlikeahugeandcomplicatedframeworkisactuallyareallyuseful
8/12/2019 EntLib DevGuide PDC Preview
6/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 6
setofindividualcomponentsandfeaturesfromwhichyoucanpickandchoose.Acandystoreforthe
architectanddeveloper.
WhatDoYouNeedtoGetStarted?
Theprerequisitesforusingthisguidearerelativelysimple.You'llneedtoberelativelyexperiencedin
eitherthe
C#
or
Visual
Basic
language,
and
understand
general
object
oriented
programming
techniques.Ifyouwanttoruntheexamples,youmusthaveatleastversion3.5ofthe.NETFramework
withServicePack1installed.Tobeabletoviewanddebugthesamplesourcecode,youwillneedVisual
Studio2008(anyversion)orhigher.However,ifyouwanttobeabletoviewandrunthesourcecode
andunittestsforEnterpriseLibraryitself,youwillneedatleastVisualStudio2008TeamSuiteEdition.
Otherthanthat,allyourequireissomesparetimetositandread,andtoplaywiththeexample
programs.Hopefullyyouwillfindthecontentsinteresting(andperhapsevenentertaining),aswellasa
usefulsourceforlearningaboutEnterpriseLibrary.
The Team Who Brought You This Guide
PrimaryAuthor
AlexHomer
Contributors
NicholasBotto,GrigoriMelnik,EricRenaud,FernandoSimonazzi,ChrisTavares
EnterpriseLibrary5.0Team
Product/ProgramManagement
GrigoriMelnik
Architecture/Development
BobBrumfield,OlafConijn,FernandoSimonazzi,ChrisTavares
Testing
NicolasBotto,CarlosFarre,MeenakshiKrishnamoorthi,ManiKrishnaswami,MasashiNarumoto,Erik
Renaud,LavanyaSelvaraj,RohitSharma,MagdeleneSona,SachinTah,FranoisTanguay,Ravindra
Varman
8/12/2019 EntLib DevGuide PDC Preview
7/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 7
UserExperience
HeidiAdkisson,JenAmsterlaw,BradCunningham,KellyFranznick,DamonvanVessem
Documentation
AlexHomer,DennisDeWitt,LennyFenster
EditingandRelease
RichardBurte,RoAnnCorbisier,NellyDelgado,TracyEmory
patterns&practicesLeadershipTeam
MohammadAlSabt,JohnDeVadoss,SteveElston,DavidHill,AjoyKrishnamoorthy,AdeMiller,Don
Smith
AdvisoryCouncil
[Memberstobelistedinthefinalversionwithpermission]
Community
Attendeesatpatterns&practicessummits,PDC,TechReadyandTechEdconferenceswhoprovided
informalfeedbackonthis.
EnterpriseLibraryusers whocommentedonthisgudieonCodeplex.
Thankyou!
8/12/2019 EntLib DevGuide PDC Preview
8/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 8
Chapter 1 Meet the Librarian
Introduction............................................................................................................................................ 9
WhatYouGetwithEnterpriseLibrary.................................................................................................... 9
ThingsYouCanDowithEnterpriseLibrary........................................................................................... 10
WhyShouldIUseEnterpriseLibrary?................................................................................................... 11
SomeFundamentalsofEnterpriseLibrary............................................................................................ 12
InstallingEnterpriseLibrary.............................................................................................................. 12
AssembliesandReferences.............................................................................................................. 12
Signedor
Unsigned,
GAC
or
Bin?
.............................................................................................
13
UsingImports........................................................................................................................... 14
InterblockDependencies................................................................................................................. 15
ConfiguringEnterpriseLibrary.............................................................................................................. 16
EncryptingConfigurationSections.................................................................................................... 17
InstantiatingEnterpriseLibraryObjects............................................................................................... 19
HowEnterpriseLibraryUsesDependencyInjection......................................................................... 20
ResolvingInstancesofEnterpriseLibraryObjects............................................................................ 21
InjectingInstancesofEnterpriseLibraryObjectsintoYourApplication.......................................... 21
InitializingtheContainer.......................................................................................................... 22
ResolvingInstancesofObjectsDirectly................................................................................... 22
InjectingInstancesofObjects.................................................................................................. 23
ConstructorInjection............................................................................................................... 26
Property(Setter)Injection....................................................................................................... 26
MethodCallInjection............................................................................................................... 27
Summary...............................................................................................................................................
28
8/12/2019 EntLib DevGuide PDC Preview
9/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 9
1.1 Introduction
BeforewebeginourexplorationofMicrosoftEnterpriseLibrary,andthewondrousrangeofcapabilities
andopportunitiesitencompasses,youneedtomeettheLibrarian.SometimeswecallhimTom,
sometimeswecallhimChris,andsometimeswecallhimGrigori.But,despitethissomewhatunnerving
namevariability,
hein
collaboration
with
an
advisory
board
of
experts
from
the
industry
and
other
internalMicrosoftproductgroups,andaconsiderablenumberofothercommunitycontributorsisthe
guardianandprotectoroftheMicrosoftpatterns&practicesEnterpriseLibrary.
Sinceitsinceptionasadisparatecollectionofindividualapplicationblocks,theLibrarianhasguided,
prodded,inspired,andencouragedhisteamofelvestotransformitintothecomprehensive,powerful,
easytouse,andprovenlibraryofcodethatcanhelptominimizedesignpain,maximizedevelopment
productivity,andreducecosts.Andnow,inversion5.0,itcontainsevenmorebuiltingoodnessthatwill
hopefullymakeyourjobeasier.It'sevenpossiblethat,withthetimeandeffortyouwillsave,Enterprise
Librarycanreduceyourgolfhandicap,helpyoumastertheskislopes,letyouspendmoretimewith
yourkids,orjustmakeyouabetterperson.However,notethattheauthor,thepublisher,andtheir
employeescannot
be
held
responsible
if
you
just
end
up
watching
more
TV
or
discovering
you
actually
havealife.
Whatareapplicationblocks?Acommondefinitionweuseis"reusablesoftwarecomponentsdesigned
toassistdeveloperswithcommonenterprisedevelopmentchallenges".Applicationblockshelpaddress
thecommonproblemsthatdevelopersfacefromonelineofbusinessprojecttothenext.Theirdesign
encapsulatestheMicrosoftrecommendedpracticesfor.NETapplications;anddeveloperscanaddthem
to.NETapplicationsquicklyandeasily.
1.2 WhatYouGetwithEnterpriseLibrary
EnterpriseLibraryismadeupofaseriesofapplicationblocks,eachaimedatmanagingspecific
crosscuttingconcerns.Incasethiswordisunfamiliar,crosscuttingconcernsarethoseannoyingtasks
thatyouneedtoaccomplishinseveralplacesinyourapplication,andwherethereisariskthatyoumay
endupimplementingslightlydifferentspecificsolutionsateachlocation(orjustforgettingit
altogether).SomegoodexamplesofthisarewritingentriestoasystemlogfileorWindowsEventLog,
cachingdata,andvalidatinguserinput.Whilethereareseveralapproachestomanagingyour
crosscuttingconcerns,theEnterpriseLibraryapplicationblocksmakeitawholeloteasierbyproviding
genericand
configurable
functionality
that
you
can
centralize
and
manage.
Aswellastheapplicationblocks,EnterpriseLibrarycontainsconfigurationtools,plusasetofcore
functionsthatmanagetasksapplicabletoalloftheblocks.Someofthesefunctionsareexposedand
availableforyoutouseinyourownapplicationsforexample,routinesforhandlingconfigurationand
serialization.
8/12/2019 EntLib DevGuide PDC Preview
10/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 10
And,onthegroundsthatyouneedtolearnhowtouseanynewtoolthatismorecomplicatedthana
hammerorscrewdriver,EnterpriseLibraryincludesarangeofsampleapplications,descriptionsofkey
scenariosforeachblock,handsonlabs,andcomprehensivereferencedocumentation.Youevengetall
ofthesourcecode,andtheunitteststhattheteamcreatedwhenbuildingeachblock(theteamfollows
testdrivendesignpracticesbywritingtestsbeforewritingcode).Soyoucanunderstandhowitworks,
seehow
the
team
uses
best
practices
to
create
it,
and
then
modify
it
ifyou
want
it
to
do
something
different.
1.3 ThingsYouCanDowithEnterpriseLibrary
Ifyoulookattheinstalleddocumentation,you'llseethatEnterpriseLibrarytodayactuallycontainsnine
applicationblocks.However,thereareactuallyonlysevenblocksthat"dostuff"thesearereferredto
asfunctionalblocks.Theothertwoareconcernedwith"wiringupstuff"(the"wiringblocks").What
thisreallymeansisthattherearesevenblocksthattargetspecificcrosscuttingconcernssuchas
caching,logging,dataaccess,andvalidation.Theothertwo,theUnityDependencyInjectionMechanism
andthePolicyInjectionApplicationBlock,aredesignedtohelpyouimplementmorelooselycoupled,
testable,andmaintainablesystems.
OK,soEnterpriseLibraryreliesonthefeaturesofUnitytocreateobjectswithintheblocks,butthatjust
showshowgenerallyusefulUnityis.Inthisbook,we'llbeconcentratingonthesevenfunctionalblocks.
IfyouwanttoknowmoreabouthowyoucanuseUnityandthePolicyInjectionApplicationBlock,look
outforoursistertitle"WhatevertheUnityBookIsCalled".Thefollowinglistdescribesthecrosscutting
scenariosyou'lllearnaboutinthisbook:
Caching.TheCachingApplicationBlockletsyouincorporatealocalcacheinyourapplications
thatusesaninmemorycacheand,optionally,adatabaseorisolatedstoragebackingstore.The
blockprovidesallthefunctionalityneededtoretrieve,add,andremovecacheddata,and
supportsconfigurableexpirationandscavengingpolicies.Youcanalsoextenditbycreating
yourownpluggableprovidersorusingthirdpartyproviders;forexampletosupportdistributed
cachingandotherfeatures.Cachingcangiveconsiderableimprovementsinperformanceand
efficiencyinmanyapplicationscenarios.
CredentialManagement.TheSecurityApplicationBlockletsyoueasilyimplementcommon
authorizationrelatedfunctionality,suchascachinguser'sauthorizationandauthenticationdata
andintegratingwiththeMicrosoft.NETFrameworksecurityfeatures.
DataAccess.TheDataAccessApplicationBlocksimplifiesmanycommondataaccesstaskssuch
asreading
data
for
display,
passing
data
through
application
layers,
and
submitting
changed
databacktothedatabasesystem.Itincludessupportforbothstoredproceduresandinline
SQL,canexposethedataasasequenceofobjectsforclientsidequerying,andprovidesaccess
tothemostoftenusedfeaturesofADO.NETinsimpletouseclasses.
8/12/2019 EntLib DevGuide PDC Preview
11/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 11
Encryption.TheCryptographyApplicationBlockmakesiteasytoincorporatecryptographic
functionalitysuchasencryptinginformation,creatingahashfromdata,andcomparinghash
valuestoverifythatdatahasnotbeenaltered.
ExceptionHandling.TheExceptionHandlingApplicationBlockletsyouquicklyandeasilydesign
and
implement
a
consistent
strategy
for
managing
exceptions
that
occur
in
various
architectural
layersofyourapplication.Itcanlogexceptioninformation,hidesensitiveinformationby
replacingtheoriginalexceptionwithanotherexception,andmaintaincontextualinformation
foranexceptionbywrappingtheoriginalexceptioninsideanotherexception.
Logging.TheLoggingApplicationBlocksimplifiestheimplementationofcommonlogging
functionssuchaswritinginformationtotheWindowsEventLog,anemailmessage,adatabase,
WindowsMessageQueuing,atextfile,aWMIevent,oracustomlocation.
Validation.TheValidationApplicationBlockprovidesarangeoffeaturesforimplementing
structuredandeasytomaintainvalidationmechanismsusingattributesandrulesets,and
integratingwithmosttypesofapplicationinterfacetechnologies.
1.4 WhyShouldIUseEnterpriseLibrary?
Asyoucanseefromtheprevioussection,EnterpriseLibraryprovidesacomprehensivesetoffeatures
thatcanhelpyoutomanageyourcrosscuttingconcernsthoughareusablesetofcomponentsandcore
functionality.Ofcourse,likemanydevelopers,youmaysufferfromthewellknownNIH("NotInvented
Here")Syndrome.But,seriously,isntitabouttimethateverydeveloperonyourteamstoppedwriting
hisorherownloggingframework?It'sacommonlyacceptedfactthattheuseofstandardandproven
codelibrariesandcomponentscansaveondevelopmenttimeandcost,useofprecioustestresources,
andmaintenanceoveralleffort.InthewordsoftheLibrarian,Thesedaysyoucannotaffordnotto
reuse.
Andit'snotasthoughEnterpriseLibraryissomenewkidontheblock,whomightmorphintosomething
completelydifferentnextmonth.EnterpriseLibraryasaconcepthasbeenaroundformanyyears,and
haspassedthroughfivefullreleasesofthelibraryaswellasintermediateincrementalreleases.
EnterpriseLibrarydoesevolvealongwiththecapabilitiesofthe.NETFramework.Asthe.NET
Frameworkchangesovertime,somefeaturesthatwerepartofEnterpriseLibraryaresubsumedinto
thecore,whileEnterpriseLibrarychangestotakeadvantageofthenewfeaturesavailableinboththe
.NETFrameworkandtheunderlyingsystem.Examplesarenewprogramminglanguagecapabilities,and
improvedperformanceandcapabilitiesinthe.NETconfigurationandIOmechanisms.Yet,evenin
version5.0,thevastmajorityofthecodeisentirelybackwardscompatiblewithapplicationswrittento
useEnterpriseLibrary2.0.
YoucanalsouseEnterpriseLibraryaslearningmaterialnotonlytoimplementdesignpatternsinyour
application,butalsotolearnhowthedevelopmentteamappliespatternswhenwritingcode.Enterprise
Libraryembodiesmanydesignpatterns,anddemonstratesbestpracticearchitecturalandcoding
8/12/2019 EntLib DevGuide PDC Preview
12/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 12
techniques.Thesourcecodefortheentirelibraryisprovided,andsoyoucanexplorethe
implementationsandreusethetechniquesinyourownapplications.
And,finally,itisfree!Orrather,itisdistributedundertheMicrosoftPublicLicensethatgrantsyoua
royaltyfreelicensetobuildderivativeworks,anddistributethemfreeorevensellthem.Youmust
retaintheattributionheadersinthesourcefiles,butyoucanmodifythecodeandincludeyourown
customextensions.DoyouneedanyotherreasonstotryEnterpriseLibrary?
You'llnoticethat,eventhoughwedidn'tput"Don'tPanic"inlargefriendlylettersonthecover,this
bookdoestakealittletimetosettledownintoamoreusualdocumentationstyleandstartprovide
usefulinformation.However,youcanbesurethatfromhereoninyou'llfindawholerangeof
guidanceandexamplesthatwillhelpyoumasterEnterpriseLibraryquicklyandeasily.
1.5 SomeFundamentalsofEnterpriseLibrary
BeforewediveintoourtouroftheapplicationblocksandfeaturesofEnterpriseLibrary,youneedto
graspsomefundamentals.Inthischapter,theLibrarianwillhelpyoutoexploretopicssuchasthe
contentsofthelibrary,thebroadaimsofthelibraryandeachapplicationblock,howyouinstalland
deploythelibrary,andhowyouperforminitialconfiguration.Afterthat,you'llbefreetoskiptoanyof
theotherchaptersandlearnmoreaboutthewaysthateachblockhelpsyoutosimplifyyourcodeand
manageyourcrosscuttingconcerns.Formoreinformationaboutthetopicscoveredhere,seethe
productdocumentationinstalledwithEnterpriseLibrary,ortheonlinedocumentationavailableat
http://msdn.microsoft.com/entlib/.
1.5.1 InstallingEnterpriseLibrary
Thefirst
step
is
to
obtain
and
install
Enterprise
Library.
You
can
download
the
current
version
from
http://msdn.microsoft.com/entlib/.SimplyruntheMicrosoftInstaller(MSI)packagetobeginthe
installation.Ifyouwanttoexaminethesourcecode,andperhapsevenmodifyittosuityourown
requirements,besuretoselecttheoptiontoinstallthesourcecodewhenyouruntheinstaller.It'salso
agoodideatoselecttheoptiontohavetheinstallercompilethelibraryforyousothatyouarereadyto
startusingitstraightaway.
Aftertheinstallationiscomplete,youwillseeaStartmenuentrycontaininglinkstotheEnterprise
Librarytools,sourcecode,anddocumentation.Thetoolsincludebatchfilesthatinstallinstrumentation,
databasefiles,andothersettingsforthesamples.Therearealsobatchfilesthatyoucanusetocompile
theentirelibrarysourcecode,andtocopyalltheassembliestothebinfolderinthesourcecodefolders.
1.5.2AssembliesandReferences
EnterpriseLibraryisa"pickandmix"candystore,whereyoupickjustthefeaturesyouwanttouseand
simplydisregardtherest.Ofcourse,beforeyoucanchooseyourfavoritecandiesfromthetempting
displaysinthecandystore,youneedtofindapaperbagtoholdthem.Youcanthinkofthisasa
8/12/2019 EntLib DevGuide PDC Preview
13/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 13
prerequisitefor"pickingandmixing",andabasicfeaturethatyouwilluseeverytimeirrespectiveof
whetheryouchoosegummybears,chocolatecoveredhazelnuts,ormintimperials.
Likewise,withEnterpriseLibrary,thereareprerequisitesandbasicfeatures.Themainprerequisite
beforeyoustartdevelopmentistoinstallthebinariesandsupportfilesontoyourmachine.Thebasic
featuresthatyouneedeverytimeyouuseEnterpriseLibraryarethecoreassembliesthatimplement
accesstoconfiguration,objectcreation,andancillarycommonfeatures.
It'snotuncommon,whenpeoplefirstlookatEnterpriseLibrary,toseealookofmildpanicspread
acrosstheirfaces.Yes,therearealotofassembliesover100inallbutremember:
Youonlyneedtousethosedirectlyconnectedwithyourownscenario.
Severalarerequiredforonlyveryspecialistsituations.
Manyareonlyforusebytheconfigurationtools,andyouneverusetheseassembliesinyour
applications.
Theyare
mostly
less
than
100
KB
in
size;
and
the
largest
of
all
is
less
than
300
KB.
Inmostapplications,thetotalsizeofalltheassembliesyouwillusewillbelessthan2MB.
ThefiveassembliesyoumustaddtoanyapplicationthatusesEnterpriseLibraryarethecommon(core)
assembly,theUnitydependencyinjectionmechanism,andthecontainerservicelocationassembly:
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Configuration.dll
Microsoft.Practices.Unity.Interception.dll.
Microsoft.Practices.ServiceLocation.dll
Inadditiontotherequiredassemblies,youmustreferencetheassembliesthatimplementthe
EnterpriseLibraryfeaturesyouwilluseinyourapplication.Thereareseveralassembliesforeach
applicationblock.Generally,thesecomprisea"main"assemblythathasthesamenameastheblock
(suchasMicrosoft.Practices.EnterpriseLibrary.Caching.dll),plusadditionalassembliesthatimplement
specifichandlersorcapabilitiesfortheblock.Youonlyneedtheseadditionalassembliesifyouwantto
usethefeaturestheyadd.Forexample,inthecaseoftheCachingblock,thereareseparateassemblies
forcaching
to
adatabase
(Microsoft.Practices.EnterpriseLibrary.Caching.Database.dll)
and
encrypting
cacheddata(Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.dll).Ifyouonlycache
unencrypteddatainmemory,youdonotneedtoreferencethesetwoassemblies.
SignedorUnsigned,GACorBin?
Alloftheassembliesareprovidedasprecompiledsignedversions,whichyoucaninstallintotheGlobal
AssemblyCache(GAC)ifyouwish.However,ifyouneedtorundifferentversionsofEnterpriseLibrary
8/12/2019 EntLib DevGuide PDC Preview
14/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 14
assembliessidebyside,thismaybeproblematicandyoumayprefertolocatetheminfolderscloseto
yourapplication.
Youcanthenreferencethecompiledassembliesinyourprojects,whichautomaticallycopiesthemto
thebinfolder.InaWebapplication,youcansimplycopythemdirectlytoyourapplication'sbinfolder.
Thisapproachgivesyousimpleportabilityandeasyinstallation.
Alternatively,youcaninstallthesourcecodeforEnterpriseLibraryandusethescriptsprovidedto
compileunsignedversionsoftheassemblies.Thisisusefulifyoudecidetomodifythesourcecodeto
suityourownspecificrequirements.Youcanstrongnameandsigntheassembliesusingyourown
credentialsafterwardsifrequired.
Formoreinformationaboutsidebysideoperation,andotherdeploymentissues,seeoursister
publication"Whatevertheadministratorguideiscalled"orthedocumentationinstalledwithEnterprise
Libraryandavailableonlineathttp://msdn.microsoft.com/entlib.
UsingImports
Afteryoureferencetheappropriateassembliesinyourprojects,youwillprobablywanttoadd
statementstoyourprojectfilestosimplifyyourcodeandavoidspecifyingobjectsusingthefull
assemblyandclassnames.MostoftheEnterpriseLibraryassembliescontainseveralnamespacesto
organizethecontents.Forexample,asyoucanseethefollowingfigure,themainassemblyforthe
Loggingblock(oneofthemorecomplexblocks)containsadozensubsidiarynamespaces.Ifyouuse
classesfromthesenamespaces,suchasspecificfilters,listeners,orformatters,youmayneedtoadd
usingorImportsstatementsforthesenamespaces(dependingonyourdevelopmentcodelanguage).
8/12/2019 EntLib DevGuide PDC Preview
15/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 15
1.5.3 InterblockDependencies
EnterpriseLibraryis,asitsnamesuggest,alibraryofcodecomponentsandobjects.Toacertainextent,
thesecomponentshaveoptionaldependenciesuponeachother.Forexample,alloftheapplication
blocksrelyonfeaturesintheEnterpriseLibrarycoreassembly.Therearealsooptionalpluggable
dependencies
between
the
blocks,
such
as
the
reliance
of
the
Exception
Handling
block
on
the
Logging
blockforloggingexceptioninformation.Thefollowingtableandschematicshowthefulllistofthese
pluggabledependencies.
Application Block Dependencies
Caching Block May use the Data Access block to cache data in a database.
May use the Cryptography block to encrypt cached data.
Exception Handling Block May use the Logging block to log exception information.
May use the Data Access block to log exception information to a database.
Logging Block May use the Data Access block to log to a database.
Security Block May use the Caching block to cache credentials.
May use the Data Access block to cache credentials in a database.
May use the Cryptography block to encrypt cached credentials.
8/12/2019 EntLib DevGuide PDC Preview
16/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 16
Theconfigurationtoolswillautomaticallyaddtherequiredblocktoyourapplicationwiththedefault
configurationwhenrequired.Forexample,whenyouaddaLogginghandlertoanExceptionHandling
blockpolicy,theconfigurationtoolwilladdtheLoggingblocktotheconfigurationwiththedefault
settings.
1.6 ConfiguringEnterpriseLibrary
Oneofthebiggestchallengesforuserspriortothecombiningoftheoriginalindividualapplication
blocksintoEnterpriseLibrarywasconfiguration.Youhadtoeditthesectionsoftheapplication
configurationfilemanually,whichprovedtobeerrorproneandjustplainannoying.InEnterprise
Library,youhaveachoiceoftoolsforperformingconfiguration.Thereisastandalonetoolcalledthe
configurationeditor,whichyoucanrunatanytime.Youcanevencopyit(andtheassembliesisuses)to
amachinethatdoesnothaveEnterpriseLibraryinstalledifyoujustwanttoperformpostdeployment
configuration.The
following
figure
shows
the
configuration
console
with
all
of
the
application
blocks
coveredinthisbookinstalledintotheconfiguration.
[Awaitingimageofconfigurationconsole]
EnterpriseLibraryalsocontainsaconfigurationtoolthatintegrateswithVisualStudio.TheVisualStudio
ConfigurationEditordisplaysaverysimilarinterfacetothatshowninFigure2,butallowsyoutoedit
yourconfigurationfileswithasimplerightclickinSolutionExplorer.
Youcancreateanewapplicationconfigurationfile(suchasWeb.configorApp.config)bycreatinganew
EnterpriseLibraryconfigurationintheconfigurationconsoleandthensavingittodisk,oryouanopen
anexistingconfigurationfileandeditittoaddEnterpriseLibrarytoyourapplication.Eitherway,once
youhavetheconfigurationfileopen,thegeneraltechniqueforcreatinganewconfigurationfileand
configuringtheapplicationisasfollows:
[Allofthefollowingprocedureneedstobeupdated]
1. RightclicktherootEnterpriseLibraryConfigurationnodeintheconfigurationconsole,pointto
New,and
click
Application.
2. RightclicktheApplicationConfigurationnodethatappears,pointtoNew,andclickthename
oftheapplicationblockyouwanttoaddtoyourconfiguration.
Ifyouopenanexistingconfigurationfile,youwillseethefullpathandnameofthefileinstead
of"ApplicationConfiguration".
8/12/2019 EntLib DevGuide PDC Preview
17/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 17
3. Seetherelevantchapterlaterinthisbookfortheapplicationblockyouchosefordetailsofhow
toconfigureindividualfeaturesoftheblock.
4. Ifyouwanttousetheconfigurationconsoletoeditvaluesinthesectionofyour
configurationfile,rightclicktheApplicationConfigurationnode,pointtoNew,andclick
ApplicationSettings.ThenrightclicktheApplicationSettingsnode,pointtoNew,andclick
Setting.Youcantheneditthenameandvalueforthatsetting,andaddadditionalsettingsas
required.
Ifyouopenanexistingconfigurationfilethatalreadycontainsansection,you
willseeanyexistingsettingsandyoucaneditthemhere.
5. ToenabletheEnterpriseLibrarybuiltininstrumentation,rightclicktheApplication
Configurationnode,pointtoNew,andclickInstrumentation.Theneditthevaluesinthat
sectiontoturnontherequiredinstrumentation.Seethedocumentationinstalledwith
EnterpriseLibraryforinformationonusingtheEnterpriseLibrarybuiltininstrumentation.
6. Ifyou
want
to
store
your
configuration
in
alocation
other
than
afile,
right
click
the
Application
Configurationnode,pointtoNew,andclickConfigurationSources.Thenaddandconfigurethe
configurationsourceyouwanttouse.YoucanuseaManageableConfigurationSourceto
enforceGroupPolicysettingsandexposeconfigurationinformationthroughWMI.Seethe
documentationinstalledwithEnterpriseLibraryforinformationonusingalternative
configurationsources.
7. Ifyouwanttoconfiguredifferentsettingsforanapplicationbasedondifferentdeployment
scenariosorenvironments,rightclicktheEnvironmentsnode,pointtoNew,andclick
Environment.Thisfeatureisusefulifyouhavemultipleenvironmentsthatsharethesamebasic
configuration
but
require
different
property
settings.
It
allows
you
to
create
a
base
configurationfile(.config)andanenvironmentdeltafilethatcontainsthedifferences(.dconfig).
SeethedocumentationinstalledwithEnterpriseLibraryforinformationonconfiguringand
mergingenvironments.
8. Whenyouhavefinishedconfiguringyourapplication,saveitasafileinyourapplicationfolder
withtheappropriatename;forexample,useWeb.configforaWebapplicationandApp.config
foraWindowsFormsapplication.
Youcan,ofcourse,edittheconfigurationfilesusingatextorXMLeditor,butitislikelytobeapainful
processcomparedtousingtheconfigurationconsole.However,itmaybeausefulapproachforminor
changesto
the
configuration
when
the
application
is
running
on
aserver
where
the
configuration
consoleisnotinstalled.
1.6.1 EncryptingConfigurationSections
Probablythemostcommonapproachforstoringconfigurationinformationforyourapplicationsthat
useEnterpriseLibraryistouseanApp.configorWeb.configfilestoredintherootfolderofyour
8/12/2019 EntLib DevGuide PDC Preview
18/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 18
application.That'sfine,butyoumaybeconcernedthatanyonewhohappenstostrollpasttheserver
(eitherphysically,orvirtuallyovertheInternet)willbeabletoopenthefileandseesensitivedetails.
ThesemightincludeconnectionstringsfortheDataAccessblock,validationrulesfortheValidation
block,orconnectioninformationusedbytheLoggingblocktocommunicatewithWindowsMessage
Queuing.
While,intheory,youwillprotectyourconfigurationfilesbyphysicallysecuringtheserverandnot
leavingitrunningunderaloggedonadministratoraccount,youcan(andprobablyshould)addanextra
layerofprotectionbyencryptingsectionsofyourconfigurationfiles.Theconfigurationtoolscandothis
foryouautomaticallyallyouneedtodoissettheProtectionProviderpropertyofthespecificblockor
configurationsectionthatyouwanttoencrypt.
Youcanselectanyoftheencryptionprovidersthatareincludedinyoursystem'sMachine.configfile.
Typically,thesearetheDataProtectionConfigurationProvider,whichusesDPAPI,andthe
RsaProtectedConfigurationProvider,whichusesRSA.Thesettingsfortheseproviders,suchaswhere
keysarestored,arealsointheMachine.configfile.Youcannoteditthisfilewithaconfigurationtool;
instead,you
must
modify
it
using
atext
editor
or
an
operating
system
configuration
tool.
Asanexampleoftheeffectofthisoption,thefollowingisasimpleunencryptedconfigurationforthe
DataAccessblock.
XML
WhenyouspecifytheDataProtectionConfigurationProvideroption,theresultingconfigurationsection
lookslikethefollowing.
XML
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAc8HVTgvQB0quQI81ya0uH
...
JyEadytIBvTCbmvXefuN5MWT/T
8/12/2019 EntLib DevGuide PDC Preview
19/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 19
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAc8HVTgvQB0quQI81ya0uH
...
zBJp7SQXVsAs=
Ifyouonlyintendtodeploytheencryptedconfigurationfiletotheserverwhereyouencryptedthefile,
youcanusetheDataProtectionConfigurationProvider.However,ifyouwanttodeploytheencrypted
configurationfileonadifferentserver,oronmultipleserversinaWebfarm,youshouldusethe
RsaProtectedConfigurationProvider.YouwillneedtoexporttheRSAprivatekeythatisrequiredto
decryptthedata.Youcanthendeploytheconfigurationfileandtheexportedkeytothetargetservers,
andreimportthekeys.Formoreinformation,seeImportingandExportingProtectedConfigurationRSA
KeyContainers.
Ofcourse,thenextobviousquestionis"HowdoIdecrypttheconfiguration?"Thankfully,youdon't
needto.Youcanopenanencryptedfileintheconfigurationtoolsaslongasitwascreatedonthat
machineor
you
have
imported
the
RSA
key
file.
In
addition,
Enterprise
Library
will
be
able
to
decrypt
andreadtheconfigurationautomaticallyprovidingthatthesameconditionsapply.
1.7 InstantiatingEnterpriseLibraryObjects
Asyouwillseeineachofthefollowingchapters,theEnterpriseLibraryapplicationblocksareoptimized
foruseaslooselycoupledcomponentsinalmostanytypeofapplication.Ingeneral,youwillcreate
instancesofthecomponentsorfaadesthatyouneedtointeractwithusingtheDependencyInjection
(DI)pattern.Bydefault,EnterpriseLibraryusestheUnitydependencyinjectionmechanism(afeatureof
EnterpriseLibrary)toinjecttheobjectsyouconfigureforeachblockintoyourapplications.
Unityisalightweight,flexible,configurable,andextensibledependencyinjectioncontainerthat
supportsconstructor,propertysetter,andmethodcallinjection(aswellasinstanceandtype
interception).YoucanuseitasastandaloneDIcontainerifyouwish,althoughwedonotcoveritsuse
inthisbook.However,tobeabletoworkeffectivelywithEnterpriseLibrary,youshouldbefamiliarwith
thebasicapproachesforcreatingEnterpriselibraryobjects,andinjectingEnterpriseLibraryobjectsinto
yourapplicationclassesandcomponents.
FormoreinformationonhowyoucanuseUnitytoinjectyourowncustomobjectsandcomponents,see
oursisterpublication"Whatevertheunityguideiscalled".
Ifyou
have
used
versions
of
Enterprise
Library
prior
to
version
5.0,
you
may
be
more
familiar
with
the
previousapproachtocreatingobjectswithinyourapplicationcode.Earlierversionsgenerallysupported
orrecommendeduseofstaticfaades,ordirectinstantiationofEnterpriseLibraryobjects.Whilethese
approachesarestillsupportedinversion5.0forbackwardcompatibilitywithexistingapplications,they
arenolongertherecommendedapproachandmaybedeprecatedinfuturereleases.
8/12/2019 EntLib DevGuide PDC Preview
20/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 20
1.7.1 HowEnterpriseLibraryUsesDependencyInjection
TounderstandhowyoucancreateinstancesoftheEnterpriselibraryobjectsyouwillworkwith,it's
usefultoseehowEnterpriseLibraryusestheconfigurationyouspecifytogenerateindividualinstances
oftheclassescontainedinthelibrary.Thefollowingschematicshowstheoverallprocess,thoughyoudo
not
need
to
be
concerned
with
the
details
of
how
it
works
if
you
are
happy
to
use
Enterprise
library
in
its
defaultconfiguration.AllthishappensautomaticallyafteryouaddEnterpriseLibrarytoyourapplication.
Intheschematic,youcanseethattheconfigurationisloadedintoacontainercalledthe
EnterpriseLibraryContainer.BydefaultthisisaUnityDIcontainer,thoughyoucanuseanyotherthird
partyDI
container
as
long
as
there
is
aconfigurator
available
that
can
load
it
with
the
configuration
informationyouspecify.Fordetailsofhowtouseralternativecontainers,seethedocumentation
installedwithEnterpriseLibraryoronthecommunityWebsiteathttp://www.codeplex.com/entlib.
8/12/2019 EntLib DevGuide PDC Preview
21/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 21
1.7.2 ResolvingInstancesofEnterpriseLibraryObjects
AllyoureallyneedtoknowisthatyoucanobtainaninstanceofanyEnterpriseLibraryobject
anywhereinyourcodesimplybycallingastaticmethodofthecontainer.TheCurrentpropertyofthe
EnterpriseLibraryContainerexposesareferencetoaclasscalledtheServiceLocator.TheServiceLocator
provides
several
overloads
of
the
GetInstance
method
that
resolve
objects
through
the
container.
For
example,togetaninstanceoftheLogWriterclassthattheLoggingblockusestocreateandwritelog
messages,yousimplyusethefollowingcodetoobtainaninstanceofthedefaultobjectofthespecified
type.
//ResolvethedefaultLogWriterobjectfromthecontainer.
varwriter=EnterpriseLibraryContainer.Current.GetInstance();
NoticethatthiscodeusestypeinferencethroughthevarkeywordinC#,andomittingthevariabletype
nameinVisualBasic.Thevariablewillassumethetypereturnedbytheassignment;inthiscasethetype
LogWriter.
However,you
can
configure
more
than
one
instance
of
type
for
ablock,
such
as
multiple
Cache
ManagersfortheCachingblock;andyoucanspecifyintheconfigurationwhichoneisthedefault.Each
providerortypeyouconfigureinEnterpriseLibraryhasaname.Forexample,youmayconfigurea
CacheManagernamedIsoStorethatusesWindowsisolatedstorage,andasecondCacheManager
namedSQLDBthatusesaSQLServerdatabasetocachetheitems.Inthiscase,youspecifythenameof
theobjectyouwanttoresolvewhenyoucalltheGetInstancemethod,asshownhere.
//ResolvetheCacheManagerobjectnamedIsoStoragefromthecontainer.
varcacheMgr
=EnterpriseLibraryContainer.Current.GetInstance("IsoStore");
You
can
also
see
in
this
code
that
we
are
actually
specifying
an
interface
rather
than
the
concrete
class
wewant.However,thecontaineralwaysreturnsconcretetypes,evenifyouresolveaninterface.When
youresolveanobjectoraknowninterfaceinEnterpriseLibrary,thecontainerusestheconfiguration
loadedintoittodeterminewhichconcretetypetoreturn.
ManyEnterpriseLibraryobjectsimplementinterfacesthatdefinethedifferentconcrete
implementationsofthatinterface.TheICacheManagerinterfaceisatypicalexample.Thisallowsyouto
createyourowncustomimplementationsoftheseobjectsifyouwishbyimplementingtheinterface
andcompilingthemintothelibrary.Youcanthenspecifyyourowncustomtypeintheconfigurationfor
thelibrary.
Writingcodethatspecifiestheinterfaceinsteadofaparticularconcretetypemeansthatyoucan
changetheconfigurationtospecifyadifferentconcretetypewithoutneedingtochangeyourcode.Just
bearinmindthatnotalltypesinEnterpriseLibraryimplementaninterfacethatyoucanresolve.
1.7.3 InjectingInstancesofEnterpriseLibraryObjectsintoYourApplication
Whilethebasicapproachdescribedintheprevioussectionisfineformostapplications,youmaydecide
totakeadvantageoftheUnitydependencyinjectionmechanism(oranalternativethirdpartyDI
8/12/2019 EntLib DevGuide PDC Preview
22/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 22
mechanism)tofurtherdecouplethecomponentsandobjectsinyourapplications.Insteadofspecifically
resolvinginstancesofEnterpriseLibraryobjectsusingtheGetInstancemethod,youcanusethe
containertoresolveobjectinstancesandautomaticallyinjectthemintotheparametersofconstructors
ormethods,ortoautomaticallysetthevaluesofdependentpropertiesinyourclasses.
Infact,youmayevendecidetohavethecontainercreateandinjectinstancesoftheappropriatetypes
forallofthedependenciesdefinedinyourapplicationwhenitstartsup.Whileitmayseemtobea
strangeconcept,youcanoftendothisbyresolvingthemainformorstartupclassthroughthecontainer
(thoughthismaynotbepossiblewithallthirdpartycontainers).IfyouareusingUnity,youcansimply
defineparametersorpropertiesinyourapplicationclassesandwherenecessarymarkthemwiththe
appropriatedependencyattributes.Whenyouresolvethemainstartupclassofyourapplication,ora
classthatcontainssuchparametersandattributes,throughthecontaineritwillautomaticallycreatethe
appropriateinstancesoftheobjectsrequiredbyeachclassandinjectthemintotheparametersand
properties.
Tousethistechnique,youmustfirstinitializethecontainer.Youcanalsoholdontoareferencetothe
containerfor
use
elsewhere
in
your
code
if
required.
Then
you
use
the
Resolve
method
of
the
container
tocreateyourclassesandperformtheinjection.Thefollowingsectionsdescribethesestepsinmore
detail.However,wedonothaveroominthisguideforafullexplanationofallthetechniquesand
optionsavailable(Unityisaverypowerfulmechanismwithmanyotherfeatures),andsothefollowing
sectionsdescribethebasicsyouneedtoknowtousethisapproach.Forafullexplanationofhowyou
canuseUnityanddependencyinjectiontechniques,seeourrelatedguide"Whatevertheunityguideis
called",orthedocumentationinstalledwithEnterpriseLibrary.
InitializingtheContainer
WhenusingthedefaultUnityDImechanism,allyouneedtodoisinitializethecontaineronceonyour
application;and
then
use
it
to
resolve
(or
obtain)
instances
of
Enterprise
Library
objects
or
your
own
classesandobjects.Initializingthecontainerrequiresjustthefollowingonelineofcode.
//Createandpopulatethedefaultcontainerwithapplicationconfiguration.
varcontainer=newUnityContainer()
.AddNewExtension();
YoucanstorethecontainerinaglobalvariableinaWindowsFormsorWPFapplication,inthe
Application(orintheSessionifyouwanttostoreindividualcontainersforeachuser)ofanASP.NET
application,orinacustomextensiontotheInstanceContextofaWCFservice.Formoreinformation
abouttheseandotherapproachestostoringthecontainerreference,seethedocumentationinstalled
with
Enterprise
Library
and
available
on
MSDN.
ResolvingInstancesofObjectsDirectly
UnityexposesamethodnamedResolvethatallowsyoutoresolveobjectsthroughthecontainer
directly.Thereisarangeofoverloadsthatallowyoutospecifytheactualconcretetypeyourequireif
therearemultipleregistrationsforaninterfaceorabaseclass,andyoucanspecifythelifetimeofthe
objectitcreatesaswellaspassinganyvaluesyourequiretotheparametersofthetargetobject
8/12/2019 EntLib DevGuide PDC Preview
23/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 23
constructor.Asanexample,thefollowingcoderesolvesaCacheManagerinstancenamedIsoStore.You
canseethatthesyntaxissimilartothatoftheGetInstancemethoddiscussedearlierinthischapter.
//ResolvetheCacheManagerobjectnamedIsoStoragefromthecontainer.
varcacheMgr=container.Resolve("IsoStore");
However,this
approach
offers
only
limited
advantages
over
the
GetInstance
method
approach,
and
you
willprobablyuseitmainlyifyoudecidetoregistercustommappingsinthecontainerandresolve
objectsthathaveanonstandardlifetime(suchasasingletonorperthreadlifetime).Tolearnmore
aboutusingthecontainerinthisway,seethedocumentationforUnityortherelatedguide"Whatever
theunityguideiscalled".
InjectingInstancesofObjects
WherethecontainerismostusefuliswhenyouapplyDItechniquesbydefiningdependenciesinyour
classesandthenhavingUnityinjectinstancesofobjectswhenthatclassininstantiated.Youcandefine
dependenciesinthreeways:
Asone
or
more
parameters
of
aconstructor
in
the
target
class.
Unity
will
create
instances
of
theappropriatetypesandpopulatetheconstructorparameterswhenthetargetobjectis
instantiated.Thisistheapproachyouwilltypicallyuse.Forexample,youcanhaveUnity
automaticallycreateandpassintoyourconstructoraninstanceofaLogWriteroran
ExceptionManager,storethereferenceinaclassvariableorfield,anduseitwithinthatclass.
Asoneormorepropertiesofthetargetclass,witheachofthesepropertiescarryinga
DependencyattributethatindicatestoUnitythatitmustcreateaninstanceofthetypedefined
bytheproperty,andsetthatinstanceasthevalueoftheproperty,whentheclassisresolved
throughthecontainer.
Asone
or
more
parameters
of
amethod
in
the
target
class.
Unity
will
create
instances
of
the
appropriatetypesandpopulatethemethodparameterswhenthetargetobjectisinstantiated,
thencallthatmethod.YoumustapplytheInjectionMethodattributetoanymethodsthat
requireinjection,andyoucanstorethereferencespassedintheparametersinaclassvariable
orfieldforuseitwithinthatclass.ThisapproachistypicallyusedwhenyouhaveanInitializeor
similarmethodthatshouldexecutewhentheclassisinstantiated.
AsUnitycreateseachobject,itinspectsitfordependenciesandautomaticallypopulatesthese.So,for
example,ifyouspecifyaparameterfortheconstructororadependentpropertyofacustomclasstobe
oftypeMyBusinessComponent,UnitywillcreateaninstanceofMyBusinessComponentandpopulate
theconstructororproperty.However,ifMyBusinessComponentdefinesadependencyonanotherclass
namedMyDataComponent,Unitywillcreateandinstanceofthatclassandpopulatethatdependency,
andsoon. Ifthereisnomappinginthecontainerforthetypespecifiedintheparameterorproperty,
Unitysimplycreatesanewinstanceofthespecifiedtypeandreturnsit.
PerhapsMyDataComponentrequiresanEnterpriseLibraryLogWritertocreatelogmessages?Ifit
containsadependentparameterorpropertyoftypeLogWriter,Unitywillpopulatethataspartofthe
8/12/2019 EntLib DevGuide PDC Preview
24/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 24
instantiationprocessaswell.Thiscanapplyrightacrossthedefineddependenciesinyourapplication,as
shownintheschematicbelow.
Soyou
can
see
from
this
how
easy
it
is
to
use
the
DI
approach
to
populate
all
of
your
dependencies
on
EnterpriseLibraryobjectsandyourowncustomobjectswithoutneedingtocreateinstancesdirectlyin
yourcode.And,ashintedatearlier,youcanevenuseUnitytocreateaninstanceofyourmainformor
startupclass.Providingthatyouspecifyallthedependenciesrequiredinyourapplicationthough
constructorandmethodparametersanddependentproperties,youcansimplyresolvethestartupclass
usingcode.Forexample,intheMainroutineofaWindowsFormsapplicationthatusesamainform
namedMyForm,youcanusecodesuchasthefollowingtopopulatealloftheapplicationdependencies
atstartup.
varcontainer=newUnityContainer()
.AddNewExtension();
Application.Run(container.Resolve());
ThefollowingschematicattemptstoshowsidebysidetheoverallprocessforformsbasedandWeb
basedapplicationtypesthatthesimpletwolinesofcodeshownabovecanaccomplish.Youcan
comparethesimilaritiesanddifferencesbetweenthetwotypesoftechnology.Thedocumentationfor
EnterpriseLibrarydescribessomeadvancedapproachesforstoringareferencetothecontainerat
runtimeinWebbasedapplicationsandservices.Youcanseethat,otherthatdefiningthedependencies
inyourclasses,EnterpriseLibrarysavesyouaconsiderableamountofeffort!
8/12/2019 EntLib DevGuide PDC Preview
25/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 25
Thisapproachtoresolvingandpopulatingindividualclassdependencies,orevenpopulatingtheentire
hierarchyofobjectsusedinyourapplicationbasedontyperegistrationsandmappingsdefinedinthe
container,providesseveraladvantages.Theseinclude:
Reducingcoupling
between
classes.
Dependencies
are
clearly
defined
in
each
class,
and
the
mappingsbetweeninterfacesandbaseclasses,andtheactualconcretetypes,arestoredinthe
containerandcanbeupdatedasrequiredwithoutrequiringanychangestothecode.
Makingyourcodemorediscoverable.Youcaneasilytellfromthetypesoftheconstructors,
properties,ormethodsofyourclasseswhatobjectstheyuseandwhatdependenciestheyhave.
8/12/2019 EntLib DevGuide PDC Preview
26/88
8/12/2019 EntLib DevGuide PDC Preview
27/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 27
propertyinjectionforaclassnamedMyNewObjectthatexposesasapropertyareferencetoan
instanceoftheEnterpriseLibraryCacheManagerclass.
publicclassMyNewObject
{
[Dependency]
publicCacheManager
DefaultCache
{get;set;}
}
WhenyouapplytheDependencyattributewithoutspecifyinganame,thecontainerwillreturnthe
defaultconcreteimplementationofthattypeasdefinedintheEnterpriseLibraryconfiguration.To
specifyanamedregistrationwhenusingpropertyinjection,youincludethenameasaparameterofthe
Dependencyattributeasshownbelow.
publicclassMyNewObject
{
[Dependency("LocalCache")]
publicCacheManagerNamedCache{get;set;}
}
MethodCallInjection
Methodcallinjectionisalesscommonapproachthanconstructorandpropertysetterinjection,butis
usefulintwospecificsituations.Constructorinjectiononlyworkswhenyouareinstantiatingnew
instancesofobjects(whentheconstructorisexecuted),whereasmethodcallinjectionwillworkwith
existinginstancesofobjects.Forexample,Unitywillexecutethemethodwhenitresolvesaninstance
thatisregisteredasasingleton.Andwhilepropertysetterinjectionalsoworkswithexistinginstances,it
requirespublicpropertiestobeexposed.
The
usual
approach
is
to
expose
a
public
initialization
method
that
takes
as
parameters
the
objects
you
wanttoresolveandobtainreferencesto.Unitywillpopulatetheparametersandthencallthemethod.
Asthemethodexecutes,youstoretheresolvedtypesinlocalvariablesofyourclass.Youapplythe
InjectionMethodattributetothemethodtoindicatethatanytypesdefinedinparametersofthe
methodaredependenciesoftheclass.
Thefollowingcodedemonstratesthemostcommonscenario,savingthedependentobjectinstanceina
classlevelvariable,foraclassnamedMyNewObjectthatexposesamethodnamedInitializethattakes
asparametersinstancesoftheEnterpriseLibraryCacheManagerandCryptographyManagerobjects.
publicclassMyNewObject
{
privateCacheManagermyCache;
privateCryptographyManagermyCrypto;
[InjectionMethod]
publicvoidInitialize(CacheManagercache,CryptographyManager,crypto)
{
//assignthedependentobjectstoclasslevelvariables
myCache=cache;
8/12/2019 EntLib DevGuide PDC Preview
28/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 28
myCrypto=crypto;
}
}
1.8 The
Example
Applications
TohelpyouunderstandhowyoucanuseEnterpriseLibraryandeachofthesevenapplicationblocks
coveredinthisguide,weprovideaseriesofsimpleexampleapplicationsthatyoucanrunandexamine.
EachisaConsolebasedapplicationwith,inmostcases,alloftherelevantcodethatusesEnterprise
LibrarywithinaseriesofroutinesintheProgram.csorProgram.vbfile.Thismakesiteasytoseehowthe
differentblockswork,andwhatyoucanachievewitheachone.
TheexamplesusethesimplestapproachtocreatingtheEnterpriseobjectstheyuse(theGetInstance
methoddescribedearlierinthechapter),andhavetheconfigurationinformationfortheblockstheyuse
storedintheApp.configfile.Eachoftheoptionsintheexamplesexercisesspecificfeaturesofthe
relevantblock,anddisplaystheresults.YoucanopenthesolutionsfortheseexamplesinVisualStudio,
orjustruntheexecutablefileinthebin\debugfolderandviewthesourcefilesinatexteditorifyou
prefer.
Toobtaintheexampleapplications,goto[linktoexamplesdownload].
1.9 Summary
ThisbriefintroductiontoEnterpriseLibrarywillhelpyoutogetstartedifyouarenotfamiliarwithits
capabilitiesandthebasicsofusingitinapplications.ThischapterdescribedwhatEnterpriseLibraryis,
whereyoucangetit,andwhatitcandoforyouintermsofmakingitmucheasiertomanageyour
crosscuttingconcerns.
This
book
concentrates
on
the
application
blocks
in
Enterprise
Library
that
"do
stuff"(asopposedtothosethat"wireupstuff").Theblocksweconcentrateoninthisbookinclude
Caching,Cryptography,DataAccess,ExceptionHandling,Logging,Security,andValidation.
ThischapteralsoaimstohelpyougetstartedwithEnterpriseLibrarybyexplaininghowyoudeployand
referencetheassembliesincontains,howyouconfigureyourapplicationstouseEnterpriseLibrary,how
youinstantiateEnterpriseLibraryobjects,andtheexampleapplicationsweprovide.Someofthemore
advancedfeaturesandconfigurationoptionsareomittedsothatyoucanconcentrateonthe
fundamentalrequirements.However,EnterpriseLibrarycontainssubstantialreferencedocumentation,
samples,andotherresourcesthatwillguideyouasyouexplorethesemoreadvancedfeatures.
8/12/2019 EntLib DevGuide PDC Preview
29/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 29
Chapter 2 Much ADO About Data
Access
ContentsIntroduction.......................................................................................................................................... 30
WhatDoestheDataAccessBlockDo?................................................................................................. 30
DataOperationsSupportedbytheDataAccessBlock..................................................................... 31
HowDoIUsetheDataAccessBlock?................................................................................................... 33
ConfiguringtheBlockandReferencingtheRequiredAssemblies.................................................... 33
CreatingDatabaseInstances............................................................................................................. 33
TheExampleApplication.................................................................................................................. 34
ReadingMultipleDataRows............................................................................................................. 35
ReadingRowsUsingaQuerywithNoParameters.................................................................. 35
ReadingRowsUsinganArrayofParameterValues................................................................. 36
ReadingRowsUsingQuerieswithNamedParameters........................................................... 37
RetrievingDataasObjects................................................................................................................ 39
AboutAccessors....................................................................................................................... 39
Creatingand
Executing
an
Accessor
........................................................................................
40
CreatingandUsingMappers.................................................................................................... 41
RetrievingXMLData......................................................................................................................... 42
RetrievingSingleScalarValues......................................................................................................... 43
RetrievingDataAsynchronously....................................................................................................... 44
PreparingforAsynchronousDataAccess................................................................................ 45
RetrievingRowSetDataAsynchronously................................................................................ 46
RetrievingDataasObjectsAsynchronously............................................................................. 48
UpdatingData................................................................................................................................... 50
ExecutinganUpdateQuery..................................................................................................... 50
WorkingwithDataSets............................................................................................................. 52
UpdatingtheDatabasefromaDataSet................................................................................... 52
ManagingConnections..................................................................................................................... 55
8/12/2019 EntLib DevGuide PDC Preview
30/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 30
WorkingwithConnectionBasedTransactions................................................................................. 57
WorkingwithDistributedTransactions............................................................................................ 58
ExtendingtheBlocktoUseOtherDatabases....................................................................................... 61
Summary............................................................................................................................................... 61
2.1 Introduction
Whendidyoulastwriteanenterpriselevelapplicationwhereyoudidn'tneedtohandledata?And
there'sagoodchancethatthisdatacamefromsomekindofrelationaldatabase.Workingwith
databasesisthesinglemostcommontaskmostenterpriseapplicationsneedtoaccomplish,andsoit's
nosurprisethattheDataAccessApplicationBlockisthemostwidelyusedofalloftheEnterpriseLibrary
blocksandnocoincidencethatwedecidedtocoveritinthefirstoftheapplicationblockchaptersin
thisbook.
AgreatmanyofthemillionsofEnterpriseLibraryusersaroundtheworldfirstcuttheirteethonthe
DataAccessblock.Why?Becauseitmakesiteasytoimplementthemostcommonlyuseddataaccess
operationswithoutneedingtowritethesamerepetitivecodeoverandoveragain,andwithouthaving
toworryaboutwhichdatabasetheapplicationwilltarget.AslongasthereisaDataAccessblock
provideravailableforyourtargetdatabase,youcanusethesamecodetoaccessthedata.Youdont
needtoworryaboutthesyntaxforparameters,theidiosyncrasiesoftheindividualdataaccess
methods,andthedifferentdatatypesthatarereturned.
Thismeansthatit'salsoeasytoswitchyourapplicationtouseadifferentdatabase,withouthavingto
rewrite
code,
recompile,
and
redeploy.
Administrators
and
operators
can
change
the
target
database
to
adifferentserver;andeventoadifferentdatabase(suchasmovingfromOracletoSQLServerorthe
reverse),withoutaffectingtheapplicationcode.Inthecurrentrelease,theDataAccessblockcontains
providersforSQLServer,SQLServerCompactEdition,andOracledatabases.Therearealsothirdparty
providersavailablefortheIBMDB2,MySql,ODP.NET,andSQLitedatabases.Formoreinformationon
these,seehttp://codeplex.com/entlibcontrib.
2.2 WhatDoestheDataAccessBlockDo?
TheDataAccessApplicationBlockabstractstheactualdatabaseyouareusing,andexposesaseriesof
methodsthat
make
it
easy
to
access
that
database
to
perform
common
tasks.
For
example,
to
fill
a
DataSetyousimplycreateaninstanceoftheappropriateDatabaseclass,useittogetanappropriate
Commandinstance,andpassthistotheExecuteDataSetmethodoftheDatabaseclass.Youdon'tneed
tocreateaDataAdapterorcalltheFillmethod.TheExecuteDataSetmethodmanagestheconnection,
andcarriesoutallthetasksrequiredtopopulateyourDataSet.Inasimilarway,theDatabaseclass
allowsyoutoobtainaDataReader,executecommandsdirectly,andupdatethedatabasefroma
8/12/2019 EntLib DevGuide PDC Preview
31/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 31
DataSet.Theblockalsosupportstransactionstohelpyoumanagemultipleoperationsthatcanberolled
backifanerroroccurs.
InadditiontothemorecommonapproachesfamiliartousersofADO.NET,theDataAccessblockalso
providestechniquesforasynchronousdataaccessfordatabasesthatsupportthisfeature,andthe
abilitytoreturndataasasequenceofobjectssuitableforclientsidequeryingusingtechniquessuchas
LanguageIntegratedQuery(LINQ).However,theblockisnotintendedtobeanObject/Relational
Mapping(O/RM)solution.Itusesmappingstorelateparametersandrelationaldatawiththeproperties
ofobjects,butdoesnotimplementanO/RMmodelingsolution.
ThemajoradvantagewithusingtheDataAccessblock,besidesthesimplicityachievedthroughthe
encapsulationofthe"boilerplate"codethatyouwouldotherwiseneedtowrite,isthatitprovidesaway
tocreateproviderindependentapplicationsthatcaneasilybemovedtouseadifferentsourcedatabase
type.Inmostcases,unlessyourcodetakesadvantageofmethodsspecifictoaparticulardatabase,the
onlychangerequiredistoupdatethecontentsofyourconfigurationfilewiththeappropriate
connectionstring.Youdonthavetochangethewaythatyouspecifyqueries(suchasSQLstatementsor
storedprocedure
names),
create
and
populate
parameters,
or
handle
return
values.
Thismeansthatadministratorsandoperatorscanredeployyourapplicationwithoutdraggingyouaway
fromthenewandexcitingprojectyouareworkingon(or,evenworse,backfromthatexoticforeign
beachwhereyouareenjoyingawellearnedholiday)justtoupdatesomedataaccesscallsinyour
application.Italsomeansreducedrequirementsfortesting,andtheconfigurationchangescanevenbe
accomplishedthroughGroupPolicyandWindowsManagementInstrumentation(WMI)2.0tools.
2.2.1 DataOperationsSupportedbytheDataAccessBlock
ThefollowingtablelistsbytaskthemostcommonlyusedmethodsthattheDataAccessblockexposes
to
retrieve
and
update
data.
Some
of
the
method
names
will
be
familiar
to
those
used
to
using
ADO.NET
directly.
Task Methods
Filling a DataSet and updating the
database from a DataSet.
ExecuteDataSet. Creates, populates, and returns a DataSet.
LoadDataSet. Populates and existing DataSet.
UpdateDataSet. Updates the database using an existing DataSet.
Reading multiple data rows. ExecuteReader. Creates and returns a provider-independent DbDataReader
instance
Executing a Command. ExecuteNonQuery. Executes the command and returns the number of rows
affected. Other return values (if any) appear as output parameters.
ExecuteScalar. Executes the command and returns a single value.
Retrieving data as a sequence of
objects.
ExecuteSprocAccessor. Returns data selected by a stored procedure as a
sequence of objects for client-side querying.
ExecuteSqlStringAccessor. Returns data selected by a SQL statement as a
sequence of objects for client-side querying.
8/12/2019 EntLib DevGuide PDC Preview
32/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 32
Retrieving XML data (SQL Server
only).
ExecuteXmlReader. Returns data as a series of XML elements exposed
through and XmlReader. Note that this is a method is specific to the
SqlDatabase class (not the underlying Database class).
Creating a Command. GetStoredProcCommand. Returns a Command object suitable for executing
a stored procedure.
GetSqlStringCommand. Returns a Command object suitable for executing a
SQL statement (which may contain parameters).
Working with Command
parameters.
AddInParameter. Creates a new input parameter and adds it to the parameter
collection of a Command.
AddOutParameter. Creates a new output parameter and adds it to the
parameter collection of a Command.
AddParameter. Creates a new parameter of the specific type and direction
and adds it to the parameter collection of a Command.
GetParameterValue. Returns the value of the specified parameter as an
Object type.
SetParameterValue. Sets the value of the specified parameter.
Working with transactions. CreateConnection. Creates and returns a connection for the current database
that allows you to initiate and manage a transaction over the connection.
YoucanseefromthistablethattheDataAccessblocksupportsalmostallofthecommonscenariosthat
youwillencounterwhenworkingwithrelationaldatabases.Eachdataaccessmethodalsohasmultiple
overloads,designedtosimplifyusageandintegratewhennecessarywithexistingdatatransactions.
Ingeneral,youshouldchoosetheoverloadyouusebasedonthefollowingguidelines:
OverloadsthatacceptanADO.NETDbCommandobjectprovidethemostflexibilityandcontrol
foreachmethod.
Overloadsthatacceptastoredprocedurenameandacollectionofvaluestobeusedas
parametervaluesforthestoredprocedureareconvenientwhenyourapplicationcallsstored
proceduresthathaveinputonlyparameters.
OverloadsthatacceptaCommandTypevalueandastringthatrepresentsthecommandare
convenientwhenyourapplicationexecutesinlineSQLstatements,orstoredproceduresthat
requirenoparameters.
Overloadsthatacceptatransactionallowexecutethemethodwithinanexistingtransaction.
Ifyou
use
the
SqlDatabase
type,
you
can
execute
several
of
the
common
methods
asynchronouslybyusingtheBeginandEndversionsofthemethods.
YoucanusetheDatabaseclasstocreateAccessorinstancesthatexecutedataaccess
operationsbothsynchronouslyandasynchronously,andreturntheresultsasaseriesofobjects
suitableforclientsidequeryingusingtechnologiessuchasLINQ.
8/12/2019 EntLib DevGuide PDC Preview
33/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 33
2.3 HowDoIUsetheDataAccessBlock?
BeforeyoustarttousetheDataAccessblock,youmustaddittoyourapplication.Youconfigurethe
blocktospecifythedatabasesyouwanttoworkwith,andaddtherelevantassembliestoyourproject.
Thenyoucancreateinstancesofthesedatabasesinyourcodeandusethemtoreadandwritedata.
2.3.1 ConfiguringtheBlockandReferencingtheRequiredAssemblies
ThefirststepinusingtheDataAccessblockistoconfigurethedatabasesyouwanttoaccess.Theblock
makesuseofthestandardsectionoftheApp.configorWeb.configfiletostorethe
individualdatabaseconnectionstrings,withtheadditionofasmallEnterpriseLibraryspecificsection
thatdefineswhichoftheconfigureddatabasesisthedefault.Youcanconfigureallofthesesettings
usingtheEnterpriseLibraryconfigurationconsole,asshowninthefollowingscreenshot.
[Awaitingnewimage]
Afteryouconfigurethedatabasesyouneed,youmustinstantiatetheminyourapplicationcode.Add
referencestotheassembliesyouwillrequire,andusingstatementstoyourcodeforthenamespaces
containingtheobjectsyouwilluse.InadditiontotheEnterpriseLibraryassembliesyourequireinevery
EnterpriseLibraryproject(listedinChapter1),youmustreferenceoraddtoyourbinfolderthe
assemblyMicrosoft.Practices.EnterpriseLibrary.Data.dll.IfyouareworkingwithaSQLServerCompact
Editiondatabase,youmustalsoreferenceoraddtheassembly
Microsoft.Practices.EnterpriseLibrary.Data.SqlCe.dll.IfyouareworkingwithanOracledatabase,you
canusetheOracleproviderincludedwithEnterpriseLibraryandtheADO.NETOracleprovider,which
requires
you
to
reference
or
add
the
assembly
System.Data.OracleClient.dll.
However,
keep
in
mind
thattheOracleClientproviderisdeprecatedinversion4.0ofthe.NETFramework,althoughitisstill
supportedbytheEnterpriseLibrary.Forthefuturedevelopment,considerchoosingadifferentOracle
driversuchasthatavailablefromtheEnterpriseLibraryContribsiteat
http://codeplex.com/entlibcontrib.
2.3.2 CreatingDatabaseInstances
YoucanuseavarietyoftechniquestoobtainaDatabaseinstanceforthedatabaseyouwanttoaccess.
Thesection"InstantiatingEnterpriseLibraryObjects"inChapter1describesthedifferentapproaches
youcanuse.Theexamplesyoucandownloadforthischapterusethesimplestapproach:callingthe
GetInstancemethod
of
the
EnterpriseLibraryContainer
through
its
static
Current
property,
as
shown
here,andstoringtheminapplicationwidevariablessothattheycanbeaccessedfromanywhereinthe
code.
staticDatabasedefaultDB=null;
staticDatabasenamedDB=null;
//ResolvethedefaultDatabaseobjectfromthecontainer.
8/12/2019 EntLib DevGuide PDC Preview
34/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 34
//Theactualconcretetypeisdeterminedbytheconfigurationsettings.
defaultDB=EnterpriseLibraryContainer.Current.GetInstance();
//ResolveaDatabaseobjectfromthecontainerusingtheconnectionstringname.
namedDB
=EnterpriseLibraryContainer.Current.GetInstance("ExampleDatabase");
Thecodeaboveshowshowyoucangetaninstanceofthedefaultdatabaseandanamedinstance(using
thenameintheconnectionstringssection).Usingthedefaultdatabaseisausefulapproachbecause
youcanchangewhichofthedatabasesdefinedinyourconfigurationisthedefaultsimplybyeditingthe
configurationfile,withoutrequiringrecompilationorredeploymentoftheapplication.
NoticethatthecodeabovereferencesthedatabaseinstancesasinstancesoftheDatabasebaseclass.
Thisisrequiredforcompatibilityofyouwanttobeabletochangethedatabasetypeatsomelater
stage.However,itmeansthatyoucanonlyusethefeaturesavailableacrossallofthepossibledatabase
types(themethodsandpropertiesdefinedintheDatabaseclass).
Some
features
are
only
available
in
the
concrete
types
for
specific
database.
For
example,
the
ExecuteXmlReadermethodisonlyavailableintheSqlDatabaseclass.Ifyouwanttousesuchfeatures,
youmustcastthedatabasetypeyouinstantiatetotheappropriateconcretetype.Thefollowingcode
createsaninstanceoftheSqlDatabaseclass.
staticSqlDatabasesqlServerDB=null;
//ResolveaSqlDatabaseobjectfromthecontainerusingthedefaultdatabase.
sqlServerDB=EnterpriseLibraryContainer.Current.GetInstance()
asSqlDatabase;
Inadditiontousingconfigurationtodefinethedatabasesyouwilluse,theDataAccessblockallowsyou
tocreate
instances
of
concrete
types
that
inherit
from
the
Database
class
directly
in
your
code,
as
shownhere.AllyouneeddoisprovideaconnectionstringthatspecifiestheappropriateADO.NETdata
providertype(suchasSqlClient).
//AssumethemethodGetConnectionStringexistsinyourapplicationand
//returnsavalidconnectionstring.
stringmyConnectionString=GetConnectionString();
SqlDatabasesqlDatabase=newSqlDatabase(myConnectionString);
2.3.3 TheExampleApplication
NowthatyouhaveyournewDatabaseobjectsreadytogo,we'llshowyouhowyoucanuseitto
performavariety
of
tasks.
You
can
download
an
example
application
(a
simple
Console
based
application)thatdemonstratesallofthescenariosyouwillseeintheremainderofthischapter.Youcan
runthisdirectlyfromthebin\debugfolder,oropenthesolutionnamedDataAccessinVisualStudioto
seeallofthecodeasyouruntheexamples.
8/12/2019 EntLib DevGuide PDC Preview
35/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 35
2.3.4 ReadingMultipleDataRows
Oneofthemostcommonoperationswhenworkingwithadatabaseisreadingmultiplerowsofdata.In
a.NETapplication,youusuallyaccesstheserowsasaDataReaderinstance,orstorethemina
DataTable(usuallywithinaDataSetyoucreate).Inthissectionwe'lllookattheuseofthe
ExecuteReader
method
that
returns
a
DataReader.
You
will
see
how
to
use
a
DataSet
with
the
Data
Accessblockmethodslaterinthischapter.
ReadingRowsUsingaQuerywithNoParameters
SimplequeriesconsistingofaninlineSQLstatementorastoredprocedure,whichtakenoparameters,
canbeexecutedusingtheExecuteReadermethodoverloadthatacceptsaCommandTypevalueanda
SQLstatementorstoresprocedurenameasastring.
Thefollowingcodeshowsthesimplestapproachforastoredprocedure,whereyoucanalsoomitthe
CommandTypeparameter.ThedefaultisCommandType.StoredProcedure(unlikeADO.NET,wherethe
defaultisCommandType.Text.
//CalltheExecuteReadermethodbyspecifyingjustthestoredprocedurename.
using(IDataReaderreader=namedDB.ExecuteReader("MyStoredProcName"))
{
//Usethevaluesintherowsasrequired.
}
TouseaninlineSQLstatement,youmustspecifytheappropriateCommandTypevalue,asshownhere.
//CalltheExecuteReadermethodbyspecifyingthecommandtype
//asaSQLstatement,andpassingintheSQLstatement.
using(IDataReaderreader=namedDB.ExecuteReader(CommandType.Text,
"SELECTTOP1*FROMOrderList"))
{//Usethevaluesintherowsasrequired herewearejustdisplayingthem.
DisplayRowValues(reader);
}
Theexamplenamed"ReturnrowsusingaSQLstatementwithnoparameters"usesthiscodetoretrieve
aDataReadercontainingthefirstorderinthesampledatabase,andthendisplaysthevaluesinthis
singlerow.Itusesasimpleauxiliaryroutinethatiteratesthroughalltherowsandcolumns,writingthe
valuestotheconsolescreen.
privatestaticvoidDisplayRowValues(IDataReaderreader)
{
while(reader.Read())
{
for(inti=0;i
8/12/2019 EntLib DevGuide PDC Preview
36/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 36
}
TheresultisalistofthecolumnsandtheirvaluesintheDataReader,asshownhere.
Id=1
Status=DRAFT
CreatedOn
=
01/02/2009
11:12:06
Name=AdjustableRace
LastName=Abbas
FirstName=Syed
ShipStreet=123ElmStreet
ShipCity=Denver
ShipZipCode=12345
ShippingOption=Twodayshipping
State=Colorado
ReadingRowsUsinganArrayofParameterValues
WhileyoumayusesimplenoparameterstoredproceduresandSQLstatementsinsomescenarios,it's
farmorecommontousequeriesthatacceptinputparametersthatselectrowsorspecifyhowthequery
willexecutewithinthedatabaseserver.Ifyouuseonlyinputparameters,youcanwrapthevaluesupas
anObjectarrayandpassthemtothestoredprocedureorSQLstatement.Notethatthismeansyou
mustaddthemtothearrayinthesameorderastheyareexpectedbythequery,becauseyouarenot
usingnamesfortheseparametersyouareonlysupplyingtheactualvalues.Thefollowingcodeshows
howyoucanexecuteastoredprocedurethattakesasinglestringparameter.
//CalltheExecuteReadermethodwiththestoredprocedure
//nameandanObjectarraycontainingtheparametervalues.
using(IDataReaderreader=defaultDB.ExecuteReader("ListOrdersByState",
newobject[]{"Colorado"}))
{
//Usethevaluesintherowsasrequired herewearejustdisplayingthem.
DisplayRowValues(reader);
}
Theexamplenamed"Returnrowsusingastoredprocedurewithparameters"usesthiscodetoquery
thesampledatabase,andgeneratesthefollowingoutput.
Id=1
Status=DRAFT
CreatedOn=01/02/200911:12:06
Name=AdjustableRace
LastName=Abbas
FirstName=Syed
ShipStreet=123ElmStreet
ShipCity=Denver
ShipZipCode=12345
ShippingOption=Twodayshipping
State=Colorado
8/12/2019 EntLib DevGuide PDC Preview
37/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 37
Id=2
Status=DRAFT
CreatedOn=03/02/200901:12:06
Name=AllPurposeBikeStand
LastName=Abel
FirstName=Catherine
ShipStreet=321CedarCourt
ShipCity=Denver
ShipZipCode=12345
ShippingOption=Onedayshipping
State=Colorado
ReadingRowsUsingQuerieswithNamedParameters
Thetechniqueinthepreviousexampleofsupplyingjustanarrayofparametervaluesiseasyand
efficient,buthassomelimitations.Itdoesnotallowyoutospecifythedirection(suchasinputor
output),orthedatatypewhichmaybeanissueifthedatatypeofaparameterdoesnotexactlymatch
(or
cannot
be
implicitly
converted
into)
the
correct
type
discovered
for
a
stored
procedure.
If
you
create
anarrayofparametersforyourquery,youcanspecifymoredetailsaboutthetypesoftheparameters,
andthewaytheyshouldbeused.
Inaddition,somedatabasesystemsallocateparametersusedinSQLstatementsorstoredprocedures
simplybyposition.However,manydatabasesystems,suchasMicrosoftSQLServer,allowyoutouse
namedparameters.Thedatabasematchesthenamesoftheparameterssentwiththecommandtothe
namesoftheparametersdefinedintheSQLstatementorstoredprocedure.Thismeansthatyouare
notconfinedtoaddingparameterstoyourcommandinaspecificorder.However,beawarethatifyou
usenamedparametersandthenchangethedatabasetypetoonethatdoesnotsupportnamed
parametersanyparametersthataresuppliedoutoforderwillprobablycauseerrors(whichmaybe
difficultto
detect
ifall
of
the
parameters
are
of
the
same
data
type!).
Toworkwithnamedparametersorparametersofdefinedtypes,youmustaccesstheCommandobject
thatwillbeusedtoexecutethequery,andmanipulateitscollectionorparameters.TheDataAccess
blockmakesiteasytocreateandaccesstheCommandobjectbyusingtwomethodsoftheDatabase
class:GetSqlStringCommandandGetStoredProcCommand.Thesemethodsreturnaninstanceofthe
appropriatecommandclassfortheconfigureddatabaseasaproviderindependentDbCommandtype
reference.
Afteryoucreatetheappropriatetypeofcommand,youcanusethemanyvariationsoftheDatabase
methodstomanipulatethecollectionofparameters.Youcanaddparameterswithaspecificdirection
usingthe
AddInParameter
or
AddOutParameter
method,
or
by
using
the
AddParameter
method
and
providingavaluefortheParameterDirectionparameter.Youcanchangethevalueofexisting
parametersalreadyaddedtothecommandusingtheGetParameterValueandSetParameterValue
methods.
Thefollowingcodeshowshoweasyitistocreateacommand,addaninputparameter,andexecute
bothaSQLstatementandastoredprocedure.Noticehowthecodespecifiesthecommandtowhichthe
8/12/2019 EntLib DevGuide PDC Preview
38/88
AGuidetoDevelopingwithEnterpriseLibrary5.0 38
Databaseclassshouldaddtheparameter(therecouldbemorethanoneconnectiondefinedforthe
database),thename,thedatatype,andthevalueofthenewparameter.
//ReaddatawithaSQLstatementthatacceptsoneparameter.
stringsqlStatement="SELECTTOP1*FROMOrderListWHEREStateLIKE@state";
//Create
asuitable
command
type
and
add
the
required
parameter.
using(DbCommandsqlCmd=defaultDB.GetSqlStringCommand(sqlStatement))
{
defaultDB.AddInParameter(sqlCmd,"state",DbType.String,"NewYork");
//CalltheExecuteReadermethodwiththecommand.
using(IDataReadersqlReader=namedDB.ExecuteReader(sqlCmd))
{
Console.WriteLine("ResultsfromexecutingSQLstatement:");
DisplayRowValues(sqlReader);
}
}
//Nowreadthesamedatawithastoredprocedurethatacceptsoneparameter.
stringstoredProcName="ListOrdersByState";
//Createasuitablecommandtypeandaddtherequiredparameter.
using(DbCommandsprocCmd=defaultDB.GetStoredProcCommand(storedProcName))
{
defaultDB.AddInParameter(sprocCmd,"state",DbType.String,"NewYork");
//CalltheExecuteReadermethodwiththecommand.
using(IDataReadersprocReader=namedDB.ExecuteReader(sprocCmd))
{
Console.WriteLine("Resultsfromexecutingstoredprocedure:");
DisplayRowValues(sprocReader);}
}
Theexamplenamed"ReturnrowsusingaSQLstatementorstoredprocedurewithnamedparameters"
usesthecodeyouseeabovetoexecuteaSQLstatementandastoredprocedureag