4. Networking on Windows Phone
• Support for networking features
• Windows Communication Foundation (WCF)
• HttpWebRequest
• WebClient
• Sockets
• Full HTTP header access on requests
• NTLM authentication
4
5. New Features in WP8
• Two different Networking APIs
• System.Net – Windows Phone 7.1 API, upgraded with new features
• Windows.Networking.Sockets – WinRT API adapted for Windows Phone
• Support for IPV6
• Support for the 128-bit addressing system added to System.Net.Sockets and also is
supported in Windows.Networking.Sockets
• NTLM and Kerberos authentication support
• Incoming Sockets
• Listener sockets supported in both System.Net and in Windows.Networking
• Winsock support
• Winsock supported for native development
8/16/2014 5
7. Async support in WP8 Networking APIs
• C# 5.0 includes the async and await keywords to ease writing of asynchronous
code
• In desktop .NET 4.5, and in Windows 8 .NET for Windows Store Apps, new
Task-based methods allow networking calls as an asynchronous operation
using a Task object
• HttpClient API
• WebClient.DownloadStringTaskAsync(), DownloadFileTaskAsync(),
UploadStringTaskAsync() etc
• HttpWebRequest.GetResponseAsync()
• These methods are not supported on Windows Phone 8
• Task-based networking using WebClient and HttpWebRequest still possible using
TaskFactory.FromAsync()and extension methods
• Coming up later…
8/16/2014 7
9. • In Windows Phone 7.x, the emulator shared the networking of the Host
PC
•You could host services on your PC and access them from your code using
http://localhost...
• In Windows Phone 8, the emulator is a Virtual machine running under
Hyper-V
•You cannot access services on your PC using http://localhost...
•You must use the correct host name or raw IP address of your host PC in URIs
WP8 Emulator and localhost
8/16/2014
10. • If you host your web sites or services in IIS, you must open your firewall
for incoming HTTP requests
Configuring Web Sites Running in Local IIS 8
Firewall
8/16/2014
11. • If your service is a WCF service, you must also ensure that HTTP
Activation is checked in Turn Windows features on or off
Configuring Web Sites Running in Local IIS 8
WCF Service Activation
8/16/2014
12. • Create your website or web service in
Visual Studio 2012
• Run it and it is configured to run in
localhost:port
Configuring Sites Running in IIS Express
STEP 1: Create Your Website or Web service
8/16/2014
13. • Remove your website (don’t delete!) from the Visual Studio 2012 solution
• Edit the file C:UsersyourUsernameDocumentsIISExpressconfigapplicationhost.config
• Find the <sites> section
• Find the entry for the website or service you just created
• Change
<binding protocol="http" bindingInformation="*:nnnn:localhost" />
to
<binding protocol="http" bindingInformation="*:nnnn:YourPCName" />
• Save changes
• Use ‘Add Existing Website’ to add the website folder back into your solution
Configuring Sites Running in IIS Express
STEP 2: Modify Config to Run on a URI Using Your PC Name
8/16/2014
14. • From a Command Prompt (Run as Administrator), open the port in the Firewall:
netsh advfirewall firewall add rule name="IIS Express (non-SSL)" action=allow
protocol=TCP dir=in localport=nnnn
• Also run the following at the command prompt:
netsh http add urlacl url=http://yourPC:nnnn/ user=everyone
• Substitute yourPC with the host name of your Host PC
• Substitute 8080 for the port where your service is running
• Run it and access from your desktop browser – Now it is hosted at YourPCName:port
Useful References:
• How to: Specify a Port for the Development Server
http://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspx
Configuring Sites Running in IIS Express
STEP 3: Open Port in the Firewalland RegisterURL
8/16/2014
17. • No Task-based async methods have been added to WebClient
• Async operation possible using custom extension methods, allowing usage
such as:
WebClient using async/await
17
using System.Net;
using System.Threading.Tasks;
...
private async void loadButton_Click(object sender, RoutedEventArgs e)
{
var client = new WebClient();
string response = await client.DownloadStringTaskAsync(new Uri("http://MyServer/ServicesApplication/rssdump.xml"));
this.downloadedText = response;
}
18. More Control – HttpWebRequest
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Suppliers")
as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
// Must pass the HttpWebRequest object in the state attached to this call
// Begin the request…
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
• HttpWebRequestis a lower level API that allows access to the requestand response streams
• The state object passed in the BeginGetResponsecall must be the initiating HttpWebRequest
object, or a custom state object containing the HttpWebRequest
19. HttpWebRequest – Response Handling
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
string data;
// State of request is asynchronous
HttpWebRequest myHttpWebRequest = (HttpWebRequest)asynchronousResult.AsyncState; ;
using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult))
{
// Read the response into a Stream object.
System.IO.Stream responseStream = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
// Callback occurs on a background thread, so use Dispatcher to marshal back to the UI thread
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Received payload of " + data.Length + " characters");
} );
}
catch (Exception e) ...
}
20. HttpWebRequest – Error Handling
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
// Handle the Response
...
}
catch (Exception e)
{
var we = e.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("RespCallback Exception raised! Message:" + we.Message +
"HTTP Status: " + we.Status);
});
}
else
throw;
}
}
21. HttpWebRequest – Using TPL Pattern
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/Suppliers")
as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
// Use the Task Parallel Library pattern
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
try
{
var response = await task;
// Read the response into a Stream object.
System.IO.Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
MessageBox.Show("Received payload of " + data.Length + " characters");
}
catch (Exception ex) ...
22. HttpWebRequest (TPL) – Error Handling
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
// Make the call and handle the Response
...
}
catch (Exception e)
{
var we = e.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
MessageBox.Show("RespCallback Exception raised! Message:" + we.Message +
"HTTP Status: " + we.Status);
}
else
throw e;
}
}
25. WCF/ASMX Services
• Can ‘Add Reference’ from
Windows Phone projects to
automatically generate proxy
classes
• ASMX should ‘just work’
• WCF requires that you use
basicHttpBinding
25
26. RESTful Web Services
Building them
• Rather than building “walled gardens,” data should be published in a way
that allows it to reach the broadest range of mobile clients
• Old-style ASMX SOAP 1.1 Web Services using ASP.NET or Windows
Communication Foundation (WCF) require clients to implement SOAP
protocol
• With Windows Phone 7 and Silverlight, we use WCF with BasicHttpBinding
both on-premise and as a Web Role in Windows Azure to publish our data
from local and cloud-based data sources like SQL Azure
• Recommend using lightweight REST + JSON Web Services that are better
optimized for high-latency, slow, intermittent wireless data connections
26
27. WCF Data Services: OData
• WCF Data Services provide an
extensible tool for publishingdata
using a REST-based interface
• Publishes and consumes data using the OData web
protocol (http://www.odata.org)
• Formatted in XML or JSON
• WCF Data Services Client Library
(DataServicesClient) is a separate
download from
NuGet
• Adds ‘Add Service Reference’ for OData V3 Services
28. Generate Client Proxy
• In most cases, Add Service Reference will just work
• Alternatively, open a command prompt as administrator and navigate
to
C:Program Files (x86)Microsoft WCF Data
Services5.0toolsPhone
• Run this command
DataSvcutil_WindowsPhone.exe
/uri:http://odata.netflix.com/v2/Catalog/
/DataServiceCollection /Version:1.0/out:netflixClientTypes
• Add generated file to your project
29. Fetching Data
29
public partial class NorthwindModel
{
NorthwindEntities context;
private DataServiceCollection<Customer> customers;
private override void LoadData()
{
context = new NorthwindEntities(new Uri("http://services.odata.org/V3/Northwind/Northwind.svc/"));
// Initialize the context and the binding collection
customers = new DataServiceCollection<Customer>(context);
// Define a LINQ query that returns all customers.
var query = from cust in context.Customers
select cust;
// Register for the LoadCompleted event.
customers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(customers_LoadCompleted);
// Load the customers feed by executing the LINQ query.
customers.LoadAsync(query);
}
...
30. Fetching Data - LoadCompleted
30
...
void customers_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error == null)
{
// Handling for a paged data feed.
if (customers.Continuation != null)
{
// Automatically load the next page.
customers.LoadNextPartialSetAsync();
}
else
{
foreach (Customer c in customers)
{
//Add each customer to our View Model collection
App.ViewModel.Customers.Add(new CustomerViewModel(){SelectedCustomer = c});
}
}
}
else
{
MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message));
}
}
32. Open Data Protocol (OData)
• “RESTful” Web protocol
• Designed to work with data across HTTP
• Built on existing Web standards
• Uses popular formats to return data payloads to consumer
• Uses self-describing metadata
• Has multiple options to build implementation based on standard
protocol
• Soon to be a full web standard
33. The Basics of OData
Feeds, which are Collections of typed Entities
OData services can expose Actions and Functions
(v4), Services (v3)
OData services expose all these constructs via
URIs
OData service may also expose a Service Metadata
Document
34. Full SQL like Query “Language”
HTTP Command (Verb) SQL Command
GET SELECT
PUT UPDATE
POST INSERT
DELETE DELETE
37. OData Best Practices (Producer)
• Always design your OData feed will server-side paging if your entity
collections hold large amounts of data.
• Looks at server-side validation of queries and data updates based on
the user credentials sent through HTTP
41. OData Best Practices (Consumer)
• Use Query Projection to only bring back the entity properties you or
your app needs.
• Think about client-side paging even if their exists server-side paging.
• Design and implement a client-side data caching function in your app
(unless sensitive data).
43. Summaries
• WebClient and HttpWebRequest for HTTP communications
• Windows Phone has a sockets API to support connection-oriented
and connectionless TCP/IP and UDP/IP networking
• Support for ASMX, WCF and REST Web Services
• DataServicesClient for OData service access out of the box in 7.1 SDK
• Consider JSON serialization for maximum data transfer efficiency
• Windows Phone 8 supports Basic, NTLM, digest and Kerberos
authentication
• Encrypt sensitive data on the phone using the ProtectedData class