XML Web Services - MIT OpenCourseWare

1y ago
33 Views
1 Downloads
288.59 KB
24 Pages
Last View : 17d ago
Last Download : 1m ago
Upload by : Hayden Brunner
Transcription

1.264 Lecture 22XMLWeb servicesNext class: No readings. Exercise due after classUse same Web site today that we started in Lecture 21Also open SQL Server Management Studio1

Recap of XML Basics XML documents hold self-describing data– Hierarchies, objects, database tables can be sent– Extensible, flexible, decided by industry groups, partners XSLT documents can transform or style XMLdocuments– CSS isn’t enough because we want to display tags here DTD files can validate XML documents– URL has the DTD that server or client can use– DTDs are limited: can’t define data types, etc. XSchema (XSD) files preferred to validate XMLdocuments– More structured, more extensible than DTDs Databases can read and write XML– Web servers can send and receive XML as payload inHTTP, much like HTML pages– Microsoft has made XML the markup language in Office– Putting a disruptive technology in place to automatecommerce?2

Exercise 1: XmlDataSource: BookMIT.aspx File- New File - Web Form: BookMIT.aspx Drag XmlDataSource control on page, configure:– Browse for Books.xml– XPath: //booklist/book[Forward slashes, not backward] Drag DataList onto XmlDataSource– Choose XmlDataSource– (View in browser—MS tools only show attributes, not elements) Go to source view, delete all text in ItemTemplate and replacewith: p %# %# %# %# %# %# %# /p XPath("author/first-name")% XPath("author/last-name")% XPath("title") % XPath("price") % XPath("@topic") % XPath("@publicationdate") % XPath("@ISBN") % Save and test (BookMIT2.aspx has nicer format—see download)3

XSLT: XML Stylesheet Language/Transformation XSLT is a language to transform and style XMLdocuments from one form to another– Use for display, especially to show tags, which CSSdoes not do– Use to convert an XML document from one format toanother, in passing it from one organization to another Example on next page transforms Books.xml intoAuthors.xml by selecting just the author tags– XSLT has loops, if statements and is a miniprogramming language to select and transform data– You don’t need to understand the details of XSLT– BookAuthorXSLT.aspx applies Books.xslt to Books.xml See download and example run in class4

Exercise 2: XSLT: Books.xslt ?xml version "1.0" encoding "utf-8" ? xsl:stylesheet xmlns:xsl "http://www.w3.org/1999/XSL/Transform"version "1.0" xsl:template match "/" xsl:element name "Authors" xsl:apply-templates select "//book"/ /xsl:element /xsl:template xsl:template match "book" xsl:element name "Author" xsl:value-of select "author/first-name"/ xsl:text /xsl:text xsl:value-of select "author/last-name"/ /xsl:element /xsl:template /xsl:stylesheet Run BookAuthorXSLT.aspx to apply Books.xslt to Books.xml5

Exercise 3: Simple XSLT File- New File - Web Form: BookMIT3.aspx Drag Xml control on page from the Standard tools– Not an XMLDataSource control Configure it by typing two properties in Source view, or byusing the Properties window to select them:– DocumentSource "Books.xml"– TransformSource "Books.xslt" The XML control will display the authors from the XML file– This is a simple illustration of transforms All of these exercises are illustrative. XML stillrequires some programming, often simple, which isbeyond the scope of this class.6

Exercise 4: Blogs are XML: Blog.aspx %@ Page Language "C#“ (details omitted) % !DOCTYPE html (details omitted) html xmlns "http://www.w3.org/1999/xhtml" head id "Head1" runat "server" title XmlDataSource Blog /title /head body form id "form1" runat "server" asp:DataList ID "D1" Runat "server“ DataSourceID "XmlData1" ItemTemplate %# XPath("title") % br / %# XPath("pubDate") % br / %# XPath("description") % /ItemTemplate /asp:DataList asp:XmlDataSource ID "XmlData1" Runat "server"DataFile "http://www.hanselman.com/blog/feed"XPath "rss/channel/item" /asp:XmlDataSource /form /body /html 7Execute Blog.aspx. Compare with www.hanselman.com in browser.

