Tải bản đầy đủ (.pdf) (1,436 trang)

Visual studio tools for office using visual basic 2005 with excel, word, outlook, and infopath (2006)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (16.8 MB, 1,436 trang )

VisualStudioToolsforOffice:UsingVisualBasic
2005withExcel,Word,Outlook,andInfoPath
ByEricCarter,EricLippert
...............................................
Publisher:AddisonWesleyProfessional
PubDate:April26,2006
PrintISBN-10:0-321-41175-7
PrintISBN-13:978-0-321-41175-4
Pages:1120

TableofContents|Index

"WiththeapplicationdevelopmentcommunitysofocusedontheSmartClientrevolution,a
bookthatcoversVSTOfromAtoZisbothimportantandnecessary.Thisbooklivesupto
bigexpectations.Itisthorough,hastonsofexamplecode,andcoversOfficeprogramming
ingeneraltermstopicsthatcanbeforeigntotheseasoned.NETdeveloperwhohas
focusedonASP.NETapplicationsforyears.CongratulationstoEricLippertandEricCarter
forsuchavaluablework!"TimHuckaby,CEO,InterKnowlogy,Microsoftregionaldirector
"Thisbookcoversinaclearandconcisewayalloftheinsandoutsofprogrammingwith
VisualStudioToolsforOffice.Giventheauthors'exhaustiveexperienceswiththissubject,
youcan'tgetamoreauthoritativedescriptionofVSTOthanthisbook!"PaulVick,technical
lead,VisualBasic.NET,MicrosoftCorporation
"EricandEricreallygetit.ProfessionalprogrammerswilllovetherichpowerofVisual
Studioand.NET,alongwiththeabilitytotapintoOfficeprogrammability.Thisbookwalks
youthroughprogrammingExcel,Word,InfoPath,andOutlooksolutions."VernonW.Hui,
testlead,MicrosoftCorporation
"Thisbookisanin-depth,expert,anddefinitiveguidetoprogrammingusingVisualStudio
ToolsforOffice2005.Itisamust-havebookforanyonedoingOfficedevelopment."Siew
MoiKhor,programmer/writer,MicrosoftCorporation
"Wedon'tbuytechnicalbooksforlightreading.Webuythemasaresourcefordeveloping
asolution.ThisbookisanexcellentresourceforsomeonegettingstartedwithSmart


Clientdevelopment.Forexample,itiscommontohearacommentalongthelinesof,'Itis
easytomanipulatetheTaskPaneinOffice2003usingVSTO2005,'butuntilyousee
somethingliketheexampleatthestartofChapter15,itishardtoput'easy'into
perspective.ThisisathoroughbookthatcoverseverythingfromcallingOfficeapplications
fromyourapplication,tobuildingapplicationsthatareSmartDocuments.Itallowsthe
traditionalWindowsdevelopertoreallyleveragethepowerofOffice2003."BillSheldon,
principalengineer,InterKnowlogy,MVP
"EricCarterandEricLipperthavebeenthedrivingforcebehindOfficedevelopmentand


VisualStudioToolsforOffice2005.Thedepthoftheirknowledgeandunderstandingof
VSTOandOfficeisevidentinthisbook.Professionaldevelopersarchitectingenterprise
solutionsusingVSTO2005andOfficeSystem2003nowhaveanewweaponintheir
technicalarsenal."PaulStubbs,programmanager,MicrosoftCorporation
"Thisbookisbothalearningtoolandareferencebook,witharichnessoftables
containingobjectmodelobjectsandtheirproperties,methods,andevents.Iwould
recommendittoanyoneconsideringdoingOfficedevelopmentusingthe.NETframework,
especiallypeopleinterestedinVSTOprogramming."RufusLittlefield,softwaredesign
engineer/tester,MicrosoftCorporation
VisualStudioToolsforOfficeisboththefirstandthedefinitivebookonVSTO2005
programming,writtenbytheinventorsofthetechnology.VSTOisasetoftoolsthatallows
professionaldeveloperstousethefullpowerofVisualStudio.NETandthe.NET
FrameworktoputcodebehindExcel2003,Word2003,Outlook2003,andInfoPath2003.
VSTOprovidesfunctionalityneverbeforeavailabletotheOfficedeveloper:databinding
anddata/viewseparation,design-timeviewsofExcelandWorddocumentsinsideVisual
Studio,richsupportforWindowsFormscontrolsinadocument,theabilitytocreate
customOfficetaskpanes,server-sideprogrammingsupportagainstOffice,andmuch
more.
CarterandLippertcovertheirsubjectmatterwithdeftinsightintotheneedsof.NET
developerslearningVSTO.Thisbook

