Tải bản đầy đủ - 0 (trang)
Simple C# Web Service and Visual Studio.NET

Simple C# Web Service and Visual Studio.NET

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



Figure6.4:DesignmodeforcreatingWebServicesinVisual

Studio.

Onceyouareinthecodewindow,thereisalotofcodealready

generatedforyou.Thefollowingcodesampleshowsthisgenerated

code.

Thefirstthingstonoticeinthesampleareallthe“using”statements.

Thesearethenamespaces(knownas“includes”inC++or“imports”in

Java)thatMicrosoftusestomaketheservicespossible.These

namespacesareusedbythecodegeneratedforyou;youdon’treally

needtoworryaboutthem.

Nextthere’sthenamespacedefinitionforthisservice.Rightnowthis

codesampleusesthedefaultthatMicrosoftassigned,whichis

WebService1.Youcanignoremuchoftherestofthecodebecauseit

initializesanddestroystheobjectsthatworkbehindthescenestomake

theWebServicepossible.

NoticethehelloworldexampleMicrosoftincludedinthecode.

usingSystem;

usingSystem.Collections;

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Diagnostics;



usingSystem.Web;

usingSystem.Web.Services;



namespaceWebService1

{

///

///SummarydescriptionforService1.

///


publicclassService1:System.Web.Services.WebService

{

publicService1()

{

//CODEGEN:ThiscallisrequiredbytheASP.N

ServicesDesigner

InitializeComponent();

}

#regionComponentDesignergeneratedcode

//RequiredbytheWebServicesDesigner

privateIContainercomponents=null;



///

///RequiredmethodforDesignersupport-donotm

///thecontentsofthismethodwiththecodeedito

///


privatevoidInitializeComponent()

{

}

///

///Cleanupanyresourcesbeingused.

///


protectedoverridevoidDispose(booldisposing)

{

if(disposing&&components!=null)

{



components.Dispose();

}

base.Dispose(disposing);

}

#endregion



//WEBSERVICEEXAMPLE

//TheHelloWorld()exampleservicereturnsthestr

//HelloWorld

//Tobuild,uncommentthefollowinglinesthensav

//buildtheproject

//TotestthisWebService,pressF5

//[WebMethod]

//publicstringHelloWorld()

//{

//return"HelloWorld";

//}

}

}

Thestockquoteexampleinthischapterreallywon’tlookupstock

quotes,butwilljustprovideyouwithavalueforoneparticularsymbol

andthenanegativenumberforallothervalues.Theexamplesinthis

chapteraresimpleandmeantonlytointroduceyoutothebasic

concepts.

TomodifytheserviceMicrosoftcreatesforyou,firstchangethe

namespacetosomethingthatisappropriateforyourenvironment.Inthis

example,thenamespacechosenisStockQuote.Thenskipdownto

wherethecodestates[WebMethod].Youcancommentoutthecodeat

thatpointandaddthefollowingcode.

[WebMethod]

publicdoubleGetTestQuote(stringsymbol)

{

doublestockValue=55.95;



doubleempty=-1;

if(symbol=="C")

{

returnstockValue;

}

else

{

returnempty;

}

}

Noticethatintheprecedingcodeexampletheonlyrealdifference

betweenthiscodeandthecodeexampleinChapter1istheadditionof

[WebMethod]tothedefinitionofthemethod.Otherthanthat,thecodeis

astandardC#method.

ThecodesimplyreturnsanumericvalueorpriceforthesymbolCand-1

foreveryothersymbolpassedtoit.

AfteraddingthelastcodesnippettoyourWebServicescode,theentire

WebServicecodeshouldnowlooklikethefollowing.

usingSystem;

usingSystem.Collections;

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Diagnostics;

usingSystem.Web;

usingSystem.Web.Services;

//modifiednamespace--Xplatformbook

namespaceStockQuote

{

///

///ThefirstC#WebService

///


publicclassService1:System.Web.Services.WebService



{

publicService1()

{

//CODEGEN:ThiscallisrequiredbytheASP.N

//ServicesDesigner

InitializeComponent();

}

#regionComponentDesignergeneratedcode

//RequiredbytheWebServicesDesigner

privateIContainercomponents=null;



///

///RequiredmethodforDesignersupport-donotm

///thecontentsofthismethodwiththecodeedito

///


privatevoidInitializeComponent()

{

}

///

///Cleanupanyresourcesbeingused.

///


protectedoverridevoidDispose(booldisposing)

{

if(disposing&&components!=null)

{

components.Dispose();

}

base.Dispose(disposing);

}

#endregion



[WebMethod]



publicdoubleGetTestQuote(stringsymbol)

{

doublestockValue=55.95;

doubleempty=-1;

if(symbol=="C")

{

returnstockValue;

}

else

{

returnempty;

}

}

}

}

Under“Debug”inStudio,clickon“StartwithoutDebugging,”whichis