Exercise 5: Databases and XML Open SQL Server Mgt Studio, use MIT1264 database Type:– SELECT * FROM Customers FOR XML AUTO Generates XML with data as attributes– SELECT * FROM Customers FOR XML AUTO, ELEMENTS Generates XML with data as elements– Place a root tag (e.g., Customerlist ) and end tag aroundthe SQL result set, and we have a valid XML document Can generate the root and end tags with SQL, C#, Java, .– Can also INSERT, UPDATE, DELETE with XML8

XML database insert exampleCREATE PROCEDURE xmlOrderInsert @order ntext ASDECLARE @docHandle int, @OID intEXEC sp xml preparedocument @docHandle OUTPUT, @orderBEGIN TRANSACTIONINSERT INTO Orders( CustomerID, EmployeeID, OrderDate, RequiredDate )SELECT CustomerID, EmployeeID, OrderDate, RequiredDateFROM Openxml( @docHandle, '/Order', 3) WITH ( CustomerID nchar(5),EmployeeID int,OrderDate datetime, RequiredDate datetime)IF @@ERROR 0 BEGIN ROLLBACK TRANSACTION RETURN -100 ENDSET @OID SCOPE IDENTITY()INSERT INTO [Order Details] ( OrderID, ProductID, UnitPrice, Quantity,Discount )SELECT @OID AS [PO ID], ProductID, UnitPrice, Quantity, DiscountFROM OpenXml( @docHandle, '/Order/OrderDetails', 1)WITH( ProductID int, UnitPrice money, Quantity smallint, Discount real)IF @@ERROR 0 BEGIN ROLLBACK TRANSACTION RETURN -101 ENDCOMMIT TRANSACTIONEXEC sp xml removedocument @docHandle SELECT @OID AS [Order ID]GOFrom codeproject.com9

Exercise 6: More databases and XML You can have XML columns in a database– You can query, update and index them One at a time, run:––––xml1.sqlxml2.sqlxml3.sqlxml4.sql What does each do? This is a nice way to store highly variableinformation where standard columns don’t workXML1-4 code from Kiessig, Ultra-Fast ASP.NET10

Solution: Exercise 6 Xml1: Creates XML schema and Products table– Used by Products table to validate XML column Xml2:––––Select all columns from all rowsSelect id, name, props where width existsSelect id, name, width where color of top part is blackSelect id, name, first color where color of legs is chrome Xml3:– Change leg color to silver– Add arm with color white– Remove first color (arm) Xml4: creates index on XML column, path,properties and values– See indexes on Products table in SSMS explorer11

Midpoint summary XML document: snippet of database being sentfrom one Web server to another– Contains tags defined by business, hyperlinks, etc.– Grew from HTML but defines content, not appearance DTD and/or XSD: contains business rules (1-1, 1many, null/not null, etc) to validate XML document XSLT: transforms and styles and XML document– Make change to sent or received XML to meet businessneeds XPath: query language used for XML documents– Same role as SQL12

Simple Object Access Protocol: SOAP SOAP is XML and HTTP– Intent is to use no extra technology for distributedcomputing– SOAP adds some headers to HTTP– SOAP adds new MIME type: text/xml– Adds agreed definitions of data types, mandatoryvalues, etc.– HTTP POST and XML replace complex programs– SOAP is text rather than binary, so it’s much easier tointeroperate across machines and debug it Binary transmissions are not human-readable SOAP can send binary objects like pictures (that arehuman readable)– SOAP is sufficiently efficient for most machine-machinecommunication SOAP is the key component in Web services, orService Oriented Architectures (SOA)13

Web Services Web service provides information in an XMLformat to be used by a client– It does not display the data in a user interface– It is not tied to a specific Web page or document Web services in .NET are on pages with a .asmxextension (not .aspx)– VSW and .NET make writing simple Web services easy– SQL is generally used to generate the XML payload– Web services accept parameters, such as customernumber or order number, to return only data required Parameters are used in the WHERE clause in SQL Web Services Description Language (WSDL)describes a Web service– Automatically created by VSW14