ExplainsthearchitectureofMicrosoftOfficeprogrammingandintroducestheobject
models
TeachesthethreebasicpatternsofOfficesolutions:Officeautomationexecutables,
Officeadd-ins,andcodebehindadocument
ExploresthewaysofcustomizingExcel,Word,Outlook,andInfoPath,andplumbs
thedepthsofprogrammingwiththeireventsandobjectmodels
IntroducestheVSTOprogrammingmodel
TeacheshowtouseWindowsFormsinVSTOandhowtoworkwiththeActionsPane
DelvesintoVSTOdataprogrammingandserverdatascenarios
Explores.NETcodesecurityandVSTOdeployment
AdvancedmaterialcoversworkingwithXMLinWordandExcel,developingCOMadd-ins
forWordandExcel,andcreatingOutlookadd-inswithVSTO.
Thecompletecodesamplesareavailableonthebook'sWebpage.


VisualStudioToolsforOffice:UsingVisualBasic
2005withExcel,Word,Outlook,andInfoPath
ByEricCarter,EricLippert
...............................................
Publisher:AddisonWesleyProfessional
PubDate:April26,2006
PrintISBN-10:0-321-41175-7
PrintISBN-13:978-0-321-41175-4
Pages:1120

TableofContents|Index








































Copyright
PraiseforVisualStudioToolsforOffice
Microsoft.NETDevelopmentSeries
Foreword
Preface
Acknowledgments
AbouttheAuthors
PartI:AnIntroductiontoVSTO
Chapter1.AnIntroductiontoOfficeProgramming
WhyOfficeProgramming?
OfficeObjectModels
Properties,Methods,andEvents
TheOfficePrimaryInteropAssemblies(PIAs)
Conclusion
Chapter2.IntroductiontoOfficeSolutions
TheThreeBasicPatternsofOfficeSolutions
OfficeAutomationExecutables
OfficeAdd-Ins
CodeBehindaDocument
Conclusion
PartII:OfficeProgrammingin.NET
Chapter3.ProgrammingExcel


















































































WaystoCustomizeExcel
ProgrammingUser-DefinedFunctions
IntroductiontotheExcelObjectModel
Conclusion
Chapter4.WorkingwithExcelEvents
EventsintheExcelObjectModel
EventsinVisualStudio2005ToolsforOffice
Conclusion
Chapter5.WorkingwithExcelObjects
WorkingwiththeApplicationObject
WorkingwiththeWorkbooksCollection
WorkingwiththeWorkbookObject
WorkingwiththeWorksheets,Charts,andSheetsCollections
WorkingwithDocumentProperties
WorkingwiththeWindowsCollections

WorkingwiththeWindowObject
WorkingwiththeNamesCollectionandNameObject
WorkingwiththeWorksheetObject
WorkingwiththeRangeObject
SpecialExcelIssues
Conclusion
Chapter6.ProgrammingWord
WaystoCustomizeWord
ProgrammingResearchServices
IntroductiontotheWordObjectModel
Conclusion
Chapter7.WorkingwithWordEvents
EventsintheWordObjectModel
EventsinVisualStudioToolsforOffice
Conclusion
Chapter8.WorkingwithWordObjects
WorkingwiththeApplicationObject
WorkingwiththeDialogObject
WorkingwithWindows
WorkingwithTemplates
WorkingwithDocuments
WorkingwithaDocument
WorkingwiththeRangeObject














































































WorkingwithBookmarks

WorkingwithTables
Conclusion
Chapter9.ProgrammingOutlook
WaystoCustomizeOutlook
CustomPropertyPages
IntroductiontotheOutlookObjectModel
IntroductiontotheCollaborationDataObjects
Conclusion
Chapter10.WorkingwithOutlookEvents
EventsintheOutlookObjectModel
ApplicationLevelEvents
OutlookItemEvents
OtherEvents
Conclusion
Chapter11.WorkingwithOutlookObjects
WorkingwiththeApplicationObject
WorkingwiththeExplorersandInspectorsCollections
WorkingwiththeExplorerObject
WorkingwiththeInspectorObject
WorkingwiththeNameSpaceObject

