• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Microsoft Word - Rest, AJAX, and Web 2.0 in Communication ...
 

Microsoft Word - Rest, AJAX, and Web 2.0 in Communication ...

on

  • 870 views

 

Statistics

Views

Total Views
870
Views on SlideShare
870
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Microsoft Word - Rest, AJAX, and Web 2.0 in Communication ... Microsoft Word - Rest, AJAX, and Web 2.0 in Communication ... Document Transcript

    • Microsoft Virtual Labs ® Rest, AJAX, and Web 2.0 in Windows Communication Framework
    • Rest, AJAX, and Web 2.0 in Communication Framework Table of Contents Rest, AJAX, and Web 2.0 in Communication Framework ....................................................... 1 Exercise 1 WCF Web Programming Model (REST) .....................................................................................................2 Exercise 2 AJAX (JSON) with WCF .......................................................................................................................... 10 Exercise 3 WCF From PHP ......................................................................................................................................... 15
    • Rest, AJAX, and Web 2.0 in Communication Framework Rest, AJAX, and Web 2.0 in Communication Framework Objectives After completing this lab, you will be better able to: Create two different WCF services Use a REST approach for exposing functionality Illustrate how to connect to the same AJAX web service using PHP as the client This walkthrough introduces you to building REST-based services using Scenario Windows Communication Foundation (WCF). During this exercise, you walk through three examples of creating and consuming WCF services without using SOAP. Estimated Time to 60 Minutes Complete This Lab Computers used in this Lab NetFX-TR6 The password for the Administrator account on all computers in this lab is: P2ssw0rd Page 1 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Exercise 1 WCF Web Programming Model (REST) Scenario WCF in .NET 3.5 has added features to its programming model to make it easy to build services which can be invoked using a REST-based approach. In this first exercise you will create a WCF endpoint using this new Web programming model. You’ll expose data about musicians (recording artists) and their recordings (albums) through a URI-based REST mechanism returning XML-formatted data. Tasks Detailed Steps Complete the following a. Select Start | All Programs | Microsoft Visual Studio 2008 | Microsoft Visual task on: Studio 2008 to load the Visual Studio 2008 development environment. b. Inside of Visual Studio 2008 select File | New | Web Site. NetFX-TR6 c. Select Empty Web Site as the template, and ensure that .NET Framework 3.5 is 1. Create a WCF selected at the target framework version. endpoint using this new Web programming model. d. Select Location to be HTTP, then type the following as the URL:http://localhost/MusicWeb, select the Language to be Visual C#, and click OK. e. Right-click on the project node in the Solution Explorer, select Add ASP.NET Folder from the context menu, and select App_Data from the submenu. Page 2 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps f. Repeat the last step, this time selecting App_Code as the ASP.NET Folder to add. g. Right-click on the App_Data folder and select Add Existing Item. Browse to C:LabsWCFRESTData and add the Music.mdf database file. h. Right-click on the App_Code folder and select Add New Item. Select LINQ to SQL classes as the template, and ArtistData.dbml as the Name. Press the Add button. i. Open the Server Explorer (View | Server Explorer), expand Music.mdf, expand the Tables node. j. Drag and drop the artist and album tables onto the Object Relational Designer surface. See the image below. This action generates classes you can use to work with data from the Music database. Page 3 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps k. Right-click on the App_Code folder and select Add New Item. Select Class as the template, and name the class ArtistService.cs. Click Add. l. Open the file ArtistService.cs file. m. After the using statements, add the following using statements: using System.ServiceModel; using System.Runtime.Serialization; using System.Collections.Generic; using System.ServiceModel.Web; using System.ServiceModel.Activation; n. Add a ServiceContract attribute to the top of the ArtistService class. Add an AspNetCompatibilityRequirements attribute, with a RequirementsMode property of AspNetCompatibilityRequirements.Allowed. [ServiceContract()] [AspNetCompatibilityRequirements( RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)] public class ArtistService { } o. After the closing brace of the ArtistService class, add a public class named ArtistResult. Add the DataContract attribute to this class, and set Name property to be “Artist” and the Namespace property to a blank string: [DataContract(Namespace="", Name="Artist")] public class ArtistResult { } Page 4 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps p. Add two public fields to ArtistResult class, both of type string, one named ArtistName, and the other named Link. Add the DataMember attribute to both of these fields. [DataContract(Namespace="",Name="Artist")] public class ArtistResult { [DataMember] public string ArtistName; [DataMember] public string Link; } Note: This is the class that you will be returning from one of the Service’s methods. q. After the ArtistResult class, add another public class that derives from List<string>, this one named AlbumList. r. Add the CollectionDataContract attribute to the AlbumList class. Set its ItemName property to “Album”, and the Namespace property to a blank string. s. Add a default parameterless constructor to AlbumList. t. Add another constructor to AlbumList, this one that takes an IEnumerable<string> parameter, and calls the base class’s constructor. [CollectionDataContract(ItemName="Album",Namespace="")] public class AlbumList : List<string> { public AlbumList() { } public AlbumList(IEnumerable<string> albums):base(albums) { } } u. After the AlbumList class, add another public class, this one named ArtistDetail. Add a DataContract attribute to the ArtistDetail class, and use “Artist” as the value for the Name property and a blank string as the value of the Namespace property. v. Add two public fields, one of type AlbumList named Albums and one of type string named ArtistName. Add the DataMember attribute to both of these fields, and set the Order property of the DataMember attribute on ArtistName to 0 and the Order property of the DataMember attribute on Albums to 1. [DataContract(Namespace="",Name="Artist")] public class ArtistDetail { [DataMember(Order=0)] public string ArtistName; Page 5 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps [DataMember(Order = 1)] public AlbumList Albums; } w. Inside of the ArtistService class add a public method named GetAllArtists that returns an array of ArtistResult. Add the OperationContract attribute to this method. Also add the WebGet attribute to this method and specify the UriTemplate property of the WebGet attribute to be “/”. [OperationContract] [WebGet(UriTemplate = "/")] public ArtistResult[] GetAllArtists() { } Note: In order to implement the GetAllArtists method, you will use LINQ to SQL to query the music database. x. Within the GetAllArtists method, create an instance of the ArtistDataDataContext class, named dc: ArtistDataDataContext dc = new ArtistDataDataContext(); y. Get the URI of the incoming request and put it into a string variable. You can get this value from WebOperationContext.Current.IncomingRequest.UriTemplateMatch.Reque stUri. string currentUrl = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.T oString(); z. Add a LINQ query to get all the artists from the data context, and select it into new instances of ArtistResults, selecting the name from the data and the link by creating a string from the artistname and the currentUrl. Convert the result of the LINQ query to an array and return it. The contents of the GetAllArtists procedure should look like the following: ArtistDataDataContext dc = new ArtistDataDataContext(); string currentUrl = WebOperationContext.Current.IncomingRequest. UriTemplateMatch.RequestUri.ToString(); var result = from anArtist in dc.artists select new ArtistResult { ArtistName = anArtist.artist_name, Link = String.Format("{0}{1}", currentUrl, anArtist.artist_name) }; return result.ToArray(); aa. Inside of the ArtistService class add a public method named GetArtist that returns an ArtistDetail class and takes a string parameter named artist. Add the OperationContract attribute to this method. Also add the WebGet attribute to this method – and specify the UriTemplate property of the WebGet attribute to be “/{artist}”. [OperationContract] [WebGet(UriTemplate = "/{artist}")] public ArtistDetail GetArtist(string artist) { Page 6 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps } bb. Inside of the GetArtist method, create an instance of the ArtistDataDataContext object, named dc. cc. Use the ArtistDataDataContext.artists with a LINQ query to find the particular artist that is being queried. Create an ArtistDetail and use a subquery to fill in the AlbumList property. Return the first item from the collection. The completed contents of the procedure should look like the following: ArtistDataDataContext dc = new ArtistDataDataContext(); var result = from anArtist in dc.artists where anArtist.artist_name == artist select new ArtistDetail { ArtistName = anArtist.artist_name, Albums = new AlbumList( (from albums in anArtist.albums select albums.album_name) ) }; return result.First(); dd. Right-click on the project in the Solution Explorer and select Add New Item. Select Text File as the template, and specify the name as ArtistService.svc. Click Add. See Figure below. ee. Inside of the ArtistService.svc file, add a ServiceHost declaration with the following attributes and properties: Attribute Value Page 7 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps Language C# Service ArtistService Factory System.ServiceModel.Activation.WebServiceHostFactory <%@ ServiceHost Language="C#" Service="ArtistService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %> ff. Save all open files. Right-click on the MusicWeb project in the Solution Explorer and select Build Web Site. gg. Right-click on the ArtistService.svc file in the Solution Explorer and select View in Browser. hh. Your browser window should look similar to this (if you see an error message, refresh the content by pressing F5). Note: Now you have a REST service that returns XML that could be consumed by any REST client (typically that would not be a browser). ii. Click the menu next to the Tools menu item on the Internet Explorer toolbar (>>) and select Web Development Helper. Note: The Web Development Helper is a tracing tool which will allow you to see the requests going from the browser to the WCF Service. jj. Check the checkbox next to Enable Logging. Copy the value of the first Link Page 8 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps element from the browser (http://netfxtr6/MusicWeb/ArtistService.svc/Brian Randell and The Randettes), put that link in the address bar of your browser and press enter. This should take you to the second method. kk. Double-click on the URL in the bottom pane of the Web Development Helper, then click on the Response Content tab in the bottom pane, so you can see what the response looks like. ll. Close the Http Log View dialog. Page 9 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Exercise 2 AJAX (JSON) with WCF Scenario WCF in .NET 3.5 also supports returning JSON serialized data from REST-based Web Services. This makes consuming services from AJAX clients simpler and more efficient than XML. In this section, you’ll create a new service that returns JSON-formatted artist data for use from an ASP.NET page. Tasks Detailed Steps Complete the following a. Right-click on the project in the Solution Explorer and select Add New Item. task on: b. Select Ajax-enabled WCF Service as the template, and name the file ArtistJSONService.svc. Click Add. See Figure below. NetFX-TR6 1. Create a new service that returns JSON- formatted artist data for use from an ASP.NET page c. Open the ArtistJSONService.cs file (in the Solution Explorer – under App_Code). d. Remove all the code and comments inside of the ArtistJSONService class (everything inside of the two curly braces). e. Add a method to the ArtistJSONService named GetAllArtists that returns an array of ArtistResult objects. The code can be the same as the method on the XML Service. [OperationContract] [WebGet()] public ArtistResult[] GetAllArtists() { Page 10 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps string currentUrl = WebOperationContext.Current. IncomingRequest.UriTemplateMatch.RequestUri.ToString(); ArtistDataDataContext dc = new ArtistDataDataContext(); var result = from anArtist in dc.artists select new ArtistResult { ArtistName = anArtist.artist_name, Link = String.Format("{0}{1}", currentUrl, anArtist.artist_name) }; return result.ToArray(); } f. Add a method to the ArtistJSONService named GetArtist that takes a single parameter which is a string named artist. Use the same code from the first exercise to implement this method. [OperationContract] public ArtistDetail GetArtist(string artist) { ArtistDataDataContext dc = new ArtistDataDataContext(); var result = from anArtist in dc.artists where anArtist.artist_name == artist select new ArtistDetail { ArtistName = anArtist.artist_name, Albums = new AlbumList( (from albums in anArtist.albums select albums.album_name)) }; return result.First(); } g. Right-click on the project in the Solution Explorer and select Add New Item. h. Select AJAX Web Form as the template, and name the file ShowArtists.aspx. Click Add. i. Open the ShowArtists.aspx file. j. Expand the ScriptManager element, add a Services element, and add an ending ScriptManager element. <asp:ScriptManager ID="ScriptManager1" runat="server" > <Services> </Services> </asp:ScriptManager> k. Add an asp:ServiceReference element under Services – with a Path attribute value of ~/ArtistJSONService.svc. <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/ArtistJSONService.svc" /> </Services> Page 11 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps </asp:ScriptManager> l. After the ScriptManager end tag, add a select element with an id attribute with a value of “_artists”. Add the onchange attribute and set its value to “artistChanged()” (this is a reference to a JavaScript function you will create later). Add an option element within the select element with a value attribute of “0” and text of “Select an artist…”. <select id="_artists" onchange="artistChanged()"> <option value="0">Select an artist...</option> </select> m. After this select element, add an hr element, and then another select element with the value of “_albums”. <hr /> <select id="_albums"> </select> n. Find the script element near the top of the ShowArtists.aspx page. o. After the end of the pageLoad function, add a function named loadArtists that takes a parameter named results. Get a reference to the _artist select element and loop through the results (this will be a JSON-encoded version of the ArtistResult array) and populate the list of artists. function loadArtists(results) { var dropDown = $get("_artists"); var theOption = null; for(var i=0;i<results.length;i++) { theOption = document.createElement("OPTION"); theOption.text=results[i].ArtistName; theOption.value=results[i].ArtistName; dropDown.add(theOption); } } p. Inside of the pageLoad function, call ArtistJSONService.GetAllArtists and pass the loadArtists method to the function. Note: you will be getting IntelliSense for the ArtistJSONService type. function pageLoad() { ArtistJSONService.GetAllArtists(loadArtists); } q. Save all files, then right-click on ShowArtists.aspx in the Solution Explorer and select View in Browser. r. Click the Enable Logging checkbox in Internet Explorer and refresh the page. s. Double-click on the last URL in the Web Developer Helper to see the request made by the AJAX code in the page for the JSON service. See the image below. Page 12 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps t. In the lower pane of the HTTP Log Viewer dialog box, click the Reponse Content tab. Change the View from JSON to Text to see the raw JSON content. u. Close the dialog box. Leave Internet Explorer running. v. In Visual Studio 2008, open the ShowArtists.aspx file. w. In the script element, add a function named artistChanged. In this method, get both select elements ( “_artists” and “_albums”). Get the current value of the “_artists” select element. Reset the “_albums” select. Use the GetArtist method on the ArtistJSONService and pass the value of the “_artists” select and a token of loadAlbums: function artistChanged() { var dropDown = $get("_artists"); Page 13 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps var artist = dropDown.value; var dropDown2 = $get("_albums"); dropDown2.options.length=0; if(artist!=0) { ArtistJSONService.GetArtist(artist,loadAlbums); } } x. Create a loadAlbums function that takes a parameter named results. Implement this function by looping through the Albums property of the result parameter (this will be a JSON-encoded version of the ArtistResult type). Save the ShowArtists.aspx file when you’re done. function loadAlbums(results) { var dropDown = $get("_albums"); var theOption = null; for(var i=0;i<results.Albums.length;i++) { theOption = document.createElement("OPTION"); theOption.text=results.Albums[i]; theOption.value=results.Albums[i]; dropDown.add(theOption); } } y. Go back to Internet Explorer and refresh the page. You will be able to change the value of the artist selected, and the album should change. You can use the Web Development Helper to view the interaction with the Service. Page 14 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Exercise 3 WCF From PHP Scenario In this exercise, you’ll create a PHP page that uses the JSON-based WCF Service you built in the last exercise to get data to build its page. Tasks Detailed Steps Complete the following a. Go back to Visual Studio 2008. Right-click on the project in the Solution task on: Explorer and select Add New Item. b. In the Add New Item dialog, select Text File as the template type, and use NetFX-TR6 PHPUsingWCF.php as the Name. Press the Add button. 1. Create a PHP page c. Paste the code below into the PHP file. that uses the JSON- <html> based WCF Service <body> <h1><?php $request = "http://localhost/MusicWeb/ArtistJSONService.svc/GetAllArtist s"; $response = file_get_contents($request); $jsonobj = json_decode($response); echo("<select>"); foreach($jsonobj->d as $value) { echo("<option>"); echo($value->ArtistName); echo("</option>"); } echo("</select>"); ?></h1> </body> </html> d. Save the file. Go to Internet Explorer and navigate to the URL (http://localhost/MusicWeb/PHPUsingWCF.php) Note: You can’t right-click and select View in Browser with a php file in Visual Studio 2008. e. Verify that the page has rendered with a single select (dropdown) with the name of all the artists. f. You may note in the Web Development Helper that the PHP request to the Service doesn’t appear. This is because that request is happening on the server side (not the client). g. Modify $request item in the PHP file so that the URL for the request goes to port 8080. Page 15 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps $request = "http://localhost:8080/MusicWeb/ArtistJSONService.svc/GetAllA rtists"; h. Save the file. i. Use Windows Explorer to go to C:Labs. j. Double-click on TcpTrace.exe. You should see a dialog box like the one in the image below. Note: TcpTrace will act as a proxy so you can see the PHP request k. Set TcpTrace to listen on port 8080, Destination Server of localhost, and Destination Port of 80. l. Press OK. m. Go back to Internet Explorer and refresh the PHP page. n. Switch to the TcpTrace window. You should see the request the PHP code is making to the JSON-encoded WCF Service. See the image below. Page 16 of 17
    • Rest, AJAX, and Web 2.0 in Communication Framework Tasks Detailed Steps Page 17 of 17