symbolizedwith“!”.ThisexecutestheWebServiceandopensabrowser

windowthatlookslikeFigure6.5.





Figure6.5:Theinformationmadeavailabletothebrowserfrom

Microsoft’s.NETWebServicesimplementation.

Thefirstlinkavailableisthelinktotheservicedescription,whichisthe



WSDLfile.AnyMicrosoftWebServicesthathavethe“asmx”extension

simplyneedWSDLpassedasthequerystringinordertoseethe

description.Inthiscase,thisURLgivesustheWSDLfile:

http://localhost/XPlatform/StockQuote/Service1.asmx?WSDL.Figure6.6

showstheWSDLinformationinInternetExplorer.





Figure6.6:HowtheWebServicedisplaysitsWSDL

information.

Note RememberWSDLdescribestheWebServicesoaconsumer,

suchasaWebpageorapplication,knowswhatmethodsand

variablesareavailable.Thisisusedby.NETtocreateaproxy.

Chapter4coversWSDLindetail.

AfterthelinkforWSDL,thereisalinkfortheonemethodavailableinthis

serviceandthat’sGetTestQuote.Thislinkrevealsmethodsoftesting

theservice.Figure6.7displayshowthisoutputlooksinthebrowser.





Figure6.7:OutputinInternetExplorerfortestingtheGetTestQuote

method.

TheinformationonthemethodpageshowsyoutheSOAPrequestsand

response,alongwithadialoguetotesttheimplementation.Forthe

simplestockquoteexample,therequestlookslikethefollowing:

POST/XPlatform/StockQuote/Service1.asmxHTTP/1.1

Host:localhost

Content-Type:text/xml;charset=utf-8

Content-Length:length

SOAPAction:"http://tempuri.org/GetTestQuote"




xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">





string









Noticethatinthisexample,theWebServiceleavesoutthingslikethe

actuallengthandthevaluebeingsent.Bothofthesevaluesvary

dependingontherequestyoumake.

Notethatifyou’recallingthisWebServicefromanotherlanguage,such

asJava,youcouldsendtherequesttotheaddressoftheWebService

andgetthefollowingresponseback.

:

HTTP/1.1200OK

Content-Type:text/xml;charset=utf-8

Content-Length:length




xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">





double







Note RememberthattheSOAPstandarddescribeshowto

encapsulatedatainXMLduringtransmissiontoanodealong

withtheprotocols,suchasHTTP,thatmovethedatatothe

appropriatenode.Formoreinformation,referbacktoChapter

3.

Ifyouenterthesymbol“C”intothetextboxonthispage,you’llgetthe

followingresponseinInternetExplorer.



55.95

Notethattempura.orgisthedefaultnamespacethatVisualStudio.NET

defines.



CreatingWebServiceswiththe.NETFramework

SDK

IfVisualStudio.NETisunavailabletoyou,youcaneasilydownloadthe

.NETFrameworkSDKfromMicrosoft.Thisprovidesyouwithcommand

linecompilersforC#andVisualBasic,alongwithallthelibrariesto

createASP.NETpagesandWebServices.

Youcantakethecodefromthepreviousexample,putitinadirectory

underyourWebroot,andnamethefilewithan“.asmx”extensiononthe

end.Then,bysimplypointingabrowsertotheWebService,thecode

compiles.



Thereisoneminormodificationtobemadetothecodethatinvolves

addingthefollowinglinetothebeginningofthepage.

<%@WebServiceLanguage="C#"Class="StockQuote.XPlatformServ



ThistagindicatestoASP.NETthatthisisaWebServicewritteninC#.

JusttoensurethatyouhavetheentirepictureofhowWebServicecodes

needtolook,thefollowingistheentirecodelistingwiththeASP.NETtag

included.

<%@WebServiceLanguage="C#"Class="StockQuote.XPlatformSer

usingSystem;

usingSystem.Collections;

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Diagnostics;

usingSystem.Web;

usingSystem.Web.Services;

//modifiednamespace--Xplatformbook

namespaceStockQuote

{

///

///ThefirstC#WebService

///


publicclassService1:System.Web.Services.WebService



{

publicService1()

{

//CODEGEN:ThiscallisrequiredbytheASP.N

//ServicesDesigner

InitializeComponent();

}

#regionComponentDesignergeneratedcode

//RequiredbytheWebServicesDesigner

privateIContainercomponents=null;



///

///RequiredmethodforDesignersupport-donotm

///thecontentsofthismethodwiththecodeedito

///


privatevoidInitializeComponent()

{

}

///

///Cleanupanyresourcesbeingused.

///


protectedoverridevoidDispose(booldisposing)

{

if(disposing&&components!=null)

{

components.Dispose();

}

base.Dispose(disposing);

}

#endregion



[WebMethod]



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

Simple C# Web Service and Visual Studio.NET

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

×