WorkingwiththeMAPIFolderObject
WorkingwiththeItemsCollection
PropertiesandMethodsCommontoOutlookItems
OutlookIssues
Conclusion
Chapter12.IntroductiontoInfoPath
WhatIsInfoPath?
GettingStarted
FormSecurity
ProgrammingInfoPath
DataSourceEvents
FormEvents,Properties,andMethods
Conclusion
PartIII:OfficeProgramminginVSTO

Chapter13.TheVSTOProgrammingModel

TheVSTOProgrammingModel

VSTOExtensionstoWordandExcelObjects




DynamicControls



VSTOExtensionstotheWordandExcelObjectModels




Conclusion











































































Chapter14.UsingWindowsFormsinVSTO
Introduction
AddingWindowsFormsControlstoYourDocument
WritingCodeBehindaControl
TheWindowsFormsControlHostingArchitecture
PropertiesMergedfromOLEObjectorOLEControl
AddingControlsatRuntime
Conclusion
Chapter15.WorkingwiththeActionsPane
IntroductiontotheActionsPane
WorkingwiththeActionsPaneControl
Conclusion
Chapter16.WorkingwithSmartTagsinVSTO
IntroductiontoSmartTags

CreatingDocument-LevelSmartTagswithVSTO
CreatingApplication-LevelSmartTags
CreatinganApplication-LevelSmartTagClassLibraryinVisualStudio
CreatingaRecognizerClass
CreatinganActionClass
RegisteringandTrustinganApplication-LevelSmartTagClassLibrary
RunningandTestingtheApplication-LevelSmartTag
DebugginganApplication-LevelSmartTag
Conclusion
Chapter17.VSTODataProgramming
CreatingaData-BoundCustomizedSpreadsheetwithVSTO
CreatingaData-BoundCustomizedWordDocumentwithVSTO
Datasets,Adapters,andSources
AnotherTechniqueforCreatingData-BoundSpreadsheets
CachingDataintheDataIsland
AdvancedADO.NETDataBinding:LookingBehindtheScenes
Binding-RelatedExtensionstoHostItemsandHostControls
Conclusion
Chapter18.ServerDataScenarios
PopulatingaDocumentwithDataontheServer
UsingServerDocumentandASP.NET




AnAlternativeApproach:CreateaCustomHandler






AHandyClient-SideServerDocumentUtility
TheServerDocumentObjectModel
Conclusion





































































Chapter19..NETCodeSecurity
Code-AccessSecurityVersusRole-BasedSecurity
Code-AccessSecurityin.NET
PublisherCertificates
TrustingtheDocument
Conclusion
Chapter20.Deployment
VSTOPrerequisites
DeployingtoanIntranetSharedDirectoryorWebSite
LocalMachineDeploymentWithoutaDeploymentManifest
EditingManifests
CreatingSetupPackages
Conclusion
PartIV:AdvancedOfficeProgramming
Chapter21.WorkingwithXMLinExcel
IntroductiontoExcel'sXMLFeatures
IntroductiontoXMLSchemaCreationinVisualStudio
AnEnd-to-EndScenario
AdvancedXMLFeaturesinExcel

Excel-FriendlyXMLSchemas
VSTOSupportforExcelSchemaMapping
Conclusion
Chapter22.WorkingwithXMLinWord
IntroductiontoWord'sXMLFeatures
AnEnd-to-EndScenario:CreatingaSchemaandMappingItintoaWord
Document
ExportingtheMappedXMLintheDocumenttoanXMLDataFile
ImportinganXMLDataFileintotheMappedDocument
TheXMLOptionsDialogBox
VSTOSupportforWordSchemaMapping
VSTOSupportfortheWordMLFileFormat
Conclusion
Chapter23.DevelopingCOMAddInsforWordandExcel
IntroductiontoAddIns










































ScenariosforUsingAddIns
HowaCOMAddInIsRegistered
ImplementingIDTExtensibility2
WritingaCOMAddInUsingVisualStudio

