Your SlideShare is downloading. ×
0
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
WP7 HUB_Consuming Data Services
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

WP7 HUB_Consuming Data Services

617

Published on

Fase 3.4

Fase 3.4

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
617
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Note: This demonstration will only work if you are using a display machine with a working network connection.Open the project in Demo 01 Web Scraper using Visual StudioSelect Debug>Run to run the program.Press the Load buttonThe top of the screen should fill with HTML from the web page.Ask the class for another url.Type this into the textbox.Return to Visual Studio and use View>Solution Explorer to open the Solution Explorer if it is not already visible.Open MainPage.xaml.csPut a breakpoint on the following statement in the method client_DownloadStringCompletedif (e.Error == null)Press the Load buttonThe program should stop on the breakpoint.Click in the Visual Studio window to select it and rest the cursor over e.Result. This will show the content of the web page returned.Clear the breakpoint and click run or press F5 to continue.Note that the text appears in the emulator.Stop the program and close the project.
  • Note: This demonstration will only work if you are using a display machine with a working network connection.Open the project Demo 01 Complete Twitter Readerusing Visual StudioSelect Debug>Run to run the program.Show that the screen fills with the two fixed posts.Press the Load buttonThe list should fill up with posts from Twitter.Ask the class for another twitter username.Type this into the textbox.Press Load again, and note that the display changes.Stop the program and close the project.
  • Note: This demonstration is fairly long and complicated. Make sure you have been through it once yourself before doing it in front of a class.Open the project Demo 1a JokeServiceusing Visual StudioOpenSolution Explorer and right click JokeOfTheDayService.svcSelect View in BrowserThis will show the service description in the browser. Click RunThis should open the WCF Test ClientDouble click GetJoke in the navigation tree on the left. This should open up the method in the right hand pane.Click the Invoke button to call the service method.Make the point that the test client is running as a separate program, not attached to the server other than by an HTTP connection.Click OK to move past any security warnings that appear.The right hand pane of the test client will show the return from the method.Leave the service running and open the project in Demo 1b WindowsPhoneJokeClientOpenSolution Explorer and right click JokeOfTheDayService in Service ReferencesSelect Configure Service Reference from the context menu.This will display the Service Reference settings for the service..Show the class the Address, and make the point that it is presently connected to port on the local host.Return to the WCF Test Client and show that the address of the test client is the same as the one in the Address field in the service configuration.Close the Service Reference Settings by clicking CancelRun the Windows Phone Joke Client.Click Load in the emulator to fetch a joke. This should be displayed on the phone.In the Service project open the file JokeOfTheDayService.svc.cs. This contains the service method.Put a breakpoint on the statement:string result = "Invalid strength";In the Windows Phone emulator change the strength value next to the Load button to 1, and then click Load.This should cause the server to hit the breakpoint you set. Hover the mouse over the JokeStrengthand show that it has the value 1, which is what he phone requested.If you want long enough you will find that the Windows Phone application will throw an exception. Ask the class why?Answer: The service will timeout if the response does not arrive soon enough. Make the point that any code that uses a service like this should be able to survive events like these.Stop the Windows Phone client program and close that version of Visual Studio.Clear the breakpoint in the server (for next time) and stop the server program and close Visual Studio.
  • Transcript

    • 1. Consuming Data Services<br />
    • 2. Connectingto a data service<br />
    • 3. Topics<br />Windows Phone applications on a network<br />The role of the Windows Phone emulator<br />Creating network connections<br />Using asynchronous network requests<br />
    • 4. Windows Phone on a network<br />The Windows Phone device is very well connected<br />WIFI<br />3G<br />GPRS<br />All these networks are accessed by programs that use the TCP/IP networking protocol<br />Your program does not have to worry about the underlying communication technology<br />4<br />
    • 5. Phone limitations<br />A mobile phone does not have a working connection at all times<br />Mobile applications that use the network must either “fail gracefully” or provide offline modes for their users<br />Any network request must provide progress information and use timeouts to ensure that a failed network doesn’t cause them to get stuck<br />5<br />
    • 6. Windows Phone networking <br />Windows Phone Silverlight applications and XNA games can use the network<br />But they are not allowed to make “socket” based connections in Version 1.0 of the operating system<br />All network requests must be calls to services that will deliver a result asynchronously<br />The network calls are exactly the same as those provided in the desktop .NET libraries<br />6<br />
    • 7. Asynchronous connections<br />A program will never make a call to the network and then wait for the result<br />This is called synchronous operation, and is not supported by any network calls on the phone<br />Instead a program will make a call to the network to initiate an operation<br />The network object will then call back later with the result of the operation<br />7<br />
    • 8. Asynchronous operation<br />This form of event based operation is exactly the same as the model used by Silverlight to accept user input<br />Silverlight elements can generate program events<br />Button pressed, Text Changed etc<br />A program can bindto these events so that a method is called when an event occurs<br />8<br />
    • 9. Downloading Web Pages<br />To get started we could look at an application to “scrape” text off a web page<br />This can be used to obtain data for display<br />We can also use it to read structured data from the web, of which more later<br />9<br />
    • 10. The WebClient class<br />WebClient client;<br />To start we need something that will do the work for us<br />The .NET WebClient class can be used to fetch information from the internet<br />An instance of the WebClient class represents a single web request<br /> We can use it to read HTML from a given web page<br />10<br />
    • 11. Creating a WebClient<br />// Constructor<br />publicMainPage()<br />{<br />InitializeComponent();<br /> client = newWebClient();<br />client.DownloadStringCompleted += <br />newDownloadStringCompletedEventHandler(<br />client_DownloadStringCompleted);<br />}<br />We can create a WebClient instance in the constructor for our page<br />11<br />
    • 12. Binding to the loaded event<br />// Constructor<br />publicMainPage()<br />{<br />InitializeComponent();<br /> client = newWebClient();<br />client.DownloadStringCompleted += <br />newDownloadStringCompletedEventHandler(<br />client_DownloadStringCompleted);<br />}<br />This statement binds a method to the completed event<br />The method runs after the page is fetched<br />12<br />
    • 13. Displaying the result<br />voidclient_DownloadStringCompleted(object sender, <br />DownloadStringCompletedEventArgs e)<br />{<br />if (e.Error == null)<br /> {<br />pageTextBlock.Text = e.Result;<br /> }<br />}<br />The client_DownloadStringCompletedmethod runs when the page text has arrived<br />It checks for an error and displays the text if there was none<br />13<br />
    • 14. Sending the request<br />privatevoidloadButton_Click(object sender,RoutedEventArgs e)<br />{<br />client.DownloadStringAsync(newUri(urlTextBox.Text));<br />}<br />This is the event handler for the button that is pressed to start the transaction<br />It calls the DownloadStringAsync method on the WebClient to start the download<br />It is given a Uri to download from<br />14<br />
    • 15. The Uri <br />privatevoidloadButton_Click(object sender,RoutedEventArgs e)<br />{<br />client.DownloadStringAsync(newUri(urlTextBox.Text));<br />}<br />A Uri instance gives the address of a resource<br />It can be created from a string of text<br />In this program the Uri is created from a TextBox on the user interface <br />15<br />
    • 16. Demo 1: Web Scraping<br />Demo<br />16<br />
    • 17. Review<br />Windows phones can make connections to services over the network<br />All network requests are asynchronous<br />The result of a network request is delivered by an event generated in the client<br />The WebClient class provides a very easy way of loading the content of urls<br />17<br />
    • 18. Usinglinqtoreadstructured<br />
    • 19. Topics<br />Structured data and LINQ<br />Databases and objects<br />Database queries and LINQ<br />Creating Silverlight layout templates<br />Databinding to lists<br />Using LINQ queries to produce object collections <br />
    • 20. Reading Twitter XML feeds<br />We can use a WebClient request to read structured data from a web host<br />The Twitter feed information can be supplied as an XML structured data file<br />Our program must pull out some content and display it<br />20<br />
    • 21. Reading the Twitter feed<br />privatevoidloadButton_Click(object sender, RoutedEventArgs e){stringurl = "http://twitter.com/statuses/user_timeline/" +nameTextBox.Text + ".xml";client.DownloadStringAsync(newUri(url));}<br />This code will fetch the XML that describes a Twitter feed<br />The URL contains the Twitter username<br />21<br />
    • 22. XML structured data<br />We have already seen XML in the markup language used by Silverlight to describe pages<br />The XML for a Twitter feed contains elements and properties which are formatted to describe Twitter post information<br />We could write some C# to decode the feed, but we are going to use LINQ instead<br />LINQ stands for Language Integrated Query <br />22<br />
    • 23. LINQ<br />LINQ is a technology that is part of the .NET system libraries<br />It builds on C# language features to provide easy data transfer between structured data storage and the object models used by modern languages<br />It is well worth knowing about<br />23<br />
    • 24. A diversion into databases<br />If you want to store large amounts of structured data you will not write a system to do this<br />Instead you will use a database<br />The database manages the data for you, and your program will send commands to it to add, remove and search for data<br />24<br />
    • 25. A simple Database<br />We can start by considering a simple sales database<br />This is the customer table<br />Each row describes a single customer<br />25<br />
    • 26. Two other tables<br />Sales table<br />Product Table<br />26<br />
    • 27. Using the database<br />We can combine the information in the tables to obtain transaction details<br />Rob has Customer ID 123456<br />Customer ID 123456 ordered product ID1001<br />1001 is the product ID of a Windows Phone<br />Rob bought a Windows Phone<br />We get the database to do this for us by issuing queries to it<br />27<br />
    • 28. Database queries<br />SELECT * FROM Orders WHERE CustomerID = "123456"<br />This SQL query will create a table that contains all the orders placed by Rob<br />This result can then be used as the basis of another query<br />Database queries are much easier to create than the equivalent program statements to work through the data<br />28<br />
    • 29. A C# sales database<br />publicclassCustomer{publicstring Name {get; set;}publicstring Address { get; set; }stringBankDetails { get; set; }publicint ID { get; set; }}<br />If we wrote a C# program to store the sales database our starting point would be class designs<br />The above class holds Customer information <br />29<br />
    • 30. Holding multiple Customers<br />List<Customer> Customers = newList<Customer>();<br />Once we have a class that contains the required data we can create collections of that object<br />Above we have created a list of customers<br />We can then store customers in the list by adding them to it<br />30<br />
    • 31. Searching for customers<br />publicList<Order> FindCustomerOrders(intCustomerID){List<Order> result = newList<Order>();foreach ( Orderorderin Orders ) {if (order.CustomerID == CustomerID) {result.Add(order); } }return result;}<br />This is the C# code that implements the SQL query we saw earlier<br />31<br />
    • 32. Databases and objects<br />If object-oriented programs and databases are to work together we need something to convert from database tables to objects and back<br />We can do this by creating of “glue” code that creates objects and stores them back in tables<br />However, this task is made much easier by LINQ<br />32<br />
    • 33. A LINQ query<br />varorderQueryResult =from order indb.Orderswhereorder.CustomerID == "123456"select order;<br />This is the LINQ code that implements the SQL query we saw earlier<br />It does not look like legal program statements, but it compiles perfectly<br />It is worth a closer look<br />33<br />
    • 34. Query result<br />varorderQueryResult=from order indb.Orderswhereorder.CustomerID == "123456"select order;<br />The query returns a result which is given the type var<br />var means “a type which works here”<br />The type of a var variable depends on the context of the declaration<br />In this case orderQueryResult will hold a collection of var objects that look like orders<br />34<br />
    • 35. Iteration source<br />varorderQueryResult=from order indb.Orderswhereorder.CustomerID == "123456"select order;<br />This sets up the iteration through the elements in a table<br />The db variable represents the database connection and we are using the Orders table from that database<br />35<br />
    • 36. Restriction operation<br />varorderQueryResult=from order indb.Orderswhereorder.CustomerID == "123456"select order;<br />This is the restriction operation that identifies the orders to be selected from the table<br />In this case we are looking for orders with the CustomerID of 123456<br />36<br />
    • 37. Selection operation<br />varorderQueryResult=from order indb.Orderswhereorder.CustomerID == "123456"select order;<br />This identifies the item to be selected and added to the result when the restriction operation succeeds<br />This means that we will get a collection of var results that look like order objects<br />We can then use these objects in our program<br />37<br />
    • 38. Databases on Windows Phone<br />LINQ is a great way to combine object oriented code and databases<br />Unfortunately the present version of Windows Phone does not have database support<br />But it does contain the LINQ libraries<br />This would seem a strange design choice<br />Fortunately LINQ can also be used to read structured data and create objects from it<br />38<br />
    • 39. Twitter XML<br /><?xmlversion="1.0"encoding="UTF-8"?><statusestype="array"><status> <created_at>Tue Oct 12 11:57:37 +0000 2010</created_at><text> Hello from Twitter.</text><user> <id>2479801</id> <name>Rob Miles</name><profile_background_image_url> http://s.twimg.com/a/1286/images/themes/theme1/bg.png</profile_background_image_url></user></status></statuses><br />This is an abridged Twitter status XML file<br />39<br />
    • 40. Performing the query<br />XElementTwitterElement = XElement.Parse(twitterText);<br />The first thing we need to do is get LINQ to create a LINQ XML element or XElement<br />We will be able to perform LINQ operations on the XElement value as if it was a database source<br />The Parse method works through the XML data string returned by the server<br />40<br />
    • 41. Creating the display objects<br />We now have an easy way that we can use LINQ to pull the required data out of the XML feed<br />We want to obtain and display<br />The text of the Twitter post<br />The data of the post<br />The image of the Twitter user<br />Once we have these values we need to display them<br />41<br />
    • 42. Creating a display class<br />publicclassTwitterPost{publicstringPostText { get; set; }publicstringDatePosted { get; set; }publicstringUserImage { get; set; }}<br />This the class that we will actually use to display a post on the screen<br />We will use Silverlight data binding to connect these properties to display elements<br />42<br />
    • 43. Using LINQ to create the display<br />varpostList = from tweet intwitterElements.Descendants("status")selectnewTwitterPost{UserImage = tweet.Element("user"). Element("profile_image_url").Value,PostText = tweet.Element("text").Value,DatePosted = tweet.Element("created_at").Value};<br />This is the LINQ query that will work through the status elements in the XML and create new TwitterPost instances from each status entry<br />43<br />
    • 44. Using LINQ to create the display<br />varpostList = from tweet intwitterElements.Descendants("status")selectnewTwitterPost{UserImage = tweet.Element("user"). Element("profile_image_url").Value,PostText = tweet.Element("text").Value,DatePosted = tweet.Element("created_at").Value};<br />There is no restriction part as we want all the status elements<br />We could add one if we wanted to select particular ones based on a criteria<br />44<br />
    • 45. Finding XML elements<br />varpostList = from tweet intwitterElements.Descendants("status")selectnewTwitterPost{UserImage = tweet.Element("user"). Element("profile_image_url").Value,PostText = tweet.Element("text").Value,DatePosted = tweet.Element("created_at").Value};<br />The Element method locates an element with a particular name<br />It can be used on the element it returns<br />This is how we get the profile image<br />45<br />
    • 46. The postList variable<br />The postList variable is a var type<br />This means that it will be set to the result of an operation that will build the type when it is used<br />In fact postList refers to a list of TwitterPost values<br />Now we need to get that list onto the Phone display<br />46<br />
    • 47. XAML templates<br />What we really want to do is bind our list of Twitter posts to some kind of list on the phone<br />It turns out that this is very easy to do<br />We can create a list template that describes the layout of some Silverlight elements that can be bound to properties in the TwitterPost class<br />47<br />
    • 48. What the display will look like<br />I want each twitter post to look like this<br />A picture on the left hand side, with the post date and content arranged to the right of this<br />We can use the Silverlight StackPanel element to lay this out for us<br />48<br />
    • 49. Outer StackPanel<br /><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel><br />The outer stack panel lays out elements across the list element <br />49<br />
    • 50. Horizontal Stack Panel<br />There are two elements in the horizontal stack panel<br />One is the image of the Twitter user<br />The other will contain the date and the post text<br />50<br />
    • 51. User Image<br /><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel><br />This is the image of the Twitter user<br />The source property gives the url of the image to be displayed<br />51<br />
    • 52. Post details<br /><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel><br />The second element is another Stack Panel<br />This contains the post date above the post text<br />52<br />
    • 53. Post details<br /><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel><br />This is the date posted element<br />It binds to the DatePosted property in a TwitterPost value<br />53<br />
    • 54. Post text<br /><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel><br />This is the post text itself<br />This is set to wrap around the text area<br />54<br />
    • 55. StackPanel<br />A StackPanel will automatically arrange the items that are placed within it<br />We have seen that we can place one StackPanel value inside another<br />They allow you to create layouts that position themselves automatically<br />55<br />
    • 56. The Complete ListBox template<br /><ListBox Height="442"HorizontalAlignment="Left" Name="tweetsListBox"VerticalAlignment="Top" Width="468"><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox><br />56<br />
    • 57. A ListBox display template<br /><ListBox Height="442"HorizontalAlignment="Left" Name="tweetsListBox"VerticalAlignment="Top" Width="468"><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox><br />The ListBox is called tweetsListbox<br />57<br />
    • 58. A ListBox display template<br /><ListBox Height="442"HorizontalAlignment="Left" Name="tweetsListBox"VerticalAlignment="Top" Width="468"><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox><br />It contains an item template for each list item the box is going to display<br />58<br />
    • 59. A ListBox display template<br /><ListBox Height="442"HorizontalAlignment="Left" Name="tweetsListBox"VerticalAlignment="Top" Width="468"><ListBox.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal" Height="132"><Image Source="{BindingUserImage}" Height="73" Width="73" VerticalAlignment="Top"/><StackPanel Width="370"><TextBlock Text="{BindingDatePosted}"Foreground="#FFC8AB14"FontSize="22" /><TextBlock Text="{BindingPostText}"TextWrapping="Wrap"FontSize="24" /></StackPanel></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox><br />This is the StackPanel we created earlier<br />59<br />
    • 60. Putting it all together<br />Now we have a ListBox template for the dislay that will lay out the tweets the way that we want them to appear<br />The next thing is to connect the ListBox to a datasource that contains a collection of TwitterPost objects for display<br />First we can take a look at how such a list could be made<br />60<br />
    • 61. TwitterPost p1 = newTwitterPost{DatePosted = "Tue Oct 12 11:57:37 +0000 2010",UserImage= http://a3.twimg.com/1501/me2_normal.jpg",PostText = "This is a test post from Rob"};TwitterPost p2 = newTwitterPost{DatePosted = "Wed Oct 13 14:21:04 +0000 2010",UserImage= http://a3.twimg.com/1501/me2_normal.jpg",PostText = "This is another test post from Rob"};List<TwitterPost> posts = newList<TwitterPost>();posts.Add(p1);posts.Add(p2);<br />Displaying Lists of Tweets<br />61<br />
    • 62. TwitterPost p1 = newTwitterPost{DatePosted = "Tue Oct 12 11:57:37 +0000 2010",UserImage= http://a3.twimg.com/1501/me2_normal.jpg",PostText = "This is a test post from Rob"};TwitterPost p2 = newTwitterPost{DatePosted = "Wed Oct 13 14:21:04 +0000 2010",UserImage= http://a3.twimg.com/1501/me2_normal.jpg",PostText = "This is another test post from Rob"};List<TwitterPost> posts = newList<TwitterPost>();posts.Add(p1);posts.Add(p2);<br />Displaying Lists of Tweets<br />This code creates two TwitterPost instances<br />62<br />
    • 63. TwitterPost p1 = newTwitterPost{DatePosted = "Tue Oct 12 11:57:37 +0000 2010",UserImage= http://a3.twimg.com/1501/me2_normal.jpg",PostText = "This is a test post from Rob"};TwitterPost p2 = newTwitterPost{DatePosted = "Wed Oct 13 14:21:04 +0000 2010",UserImage= http://a3.twimg.com/1501/me2_normal.jpg",PostText = "This is another test post from Rob"};List<TwitterPost> posts = newList<TwitterPost>();posts.Add(p1);posts.Add(p2);<br />Displaying Lists of Tweets<br />These are then added to a list of posts<br />63<br />
    • 64. Binding an XML data source<br />tweetsListBox.ItemsSource = posts;<br />This sets the ItemSource property of the tweetsListBox to the collection of posts that we just created<br />Data binding will do the rest for us<br />64<br />
    • 65. Binding to the twitter data <br />tweetsListBox.ItemsSource = postList;<br />To see the posts loaded from the Twitter feed we use the list created by the LINQ query<br />The list will expand to fill the display and provide scrolling support if you want to view the rest of the items<br />65<br />
    • 66. Demo 1: Twitter viewer<br />Demo<br />66<br />
    • 67. Review<br />Web requests can return structured data in XML format<br />The Language Integrated Query (LINQ) tools provide a way of converting structured data into objects<br />LINQ can decode an XML document and create objects with data properties<br />Collections of objects can be bound to Silverlight lists which contain display templates<br />67<br />
    • 68. Usingnetworkservices<br />
    • 69. Topics<br />Creating a network service<br />Proxy objects and services<br />Service contracts and interfaces<br />Creating a client<br />Adding a service reference to a project<br />Connecting to a service<br />
    • 70. Creating services<br />Up until now all our applications have consumed services provided by other people<br />Now we are going to learn how to create services of our own and consume them on the Windows Phone<br />We are going to use the Windows Communications Framework (WCF) to do this<br />70<br />
    • 71. Services and proxies<br />The service infrastructure hides the nature of the network connection from both the server and the client<br />The server contains methods that are called to provide the service<br />The client calls methods on a proxy object that represents the service<br />71<br />
    • 72. Creating a Service<br />A service is a Visual Studio project like any other<br />It can run in a test environment on the development machine<br />72<br />
    • 73. The “Joke of the day” service <br />[ServiceContract]publicinterfaceIJokeOfTheDayService{ [OperationContract]stringGetJoke(intjokeStrength);}<br />The “Joke of the day” service contains a single method that accepts an integer and returns a string containing a joke of that “strength”<br />73<br />
    • 74. Contract attributes<br />[ServiceContract]publicinterfaceIJokeOfTheDayService{ [OperationContract]stringGetJoke(intjokeStrength);}<br />The [ServiceContract] and [OperationContract] attributes are used by the build process to generate the service descriptions<br />74<br />
    • 75. The “Joke of the day” method<br />publicclassJokeOfTheDayService : IJokeOfTheDayService{publicstringGetJoke(intjokeStrength) {string result = "Invalid strength";switch (jokeStrength) {case0: result = "Joke 0 text";break;case1: result = "Joke 1text";break;case 2: result = "Joke 2 text";break; }return result; }}<br />The [ServiceContract] and [OperationContract] attributes are used by the build process to generate the service descriptions<br />75<br />
    • 76. Joke of the day service<br />We can test the service by issuing calls on the methods from the WCF Test Client<br />This runs as part of the service project <br />76<br />
    • 77. Joke of the day service description<br />The service also provides a service description that can be used to create clients that use it<br />77<br />
    • 78. Creating a Service Reference<br />A service reference is added alongside dll references that a project uses<br />It will be added to the Visual Studio project<br />We manage the service properties from Solution Explorer and the Properties Pane<br />78<br />
    • 79. Browsing for a service<br />We enter the address of the service and Visual Studio downloads the service description<br />79<br />
    • 80. Service reference management<br />Once a service has been added it appears in the project<br />A given project can connect to multiple services<br />80<br />
    • 81. Making a proxy object<br />JokeOfTheDayService.JokeOfTheDayServiceClientjokeService;// ConstructorpublicMainPage(){InitializeComponent();<br />jokeService = newJokeOfTheDayService.JokeOfTheDayServiceClient();jokeService.GetJokeCompleted+= <br /> newEventHandler<JokeOfTheDayService.<br />GetJokeCompletedEventArgs> (jokeService_GetJokeCompleted);}<br />The proxy object provides the link between the client application and the service providing the resource<br />81<br />
    • 82. Making a proxy object<br />JokeOfTheDayService.JokeOfTheDayServiceClientjokeService;// ConstructorpublicMainPage(){InitializeComponent();<br />jokeService = newJokeOfTheDayService.JokeOfTheDayServiceClient();jokeService.GetJokeCompleted+= <br /> newEventHandler<JokeOfTheDayService.<br />GetJokeCompletedEventArgs> (jokeService_GetJokeCompleted);}<br />Create the service<br />The proxy object provides the link between the client application and the service providing the resource<br />82<br />
    • 83. Making a proxy object<br />JokeOfTheDayService.JokeOfTheDayServiceClientjokeService;// ConstructorpublicMainPage(){InitializeComponent();<br />jokeService = newJokeOfTheDayService.JokeOfTheDayServiceClient();jokeService.GetJokeCompleted+= <br /> newEventHandler<JokeOfTheDayService.<br />GetJokeCompletedEventArgs> (jokeService_GetJokeCompleted);}<br />Bind to the service completed event<br />The proxy object provides the link between the client application and the service providing the resource<br />83<br />
    • 84. Asynchronous service calls<br />Like every other network mechanism, requests to web services are asynchronous<br />The foreground program sends off the service request<br />When the service completes it fires an event in the program<br />We have to bind an event handler to the service completed message<br />This will display our joke<br />84<br />
    • 85. Displaying the result<br />voidjokeService_GetJokeCompleted(object sender, JokeOfTheDayService.GetJokeCompletedEventArgs e){if (!e.Cancelled) {jokeTextBlock.Text = e.Result; }}<br />This method checks the return arguments to make sure that the call has succeeded<br />If it has, the joke is displayed in a TextBox<br />85<br />
    • 86. Sending the request<br />privatevoidgetJokeButton_Click(object sender,RoutedEventArgs e){int strength = 0;if (int.TryParse(strengthTextBox.Text, out strength)) {jokeService.GetJokeAsync(strength); }}<br />When the button is clicked it loads the requested strength and calls the method on the instance of the service<br />86<br />
    • 87. Errors and Timeouts<br />Network connections are not guaranteed<br />It may be impossible to make a connection to a service<br />Your application should handle this<br />87<br />
    • 88. Demo 1: Joke Service<br />Demo<br />88<br />
    • 89. Review<br />Windows Phone devices can act as clients to servers running C# programs that provide services<br />The network abstracts the client request into a method call in a proxy object<br />A service exposes a description that can be used by Visual Studio to create appropriate proxy objects <br />89<br />
    • 90. Exercise 1: Create a wcf server tostore data<br />
    • 91. Exercise 2: create a windowsphoneclientapplication<br />

    ×