Tải bản đầy đủ - 0 (trang)
Chapter 9. Using Web Services in Excel, Access, and Word

Chapter 9. Using Web Services in Excel, Access, and Word

Tải bản đầy đủ - 0trang

9.1WhatAreWebServices?

Inageneralsense,webservicesareprogramsyoucanaccess

overtheWeb.Intheirbroadestdefinition,toolslikeGoogle,

Amazon,Mapquest,andotherweb-basedapplicationsare

certainlywebservices.Moretypically,webservices,asopposed

totheregularWeb,areaboutprogram-to-program

communication.Websitescanmakeinformationavailableto

otherprograms,andmanyareusingXMLtosparetheother

programsthedifficultiesofprocessingHTML.Overthelast

threeyears,webserviceshasdevelopedintoaspecialtyofits

own,builtonaprotocolcalledSOAP.

SOAPformerlytheSimpleObjectAccessProtocol,butnowan

acronymwithoutanofficialexpansionusesanXMLvocabulary

andasetofrulesforsendingXMLoverHTTP.(HTTP,the

HyperTextTransferProtocol,istheprotocolattheheartofthe

Web,mostcommonlyusedtotransferHTMLfromserversto

clients.)SOAPismostfrequentlyusedasaframeworkfor

sendingremoteprocedurecalls(RPC)betweenprograms,and

that'showtheexamplesinthischapterwilluseit.TheMicrosoft

OfficeWebServicesToolkitcreatescodethatmakesWordor

Excelaclientapplication,capableofcallingSOAP-based

servicesonothercomputers.

Therearetwootherlayerstothewebservicessupportedby

Office.WebServicesDescriptionLanguage(WSDL)providesa

machine-readabledescriptionofawebservice,identifying

thingslikethemethodsitsupportsandtheparametersand

returnvaluesforthosemethods.GivenaWSDLfile,an

application(oraprogrammer)candeterminehowtointeract

withawebservice.TheMicrosoftOfficeWebServicesToolkit

usesWSDLfilestocreateitscode.IftheWSDLfileiswritten

correctly,theresultingcodewillbeabletointeractwiththe

SOAP-basedwebservicesmoothly.



TheWSDLfilewilltelltheToolkitwhatcodetocreate,but

there'sstilloneproblem:theToolkitneedstoknowwhereto

findtheWSDLfile.UDDI(UniversalDescription,Discovery,and

Integration)isdesignedtohelpwiththisproblembyprovidinga

commonframeworkfordescribingandorganizingwebservices

inpublicorprivatedirectories.UDDIserversstoreinformation

describingservicesandtheirproviders,helpingdevelopersto

findservicestheytrustandcanuse.



Thereareotherwaystoprovideandusewebservices.XML-RPC,

describedathttp://xmlrpc.com/,precededSOAPandprovidessupport

forfunctioncallsoverHTTP.MicrosoftOfficedoesn'tprovidedirect

supportforXML-RPC.



YoucanalsouseHTTPcallstosendXMLbetweenclientsand

serverswithoutusingSOAP,inwhatisoftencalled

RepresentationalStateTransfer,orREST.FormoreonREST,see

http://internet.conveyor.com/RESTwiki/moin.cgi/FrontPage.It's

probablyeasiesttothinkofRESTmuchasyouthinkofthe

Web;itusesbasicHTTPfunctionalitytoexchangeinformation

betweenprogramsandserversmuchthesamewaythat

browsersuseHTTPtoexchangeinformationbetweenbrowsers

andservers.YoucanusesomeREST-basedservicesinOfficeby

combiningHTTPcallswiththebuilt-inXMLfunctionality

describedinearlierchapters,orthroughVBA.



9.2TheMicrosoftOfficeWebServicesToolkit

UnliketherestoftheXMLfunctionalityinWord,Excel,and

Access,ifyouwanttouseSOAP-basedwebservices,you'll

needtodownloadaseparatepackage,theMicrosoftOfficeWeb

ServicesToolkit.(InfoPathhaswebservicessupportbuiltinto

it.)AstheURLforthispackagehaschangedafewtimes,it's

easiesttogoto

http://www.microsoft.com/downloads/search.aspxandsearch

for"OfficeWebServicesToolkit."Separateversionsare

availableforOfficeXPandOffice2003.Onceyou'veinstalledit,

you'llbeabletohaveOfficegenerateVBAcodeforaccessing

andusingwebservices.Microsoft'ssupportforSOAPcomes

withthetoolkit,andhasalsobecomepartofWindowswith

WindowsXP.



ItispossibletocreateVBAcodethataccessesSOAPserviceswithout

usingtheToolkit,butdoingsorequiresmuchgreaterknowledgeof

bothVBAandSOAPthanthischapterassumes.Ifyou'refeeling

intrepid,seeChapter8ofMatthewMacDonald'sOffice2003XMLfor

PowerUsers(APress).



UnliketheotherXMLfeaturesdescribedinthisbook,usingthe

MicrosoftOfficeWebServicesToolkitworksthesameway

acrossapplications,exceptforInfoPath.Onceyou'velearned

howtointeractwithawebserviceinExcel,youcanusethe

samecodetoworkwithitinWordorAccess.Theonlything

thatneedstochangeistheintegrationbetweenyourVBAcode

andtheobjectmodelfortheparticularapplicationand

documentyou'reworkingwith.It'sprobablyeasiesttostart

yourdevelopmentinExcel,astheExcelgridmakesiteasyto

setuptestenvironmentswhereinputsoccupyparticularcells



andoutputsareplacedintoparticularcellsbytheVBAcode.



9.3AccessingaSimpleWebServicefromExcel