ThePitfallsofmscoree.dll
COMInteropandregasm.exe
Shimming:ASolutiontotheProblemswithmscoree.dll
Conclusion
Chapter24.CreatingOutlookAddInswithVSTO
MovingAwayfromCOMAddIns
CreatinganOutlookAddIninVSTO
Conclusion
BibsrcBibliography
Security
OfficeProgramming
DataProgramming
FormsProgramming
Infrastructure
Index


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andthepublisherwas
awareofatrademarkclaim,thedesignationshavebeenprinted
withinitialcapitallettersorinallcapitals.
The.NETlogoiseitheraregisteredtrademarkortrademarkof
MicrosoftCorporationintheUnitedStatesand/orother
countriesandisusedunderlicensefromMicrosoft.
Theauthorsandpublisherhavetakencareinthepreparationof
thisbook,butmakenoexpressedorimpliedwarrantyofany
kindandassumenoresponsibilityforerrorsoromissions.No
liabilityisassumedforincidentalorconsequentialdamagesin

connectionwithorarisingoutoftheuseoftheinformationor
programscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales,which
mayincludeelectronicversionsand/orcustomcoversand
contentparticulartoyourbusiness,traininggoals,marketing
focus,andbrandinginterests.Formoreinformation,please
contact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsidetheU.S.,pleasecontact:
InternationalSales



VisitusontheWeb:www.awprofessional.com
LibraryofCongressCataloging-in-PublicationData:

Carter,Eric.
VisualstudiotoolsforOffice:usingVisualBasic2005withExcel,Word,
Carter,EricLippert.
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-321-41175-7(pbk.:alk.paper)
1.MicrosoftVisualBASIC.2.BASIC(Computerprogramlanguage)
4.MicrosoftOffice.I.Lippert,Eric.II.Title.
QA76.73.B3C3452006
005.13'3dc222006001141
Copyright©2006PearsonEducation,Inc.

Allrightsreserved.PrintedintheUnitedStatesofAmerica.This
publicationisprotectedbycopyright,andpermissionmustbe
obtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissionin
anyformorbyanymeans,electronic,mechanical,
photocopying,recording,orlikewise.Forinformationregarding
permissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
TextprintedintheUnitedStatesonrecycledpaperatCourierin
Stoughton,Massachusetts.Firstprinting,April2006


Dedication
Tomywife,Tamsyn,andourchildrenJason,Hayley,
Camilla,Rand,andElizabeth.
E.C.
ToLeahLippert,forembarkingwithmeonafabulous
adventure.AndtoDavidLippert,whotaughtmetoexpect
theunexpectedalongtheway.
E.L.


PraiseforVisualStudioToolsforOffice
"Withtheapplicationdevelopmentcommunitysofocused
ontheSmartClientrevolution,abookthatcoversVSTO
fromAtoZisbothimportantandnecessary.Thisbook

livesuptobigexpectations.Itisthorough,hastonsof
examplecode,andcoversOfficeprogrammingingeneral
termstopicsthatcanbeforeigntotheseasoned.NET
developerwhohasfocusedonASP.NETapplicationsfor
years.CongratulationstoEricLippertandEricCarterfor
suchavaluablework!"
TimHuckaby,CEO,InterKnowlogy,Microsoftregional
director
"Thisbookcoversinaclearandconcisewayalloftheins
andoutsofprogrammingwithVisualStudioToolsfor
Office.Giventheauthors'exhaustiveexperienceswiththis
subject,youcan'tgetamoreauthoritativedescriptionof
VSTOthanthisbook!"
PaulVick,technicallead,VisualBasic.NET,Microsoft
Corporation
"EricandEricreallygetit.Professionalprogrammerswill
lovetherichpowerofVisualStudioand.NET,alongwith
theabilitytotapintoOfficeprogrammability.Thisbook
walksyouthroughprogrammingExcel,Word,InfoPath,
andOutlooksolutions."
VernonW.Hui,testlead,MicrosoftCorporation
"Thisbookisanin-depth,expert,anddefinitiveguideto
programmingusingVisualStudioToolsforOffice2005.It
isamust-havebookforanyonedoingOffice


development."
SiewMoiKhor,programmer/writer,MicrosoftCorporation
"Wedon'tbuytechnicalbooksforlightreading;webuy
themasaresourcefordevelopingasolution.Thisbookis

