460 likes | 575 Views
Web Service. Web services are a new breed of Web application. They are self-contained, self-describing, modular applications that can be published, located, and invoked across the Web. Web services perform functions, which can be
E N D
Web Service Web services are a new breed of Web application. They are self-contained, self-describing, modular applications that can be published, located, and invoked across the Web. Web services perform functions, which can be anything from simple requests to complicated business processes. … Once a Web service is deployed, other applications (and other Web services) can discover and invoke the deployed service. • Distributed computing model based on asynchronous messaging (XML) – Support dynamic application integration over the Web – Web Services connect computers and devices with each other using the Internet to exchange data and access services – On-the-fly software creation through the use of loosely coupled, reusable software components – Software can be delivered and paid per-use as opposed to packaged products. – Business services can be distributed over the Internet
Web Services Design Principles • Web-based Protocols – Web-services based on HTTP – protocols can traverse firewalls, can work in a heterogeneous environment • Interoperability – SOAP defines a common standard that allows different systems to interoperate • XML-based (XML schema) – machine-readable documents • Modularity – Service Components are useful in themselves, reusable. • Availability – Services are available to systems that wish to use them – Services must be exposed outside of the particular system they are available in • Machine-readable description – used to identify the interface, the location and access information • Implementation-independence – Service interface available independent of the ultimate implementation • Published – Searchable service repositories of service descriptions
DISCO - Discovery <?xml version="1.0" encoding="utf-8"?> <discovery xmlns="http://schemas.xmlsoap.org/disco/"> <contractRef ref="http://www.myserver.com/Demo-5-Service-Types/TypesService.asmx?wsdl" docRef="http://www.myserver.com/Demo-5-Service-Types/TypesService.asmx" xmlns="http://schemas.xmlsoap.org/disco/scl/" /> <soap address="http://www.myserver.com/Demo-5-Service-Types/TypesService.asmx" xmlns:q1="http://www.myserver.com/schemas/ Demo_5_Service_Types/" binding="q1:TypesServiceSoap" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> </discovery>
WSDL • WSDL (Web Services Description Language) • http://localhost/MyService.asmx?wsdl
WSDL examples <?xml version="1.0" encoding="utf-8"?> <definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:s0="http://www.devbg.org/ws/MathService" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" targetNamespace="http://www.devbg.org/ws/MathService" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> … </types> <message name="AddSoapIn"> … </message> <portType name="MathServiceSoap"> … </portType> <binding name="MathServiceSoap" … > … </binding> <service name="MathService"> … </service> </definitions>
SOAP – protocol • SOAP (Simple Object Access Protocol) • Едно SOAP съобщение се състои от: • SOAP header • SOAPbody • HTTP • firewall
SOAP request <?xml version="1.0" encoding="utf-8"?> <soap:Envelope 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/"> <soap:Body> <CalcDistance xmlns="http://www.devbg.org/Calc"> <p1> <x>4</x> <y>5</y> </p1> <p2> <x>7</x> <y>-3</y> </p2> </CalcDistance> </soap:Body> </soap:Envelope>
SOAP response <?xml version="1.0" encoding="utf-8"?> <soap:Envelope 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/"> <soap:Body> <CalcDistanceResponse xmlns="http://www.devbg.org/Calc/"> <CalcDistanceResult> 8,54400374531753 </CalcDistanceResult> </CalcDistanceResponse> </soap:Body> </soap:Envelope>
Structure Източник: MSDN
Message SOAP Interface WSDL Schema XSD Data XML Transport HTTP
HTTP, XML, XSD • HTTP • XML • XSD
Enterprise Application SOAP пакети ADO .NET Web услуга Back End (база данни) Front End (клиент)
.NET Enterprise App • 3 level: • (Front End) • (Business Tier) • ASP.NET Web service (Back End) (MS SQL Server, Oracle, DB2)
SOAP заявка SOAP отговор ASP.NET Web Service Arch. Клиентскикод ASP.NET Web услуга [WebMethod] public string Blah() {…} Платформа (.NET / Java/PHP / Perl) ASP.NET работен процес ISAPI филтър Common Language Runtime IIS ОС Операционна система (Win2000, WinXP, Win2003)
CreateWeb Service • .NET Framework <%@ WebService Language="C#" Class="SomeService" %> [WebMethod] public void SomeMethod(…) { … }
Demo-1-AddService.asmx <%@ WebService Language="C#" Class="AddService" %> using System; using System.Web.Services; public class AddService : WebService { [WebMethod] public int Add(int a, int b) { return a + b; } } Web-Service – Example
Publish WS • C:\Inetpub\wwwroot
Demo #1 • IIS
Web Service .NET типове SOAP пакети прокси Web услуга клиент
Web Service andVS.NET • Step 1 - *.sln file • Step 2 - *.asmx file • Step 3 – virtual dir in IIS C:\Documents and Settings\<your user name>\ My Documents\Visual Studio Projects\ <WebServiceName>\<WebServiceName>.sln C:\Inetput\wwwroot\<WebAppName> <WebServiceName>.csproj, <WebServiceName>.asmx, <WebServiceName>.asmx.cs, <WebServiceName>.resx, Web.config, Global.asax, Global.asax.cs
Demo #3 • VS.NET
Demo #4 • VS.NET – Add Web Reference
Attribute Web Service • Attribute[WebService] • Namespace • Name • Description Attribute[WebMethod] • Description –
Attribute - Example [WebService( Description="Demo Web service –" + " demonstratescomplex type marshalling.", Namespace="http://www.devbg.org/services/" + "Demo_5_Service_Types/2004/12/17", Name="Demo 5 - Service Types")] public class TypesService : System.Web.Services.WebService { ... [WebMethod( Description="Returns the list of" + "currently active issues.", EnableSession=true)] public Issue[] GetIssues(){…} ... }
Demo #6 • Прехвърляне на сложни типове – клиент за Web услугата
Изпълнение нa SQL заявка Извикване на Web услуга DB Резултат от SQL заявка XML DataSet База от данни Web услуга DataSet Заявки за нанасянена промените Промяна на даннипрез XML DataSet Клиент WS & DataBase
Demo #10 • Web Service & DB
Session • Session – • Application – [WebMethod(EnableSession=true)] MyService myService = new MyService(); myService.CookieContainer = new System.Net.CookieContainer();
Demo #12 • Session
Session Security • Authentication [WebMethod(EnableSession=true, Description = "Checks given login and creates a session.")] public void Login(string aUser, string aPassword) { if ( user/pass is valid ) { Session["user"] = aUser; } else { throw new Exception("Ivalid login!"); } }
Session Security • Add User: [WebMethod(EnableSession=true, Description = "This method requires active session.")] public string GetProtectedData() { string user = (string) Session["user"]; if (user!= null) { return "This is protected data!"; } else { throw new Exception("Access denied!"); } }
Изключенията в Web услугите • Когато Web услуга хвърли изключение, клиентът получава SoapException • Оригиналният тип на изключението се губи • Губят се вложените (inner) изключения • Запазва се текстът (свойството Message) • За да връщаме информация за проблем, възникнал в Web метод: • Дефинираме изброен тип (enum), съдържащ възможните грешки • Връщаме от Web метода код на грешка – инстанция на изброения тип • Клиентът проверява кода за грешка
Web Serviec and HTML Page #1 <form target="_blank" action= 'http://localhost:14572/WebSite10/Service.asmx/FahrenheitToCelsius' method="POST"> <table> <tr> <td>Fahrenheit to Celsius:</td> <td><input class="frmInput" type="text" size="30" name="Fahrenheit"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"></td> </tr> </table> </form>
Web Serviec and HTML Page <form target="_blank" action= 'http://localhost:14572/WebSite10/Service.asmx/CelsiusToFahrenheit' method="POST"> <table> <tr> <td>Celsius to Fahrenheit:</td> <td><input class="frmInput" type="text" size="30" name="Celsius"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"></td> </tr> </table> </form>
<form target="_blank" action='http://localhost:1036/WebSite1/Service.asmx/FahrenheitToCelsius' method="POST"> <table> <tr> <td>Fahrenheit to Celsius:</td> <td><input class="frmInput" type="text" size="30" name="Fahrenheit"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"></td> </tr> </table> </form> <form target="_blank" action='http://localhost:1036/WebSite1/Service.asmx/CelsiusToFahrenheit' method="POST"> <table> <tr> <td>Celsius to Fahrenheit:</td> <td><input class="frmInput" type="text" size="30" name="Celsius"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"></td> </tr> </table> </form> test <form target="_blank" action='http://localhost:1036/WebSite1/Service.asmx/FahrenheitToCelsius' method="POST"> <table> <tr> <td>Fahrenheit to Celsius:</td> <td><input class="frmInput" type="text" size="30" name="Fahrenheit"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Submit" class="button"></td> </tr> </table> </form>