Onceyou'veinstalledthetoolkit,youcanstartconnectingyour

spreadsheettowebservices.TogettotheWebService

ReferencesTool(itsnameinsideofalloftheapplications),you'll

needtogotoTools Macro VisualBasicEditor.OntheTools

menuoftheVisualBasicEditor,you'llfindWebServices

References.Selectingthatwillbringupthedialogboxshownin

Figure9-1.



Figure9-1.TheMicrosoftOfficeWebServices

Toolkitinaction



Youcanusethesearchfeaturesinthetopleftofthisdialogto



findservicesthroughMicrosoft'sUDDIservice,oryoucan

chooseinsteadtoenteraURLfortheWSDLfileatthelower

left.ThetoolkitdefaultstoUDDI,andUDDIhostedbyMicrosoft

atthat,asyou'llseeifyouclicktheMorebutton.Ifyou'dliketo

trylookingforaservicethroughUDDI,enterakeywordor

businessnameintheappropriatelocation,andthenclickthe

Searchbuttonatthebottom.Ifyouenter"currency"under

keyword,clicktheMorebutton,andclickSearch,you'llhavea

briefwaitwhilethetoolkitqueriesMicrosoftandthenyou'llsee

somethinglikeFigure9-2.



Figure9-2.SearchingforservicesusingtheUDDI

supportoftheMicrosoftOfficeWebServices

Toolkit



TheCurrencywsserviceofferstwomethods:GetLicRateand



GetRate.(Asthedocumentationforthemisidentical,it's

difficulttosaywhatthedifferenceis.)ClickingtheTestbutton

willletyouvisitapagewhereyoucantesttheservices,ifthe

provideroftheserviceofferstesting.Ifyouweretocheckthe

boxnextto"Currencyws"andclickAdd,thetoolkitwould

generatecodetoletyouaccesstheservice.

Instead,becauseUDDIhasn'treallytakenoff,andmost

consumersofwebservicesareusingtheirownorotherpeople's

privateservices,we'llexperimentwiththeotheroption,the

WebServiceURL.Thisletsyouworkwithanyservicewhose

providersofferaWSDLfiledescribingit,whetherornotit's

beenregisteredwithUDDI.

Youcanfindalistingofpublicservicesathttp://xmethods.net/,

thoughyoushoulddefinitelytesttomakesurethattheservices

stillworkbeforeyouintegratethemwithyourdocuments.Many

servicesalsorequirelicensekeysandsometimeslicense

payments,butforthisexamplewe'lluseonethatisavailable

forfree.ItreturnstheIPaddressforagivendomainname.

We'llstartbytellingExcelwhichservicewe'dliketouse,inthis

case,http://www.cosme.nu/services/dns.php?wsdl.Enterthat

valueintheURL:boxatthebottomleftandclickSearch.A

searchresultfortheDNSservicewillappearinthetopright,as

showninFigure9-3.Checktheboxtoitsleft.



Figure9-3.TellingtheWebServicesToolkitto

generatecodeforaspecificwebservice



ClickingtheAddbuttonwillmakeExcelgenerateVBAcodefor

invokingtheservice,asshowninFigure9-4.



Figure9-4.VBAcodeforaccessingtheDNS

servicegeneratedbytheWebServicesToolkit



Next,closetheVisualBasicEditorandsetupaverysimple

spreadsheetliketheoneshowninFigure9-5.



Figure9-5.Aspreadsheetforaddingwebservices



Todemonstratehowtocallaservice,addabuttonforcalling

theservice.DisplaytheControlToolbarbyright-clickingona

toolbarandchoosingControlToolboxfromthepop-upmenu.

Clickthebuttonicon,andthenclickonthespreadsheet

whereveryou'dlikethebuttontogo.Right-clickthebutton,and

choosePropertiesfromthepop-upmenu.UnderName,enter

GetData;underCaption,enterGetIPAddress.(Thesenames

canbeanythingyoulike.)ClosethePropertiesdialogbox,and



yourspreadsheetshouldlooksomethinglikeFigure9-6.



Figure9-6.Spreadsheetwithbuttonforcalling

webservices



Example9-1.Codeforcallingsimplewebservice

PrivateSubGetData_Click()

DiminfoAsNewclsws_dns

DimnameAsString

DimIPAsString



name=Range("B2").Text





IP=info.wsm_dns(name)



SetIPRange=Range("B3")



IPRange.Value=IP



EndSub



Thiscodeisprettysimple.Itreferencestheobjectthetoolkit

createdforthewebservice,clsws_dns,andcreatesvariables

forthenameandIPaddress.ItcollectsthenamefromcellB2,

callsthewebserviceatwsm_dnswiththenameasan

argument,andthenputsthevaluereturnedintocellB3.The

methodname,wsm_dns,issetbytheWebServicesToolkitand

appearsinthecommentsatthetopofthegeneratedcode,as

youcanseeifyoulookbacktoFigure9-4.

Onceyou'veenteredthiscodeandclosedtheVisualBasic

Editor,youcanthenleavedesignmodebymakingsurethe

triangleandrulericonattheleftoftheControlToolbarisn't

highlighted.Thespreadsheetwillnowletyouenteradomain

nameincellB2.Clickingonthe"GetIPAddress"buttonwill

invokethewebservice,usingthegeneratedwsm_dnsmethod,

andputtheIPaddresscorrespondingtothatdomainnamein

cellB3.Figures9-7and9-8showthisspreadsheetinaction

withdifferentdomainnames.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 9. Using Web Services in Excel, Access, and Word

Tải bản đầy đủ ngay(0 tr)

×
x