anexcellentresourceforsomeonegettingstartedwith
SmartClientdevelopment.Forexample,itiscommonto
hearacommentalongthelinesof,'Itiseasyto
manipulatetheTaskPaneinOffice2003usingVSTO
2005,'butuntilyouseesomethingliketheexampleatthe
startofChapter15,itishardtoput'easy'into
perspective.Thisisathoroughbookthatcovers
everythingfromcallingOfficeapplicationsfromyour
application,tobuildingapplicationsthatareSmart
Documents.ItallowsthetraditionalWindowsdeveloperto
reallyleveragethepowerofOffice2003."
BillSheldon,principalengineer,InterKnowlogy,MVP
"EricCarterandEricLipperthavebeenthedrivingforce
behindOfficedevelopmentandVisualStudioToolsfor
Office2005.Thedepthoftheirknowledgeand
understandingofVSTOandOfficeisevidentinthisbook.
Professionaldevelopersarchitectingenterprisesolutions
usingVSTO2005andOfficeSystem2003nowhaveanew
weaponintheirtechnicalarsenal."
PaulStubbs,programmanager,MicrosoftCorporation
"Thisbookisbothalearningtoolandareferencebook,
witharichnessoftablescontainingobjectmodelobjects
andtheirproperties,methods,andevents.Iwould
recommendittoanyoneconsideringdoingOffice
developmentusingthe.NETframework,especiallypeople
interestedinVSTOprogramming."


RufusLittlefield,softwaredesignengineer/tester,
MicrosoftCorporation



Microsoft.NETDevelopmentSeries
JohnMontgomery,SeriesAdvisor
DonBox,SeriesAdvisor
MartinHeller,SeriesEditor
TheMicrosoft.NETDevelopmentSeriesissupportedand
developedbytheleadersandexpertsofMicrosoftdevelopment
technologiesincludingMicrosoftarchitectsandDevelopMentor
instructors.Thebooksinthisseriesprovideacoreresourceof
informationandunderstandingeverydeveloperneedsinorder
towriteeffectiveapplicationsandmanagedcode.Learnfrom
theleadershowtomaximizeyouruseofthe.NETFramework
anditsprogramminglanguages.

TitlesintheSeries
BradAbrams,.NETFrameworkStandardLibraryAnnotated
ReferenceVolume1:BaseClassLibraryandExtendedNumerics
Library,0-321-15489-4
BradAbramsandTamaraAbrams,.NETFrameworkStandard
LibraryAnnotatedReference,Volume2:NetworkingLibrary,
ReflectionLibrary,andXMLLibrary,0-321-19445-4
KeithBallinger,.NETWebServices:Architectureand
Implementation,0-321-11359-4
BobBeauchemin,NielsBerglund,DanSullivan,AFirstLookat
SQLServer2005forDevelopers,0-321-18059-3
DonBoxwithChrisSells,Essential.NET,Volume1:The
CommonLanguageRuntime,0-201-73411-7



KeithBrown,The.NETDeveloper'sGuidetoWindowsSecurity,
0-321-22835-9
EricCarterandEricLippert,VisualStudioToolsforOffice:Using
C#withExcel,Word,Outlook,andInfoPath,0-321-33488-4
EricCarterandEricLippert,VisualStudioToolsforOffice:Using
VisualBasic2005withExcel,Word,Outlook,andInfoPath,0321-41175-7
MaheshChand,GraphicsProgrammingwithGDI+,0-32116077-0
KrzysztofCwalinaandBradAbrams,FrameworkDesign
Guidelines:Conventions,Idioms,andPatternsforReusable
.NETLibraries,0-321-24675-6
AndersHejlsberg,ScottWiltamuth,PeterGolde,TheC#
ProgrammingLanguage,0-321-15491-6
AlexHomer,DaveSussman,MarkFussell,ADO.NETand
System.Xmlv.2.0TheBetaVersion,0-321-24712-4
AlexHomer,DaveSussman,RobHoward,ASP.NETv.2.0The
BetaVersion,0-321-25727-8
JamesS.MillerandSusannRagsdale,TheCommonLanguage
InfrastructureAnnotatedStandard,0-321-15493-2
ChristianNagel,EnterpriseServiceswiththe.NETFramework:
DevelopingDistributedBusinessSolutionswith.NETEnterprise
Services,0-321-24673-X
BrianNoyes,DataBindingwithWindowsForms2.0:
ProgrammingSmartClientDataApplicationswith.NET,0-32126892-X
FritzOnion,EssentialASP.NETwithExamplesinC#,0-20176040-1


FritzOnion,EssentialASP.NETwithExamplesinVisualBasic
.NET,0-201-76039-8
TedPattisonandDr.JoeHummel,BuildingApplicationsand
ComponentswithVisualBasic.NET,0-201-73495-8

