WP7 HUB_Consuming Data Services

  • 572 views
Uploaded on

Fase 3.4

Fase 3.4

More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
572
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

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