Exercise 7: Web Services in VSW We will create a Web service in a regular Web site– Normally we create a separate project/site for Web services In VSW, open previous Web site, or create new one– File - New File - Web Service: TemperatureService.asmx– Uncheck ‘place code in separate file’. No master page. Type the following code:[WebMethod]public double toCelsius(double tf){return (5.0 / 9.0) * (tf - 32.0);} Save and view in browser: a WSDL page is shown15

Web service example: requestPOST /TemperatureService.asmx HTTP/1.1Host: localhostContent-Type: text/xml; charset utf-8Content-Length: 300SOAPAction: "http://tempuri.org/ToCelsius" ?xml version "1.0"encoding "utf-8"? soap:Envelope xmlns:xsi "http://www.w3.org/2001/XMLSchemainstance" xmlns:xsd "http://www.w3.org/2001/XMLSchema"xmlns:soap "http://schemas.xmlsoap.org/soap/envelope/" soap:Body ToCelsius xmlns "http://tempuri.org/" TF 32.0 /TF /ToCelsius /soap:Body /soap:Envelope 16

Web service example: responseHTTP/1.1 200 OKContent-Type: text/xml; charset utf-8Content-Length: 250 ?xml version "1.0" encoding "utf-8"? soap:Envelope xmlns:xsi "http://www.w3.org/2001/XMLSchemainstance" xmlns:xsd "http://www.w3.org/2001/XMLSchema"xmlns:soap "http://schemas.xmlsoap.org/soap/envelope/" soap:Body ToCelsiusResponse xmlns "http://tempuri.org/" ToCelsiusResult 0.0 /ToCelsiusResult /ToCelsiusResponse /soap:Body /soap:Envelope 17

Web service example 2: database query We wish to query the Parts table for all parts of agiven vendor– The vendor will be a parameter to the Web service– The Web service will use a database connection toexecute the SQL query– It will return an XML document as its result The code is in your Lecture 22 download asProductService.asmx18

Web service example 2: requestPOST /mit1264lecture22/ProductsService.asmx HTTP/1.1Host: localhostContent-Type: text/xml; charset utf-8Content-Length: lengthSOAPAction: "http://tempuri.org/GetProducts" ?xml version "1.0" encoding "utf-8"? soap:Envelope xmlns:xsi "http://www.w3.org/2001/XMLSchemainstance" xmlns:xsd "http://www.w3.org/2001/XMLSchema"xmlns:soap "http://schemas.xmlsoap.org/soap/envelope/" soap:Body GetProducts xmlns "http://tempuri.org/" Vendor string /Vendor /GetProducts /soap:Body /soap:Envelope 19

ProductService.asmx %@ WebService Language "C#" Class "ProductService" % using System; // and other ‘using’ directives[WebService(Namespace To WsiProfiles.BasicProfile1 1)]public class ProductService : System.Web.Services.WebService {[WebMethod]public DataSet GetProducts(string Vendor) {SqlConnection con1264 new SqlConnection(// Connect to db"Data Source .\\SQLEXPRESS; Password xxx;User ID yyy;Initial Catalog MIT1264");SqlDataAdapter dad1264 new SqlDataAdapter("SELECT * FROMParts WHERE Vendor @Vendor", con1264);// Create querydad1264.SelectCommand.Parameters.Add(new SqlParameter("@Vendor", Vendor));// Add parameterDataSet dstProducts new DataSet(); // Create output objectdad1264.Fill(dstProducts, "Products");// Run queryreturn dstProducts;}}20

Web service example 2: response21

Exercise 8: Web service Change the connection string in ProductServiceas needed:Data Source .\\SQLEXPRESS; Password xxx;User ID yyy;Initial Catalog MIT1264 Modify the Web service to return parts andvendors only if the part ID is 1000 or greater– Modify the connection string to log into your database22

Solution "SELECT * FROM Parts WHERE Vendor @Vendor AND partID 1000"23

MIT OpenCourseWarehttp://ocw.mit.edu1.264J / ESD.264J Database, Internet, and Systems Integration TechnologiesFall 2013For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

Web Services Web service provides information in an XML format to be used by a client –It does not display the data in a user interface –It is not tied to a specific Web page or document Web services in .NET are on pages with a .asmx extension (not .aspx) –VSW and .NET make writing simple Web services easy