Dr.NeilRoodyn,eXtreme.NET:IntroducingeXtreme
ProgrammingTechniquesto.NETDevelopers,0-321-30363-6
ChrisSells,WindowsFormsProgramminginC#,0-321-116208
ChrisSellsandJustinGehtland,WindowsFormsProgramming
inVisualBasic.NET,0-321-12519-3
PaulVick,TheVisualBasic.NETProgrammingLanguage,0321-16951-4
DamienWatkins,MarkHammond,BradAbrams,Programming
inthe.NETEnvironment,0-201-77018-0
ShawnWildermuth,PragmaticADO.NET:DataAccessforthe
InternetWorld,0-201-74568-2
PaulYaoandDavidDurant,.NETCompactFramework
ProgrammingwithC#,0-321-17403-8
PaulYaoandDavidDurant,.NETCompactFramework
ProgrammingwithVisualBasic.NET,0-321-17404-6


Foreword
IT'SWITHSOMEamountoftrepidationthatIfacedthe
challengeofcomposingaforewordtothisparticularbook.Let's
faceit:Thenamesonthecoverinspiresomeamountofawe.
It'shumblingtoknowthatone'swordswillintroducewhatone
believestobetheseminalworkonagiventopic,andbelieve
me,I'mrelativelysurethisbookwillmeetthatloftygoal.When
approachedwiththeinvitationtogracethefrontmatterofthe
book,myfirstresponsewastowonderwhatIcouldpossibly
addcouldn'ttheyfindsomeluminaryatMicrosofttowritethe
foreword?Itseems,however,thatanoutsidevoiceaddssome
credencetotheproceedings,so,dearreader,Ispeakmeeklyin
thepresenceofgreatness.
First,alittleaboutme(it'sthelastchanceI'mgoingtogetin

thisshortpiece):I'vebeenlurkingabout,programmingOffice
initsvariousguises,formorethantenyears.I'vewrittenalot
aboutthewondersandgotchasofOfficedevelopment,and
survivedthegloryyearssurroundingOffice2000,whenit
lookedlikeOfficemightfinallymakeasuccessful,integrated
developmentplatform.Around2001,itbecameclearthatno
matterhowhardIandlike-mindedfolkswantedOfficeto
becomearespecteddevelopmentstandard,itjustwasn'tgoing
tomakeitwithVBAastheprogramminglanguage.
WiththereleaseofVisualStudioToolsforOffice2003,itfinally
lookedlikewe'dmadesomeprogress:Nolongerrelegatedto
the1990s,Officedeveloperscouldembrace.NETandallits
goodness,takingadvantageofmanagedcode,code-access
security,xcopydeployment,andalltherestthat.NETsupplied.
Ilovedthisproduct,butitneverreallyreachedcriticalmass
withthedevelopercommunity.Mostlikely,thefactthatyou
couldonlyuseCOM-basedcontrolsondocuments,andthefact
thattheproductsuppliednodesign-timeexperienceatall,


madeitaslowstarter.
Aroundthattime,Iveryclearlyremembersittingdownatsome
MicrosofteventandmeetingEricCarter.Ididn'treallyknow
whohewasatthetime(andhecertainlydidn'tknowanything
aboutme),butheseemedniceenough,andwechattedfor
severalhoursaboutOfficedevelopmentingeneralandabout
VSTOspecifically.OnlylaterdidIlearnthathewashighupin
thedevelopmentsideoftheproduct.(Ispenthoursworrying
thatI'dsaidsomethingreallystupidwhilewewerechatting.
Hopenot....)Webeganalongcorrespondence,inwhichI've

moreoftenthannotmadeitclearthatI'vegotalottolearn
abouthow.NETandOfficeinteract.I'vespentmanyhours
learningfromEricCarter'sblog,andEricLippert'sblogisjustas
meaty.IfyouarespendingtimedoingOfficedevelopment,
makesureyoudropbyboth:
/> />Ispentsomehoursperusingadraftcopyofthisbookand,in
eachchapter,attemptedtofindsometrick,somelittlenugget,
thatIhadfiguredoutonmyownbutthatdidn'tappearinthe
book.IfiguredthatifIwasgoingtowritetheforewordforthe
book,Ishouldaddsomething.Theresult:Iwassimplyunable
tofindanythingmissing.Oh,I'msureyou'llfindsomelittle
tidbityou'vefiguredoutthatdoesn'tappearhere,butinmy
readingofit,Iwasn'tableto.IthoughtforsureI'dcatchthem
onsomethingbut,alas,Ifailed.(And,Isuppose,that'sagood
thing,right?)EverytimeIthoughtIhadtheminamissing
trick,thereiswas,rightthereinprint.Whatthatmeansisthat
you'llhavethebestpossiblereferencebookatyourfingertips.
Ofcourse,youneedtogetyourexpectationssetcorrectly:It's
simplynotpossible,evenina60-pagechapter,todescribethe
entiretyoftheExcelorWordobjectmodel.ButE&Ehavedone
anexcellentjobofpointingoutthebitsthatmakethebiggest


impacton.NETdevelopment.
Ifyou'rereadingthisforewordbeforepurchasingthebook,just
doit.Buythething.Ifyou'vealreadyboughtit,whyareyou
readingthis?Gettotheheartofthematterskipahead,andget
going.Youcanalwaysreadthisstufflater.There'sa
considerablehillaheadofyou,andit'sworththeclimb.Office
developmentusingmanagedcodehashitnewstrideswiththe

releaseofVisualStudio2005.Ican'twaittotakeadvantageof
thisbooktobuildgreatapplications.
KenGetz,seniorconsultant
MCWTechnologies




Preface
IN2002,THEfirstreleaseofVisualStudio.NETandthe.NET
Frameworkwasnearingcompletion.AfewofusatMicrosoft
realizedthatOfficeprogrammingwasgoingtomissthe.NET
waveunlesswedidsomethingaboutit.
WhathadcomebeforewasVisualBasicforApplications(VBA),
asimpledevelopmentenvironmentintegratedintoalltheOffice
applications.EachOfficeapplicationhadarichobjectmodel
thatwasaccessedviaatechnologyknownasCOM.Millionsof
developersidentifiedthemselvesas"Officedevelopers"and
usedVBAandtheOfficeCOMobjectmodelstodoeverything
fromautomatingrepetitivetaskstocreatingcompletebusiness
solutionsthatleveragedtherichfeaturesanduserinterfaceof
Office.Thesedevelopersrealizedthattheiruserswerespending
theirdaysinOffice.BybuildingsolutionsthatraninsideOffice,
theynotonlymadetheirusershappy,butalsowereableto
createsolutionsthatdidmoreandcostlessbyreusing
functionalityalreadyavailableintheOfficeapplications.
Unfortunately,becauseofsomelimitationsofVBA,Office
programmingwasstartingtogetabadrap.Solutions
developedinVBAbysmallworkgroupsorindividualswouldgain
momentum,andaprofessionaldeveloperwouldhavetotake

themoverandstartsupportingthem.Toaprofessional
developer,theVBAenvironmentfeltsimpleandlimited,andof
course,itenforcedasinglelanguage:VisualBasic.VBA
embeddedcodeineverycustomizeddocument,whichmadeit
hardtofixbugsandupdatesolutionsbecauseabugwouldget
replicatedindocumentsacrosstheenterprise.Security
weaknessesintheVBAmodelledtoarashofwormsandmacro
virusesthatmadeenterprisesturnVBAoff.
VisualStudio.NETandthe.NETFrameworkprovidedawayto
addressalltheseproblems.Ahugeopportunityexistedtonot


onlycombinetherichnessofthenew.NETFrameworkand
developertoolswiththepowerfulplatformthatOfficehas
alwaysprovidedfordevelopers,butalsosolvetheproblems
thatwereplaguingVBA.TheresultofthisrealizationwasVisual
StudioToolsforOffice(VSTO).
ThefirstversionofVSTOwassimple,butitaccomplishedthe
keygoaloflettingprofessionaldevelopersusethefullpowerof
VisualStudio.NETandthe.NETFrameworktoputcodebehind
Excel2003andWord2003documentsandtemplates.Itlet
professionaldevelopersdevelopOfficesolutionsinVisualBasic
2005andC#.Itsolvedtheproblemofembeddedcodeby
linkingadocumenttoa.NETassemblyinsteadofembedding
the.NETassemblyinthedocument.Italsointroducedanew
securitymodelthatused.NETcode-accesssecuritytoprevent
wormsandmacroviruses.
ThesecondversionofVSTO,knownasVSTO2005theversionof
VSTOcoveredbythisbookisevenmoreambitious.Itbrings
withitfunctionalityneverbeforeavailabletotheOffice

developer,suchasdatabindinganddata/viewseparation,
design-timeviewsofExcelandWorddocumentsinsideVisual
Studio,richsupportforWindowsFormscontrolsinthe
document,theabilitytocreatecustomOfficetaskpanes,
server-sideprogrammingsupportagainstOfficeandthat'sjust
scratchingthesurface.AlthoughtheprimarytargetofVSTOis
theprofessionaldeveloper,thatdoesnotmeanthatbuildingan
OfficesolutionwithVSTOisrocketscience.VSTOmakesit
possibletocreateveryrichapplicationswithjustafewlinesof
code.
Thisbooktriestoputintooneplacealltheinformationyou
needtosucceedusingVSTOtoprogramagainstWord2003,
Excel2003,Outlook2003,andInfoPath2003.Itintroducesthe
Officeobjectmodelsandcoversthemostcommonlyused
objectsinthoseobjectmodels.Inaddition,thisbookwillhelp
youavoidsomepitfallsthatresultfromtheCOMoriginsofthe
Officeobjectmodels.(CompleteVisualBasic2005code


samplesareavailableonthebook'sWebpageat
www.awprofessional.com/title/0321411757.)
Thisbookalsoprovidesaninsiderviewofalltherichfeaturesof
VSTO.Weparticipatedinthedesignandimplementationof
manyofthesefeatures.Wecan,therefore,speakfromthe
uniqueperspectiveoflivingandbreathingVSTOforthepast
threeyears.ProgrammingOfficeusingVSTOispowerfuland
fun.WehopeyouenjoyusingVSTOasmuchasweenjoyed
writingaboutitandcreatingit.



Acknowledgments
THOUGHONLYTWOnamesareonthecover,nobookofthis
magnitudegetswrittenwithouttheeffortsofmanydedicated
individuals.
EricCarterwouldliketothankhisentirefamilyforthepatience
theyshowedwhile"Dad"wasworkingonhisbook:Jason,
Hayley,Camilla,Rand,andElizabeth.Extremethanksaredue
tohiswife,Tamsyn,whowaseversupportiveandkept
everythingtogethersomehowduringthiseffort.
EricLippertwouldliketothankhisexcellentwife,Leah,forher
supportandtremendouspatienceoverthemanymonthsthatit
tooktoputthebooktogether.
ManythankstoeveryoneatAddison-Wesleywhomadethis
bookpossible.JoanMurrayandJessicaD'Amicoprovided
expertise,guidance,encouragement,andfeedbackthrough
everystepoftheprocess.StephaneNakibcajoledusforyears
togetabookproposaltogether.Thanksarealsoduetothe
productionandmarketingteamsatAddison-Wesley,especially
JulieNahil,MarieMcKinley,andCurtJohnson.
AhugethankyoutoeveryoneatMicrosoftwhooverthepast
threeyearscontributedtoVisualStudioToolsforOffice.Many
peoplefromdifferentdisciplinesdesign,development,
education,evangelism,management,marketing,and
testingdedicatedtheirpassionandenergytowardbringing
Officedevelopmentintothemanaged-codeworld.Wecouldnot
havewrittenthisbookwithouttheeffortsofallofthem.One
couldnotaskforabettergroupofpeopletohaveas
colleagues.
AconsiderablenumberofindustryexpertsgavetheVSTOteam
valuablefeedbackovertheyears.Manythankstoeveryonewho



camesofartogivesomuchoftheirtimeandexpertiseby
participatinginsoftwaredesignreviewsandusingearly
versionsoftheproduct.TheirsuggestionsmadeVSTOabetter
productthantheoneweoriginallyenvisioned.
WeespeciallythankAndrewClinickandHagenGreenfortheir
importantcontributionstothisbook.
WealsothankRobertGreenforhisassistanceinconverting
listingsfromtheC#booktoVisualBasic2005.
Manythankstoourtechnicalreviewers,whosealwaysconstructivecriticismwasahugehelp.Theyhelpedusremove
ahugenumberoferrorsfromthetext;thosethatremainare
ourown.Thankyou,RufusLittlefield,SiewMoiKhor,Stephen
Styrchak,PaulVick,PaulStubbs,KathleenMcGrath,Misha
Shneerson,MohitGupta,andVernonHui.Finally,we'dalsolike
tothankKDHallman,KenGetz,MikeHernandez,BJHoltgrewe,
andMartinHellerfortheirongoinginsightandsupport.


×