Oliver Scheer
Senior Technical Evangelist
Microsoft Deutschland
http://the-oliver.com
Network Communication
in Windows Pho...
Agenda
 Networking for Windows Phone
 WebClient
 HttpWebRequest
 Sockets
 Web Services and OData
 Simulation Dashboa...
Networking on
Windows Phone
Networking on Windows Phone
• Support for networking features
•Windows Communication Foundation (WCF)
•HttpWebRequest
•Web...
New Features in Windows Phone 8
• Two different Networking APIs
• System.Net – Windows Phone 7.1 API, upgraded with new fe...
Networking APIs Platform Availability
API WP7.1 WP8 W8
System.Net.WebClient   
System.Net.HttpWebRequest   
System.N...
Async support in WP8 Networking APIs
• C# 5.0 includes the async and await keywords to ease writing of asynchronous code
•...
Connecting the
Emulator to Local
Services
3/19/20148
• In Windows Phone 7.x, the emulator shared the networking of the Host PC
• You could host services on your PC and access ...
• If you host your web sites or services in IIS, you must open your firewall for incoming HTTP
requests
Configuring Web Si...
• If your service is a WCF service, you must also ensure that HTTP Activation is checked in
Turn Windows features on or of...
• Create your website or web service in Visual Studio
2012
• Run it and it is configured to run in localhost:port
Configur...
• Remove your website (don’t delete!) from the Visual Studio 2012 solution
• Edit the file C:UsersyourUsernameDocumentsIIS...
• From a Command Prompt (Run as Administrator), open the port in the Firewall:
netsh advfirewall firewall add rule name="I...
WebClient
3/19/201415
Simple Http Operations – WebClient
using System.Net;
...
WebClient client;
// Constructor
public MainPage()
{
...
client =...
• No Task-based async methods have been added to WebClient
• Async operation possible using custom extension methods, allo...
Demo 1: Simple
HTTP Networking
with WebClient
More Control – HttpWebRequest
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var request = H...
HttpWebRequest – Response Handling
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
string data;
// State...
HttpWebRequest – Error Handling
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
// Handle the Response
....
HttpWebRequest – Using TPL Pattern
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var ...
HttpWebRequest (TPL) – Error Handling
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
t...
Demo 2:
HttpWebRequest
Sockets
Sockets Support in Windows Phone OS 8.0
• TCP
• Connection-oriented
• Reliable Communication
• UDP Unicast, UDP Multicast
...
Web Services
WCF/ASMX Services
• Can ‘Add Reference’ from Windows
Phone projects to automatically
generate proxy classes
• ASMX should ...
RESTful Web Services
Building them
• Rather than building “walled gardens,” data should be published in a way that allows ...
WCF Data Services: OData
• WCF Data Services provide an extensible tool for
publishing data using a REST-based interface
•...
Generate Client Proxy
• In most cases, Add Service Reference will just work
• Alternatively, open a command prompt as admi...
Fetching Data
32
public partial class NorthwindModel
{
NorthwindEntities context;
private DataServiceCollection<Customer> ...
Fetching Data - LoadCompleted
33
...
void customers_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error =...
Demo 3: OData
Services
34
Network Information
and Efficiency
3/19/2014
Network Awareness
Making Decisions based on Data Connections
• Mobile apps shouldn’t diminish the user experience by tryin...
NetworkInformation in Windows Phone 8.0
• In Microsoft.Phone.Net.NetworkInformation namespace:
• Determine the Network Ope...
Determining the Current Internet Connection Type
private const int IANA_INTERFACE_TYPE_OTHER = 1;
private const int IANA_I...
Tips for Network Efficiency
• Mobile devices are often connected to poor quality network connections
• Best chance of succ...
Demo 4:
Wire Serialization
40
Wire Serialization Affects Payroll Size
• Simple test case: download
30 data records
• Each record just 12 fields
• Measur...
Implementing Compression on Windows Phone
• Windows Phone does not support System.IO.Compression.GZipStream
• Use third-pa...
HttpWebRequest – With Compression
var request = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/Suppli...
Compression with OData Client Library
private void EnableGZipResponses(DataServiceContext ctx)
{
ctx.WritingRequest += new...
Demo 5:
Compression
45
Data Sense
3/19/2014
• The Data Sense feature allows a user to specify the limits of their data plans and monitors their usage
• Your app can u...
• If on WiFi, no need to limit data usage
1. Get the Network Type from the
ConnectionProfile by calling NetworkInformation...
Responsible Data Usage in a Data Sense-Aware App
3/19/2014Microsoft confidential49
NetworkCostType ConnectionCost Responsi...
Demo 6:
Data Sense APIs
50
Network Security
3/19/2014
Encrypting the Communication
• You can use SSL (https://...) to encrypt data communications with servers that have an SSL
...
Authentication
• As well as encrypting data in transit, you also need to authenticate the client to make sure
they are all...
Adding Credentials to an HttpWebRequest
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var r...
Encrypting Sensitive Data Using ProtectedData
private void StoreCredentials()
{
// Convert the username and password to a ...
Decrypting Data Using ProtectedData
// Retrieve the protected data from isolated storage.
IsolatedStorageFile file = Isola...
Summary
• WebClient and HttpWebRequest for HTTP communications
• Windows Phone has a sockets API to support connection-ori...
The information herein is for informational
purposes only an represents the current view of
Microsoft Corporation as of th...
Upcoming SlideShare
Loading in...5
×

Windows Phone 8 - 12 Network Communication

1,562

Published on

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

  • Be the first to like this

No Downloads
Views
Total Views
1,562
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
35
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Windows Phone 8 - 12 Network Communication

  1. 1. Oliver Scheer Senior Technical Evangelist Microsoft Deutschland http://the-oliver.com Network Communication in Windows Phone 8
  2. 2. Agenda  Networking for Windows Phone  WebClient  HttpWebRequest  Sockets  Web Services and OData  Simulation Dashboard  Data Compression
  3. 3. Networking on Windows Phone
  4. 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. 5. New Features in Windows Phone 8 • 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 3/19/20145
  6. 6. Networking APIs Platform Availability API WP7.1 WP8 W8 System.Net.WebClient    System.Net.HttpWebRequest    System.Net.Http.HttpClient    Windows.Web.Syndication.SyndicationClient    Windows.Web.AtomPub.AtomPubClient    ASMX Web Services    WCF Services    OData Services    3/19/20146
  7. 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… 3/19/20147
  8. 8. Connecting the Emulator to Local Services 3/19/20148
  9. 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 Windows Phone 8 Emulator and localhost 3/19/2014
  10. 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 3/19/2014
  11. 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 3/19/2014
  12. 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 3/19/2014
  13. 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 3/19/2014
  14. 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 Firewall and Register URL 3/19/2014
  15. 15. WebClient 3/19/201415
  16. 16. Simple Http Operations – WebClient using System.Net; ... WebClient client; // Constructor public MainPage() { ... client = new WebClient(); client.DownloadStringCompleted += client_DownloadStringCompleted; } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { this.downloadedText = e.Result; } private void loadButton_Click(object sender, RoutedEventArgs e) { client.DownloadStringAsync(new Uri("http://MyServer/ServicesApplication/rssdump.xml")); }
  17. 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 3/19/201417 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. 18. Demo 1: Simple HTTP Networking with WebClient
  19. 19. 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); } • HttpWebRequest is a lower level API that allows access to the request and response streams • The state object passed in the BeginGetResponse call must be the initiating HttpWebRequest object, or a custom state object containing the HttpWebRequest
  20. 20. 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) ... }
  21. 21. 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; } }
  22. 22. 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) ...
  23. 23. 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; } }
  24. 24. Demo 2: HttpWebRequest
  25. 25. Sockets
  26. 26. Sockets Support in Windows Phone OS 8.0 • TCP • Connection-oriented • Reliable Communication • UDP Unicast, UDP Multicast • Connectionless • Not Reliable • New Features in 8.0! • IPV6 support • Listener Sockets
  27. 27. Web Services
  28. 28. 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 28
  29. 29. 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 29
  30. 30. WCF Data Services: OData • WCF Data Services provide an extensible tool for publishing data 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
  31. 31. 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
  32. 32. Fetching Data 32 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); } ...
  33. 33. Fetching Data - LoadCompleted 33 ... 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)); } }
  34. 34. Demo 3: OData Services 34
  35. 35. Network Information and Efficiency 3/19/2014
  36. 36. Network Awareness Making Decisions based on Data Connections • Mobile apps shouldn’t diminish the user experience by trying to send or receive data in the absence of network connectivity • Mobile apps should be intelligent about performing heavy data transfers or lightweight remote method calls only when the appropriate data connection is available • With Windows Phone, we use the NetworkInterfaceType object to detect network type and speed and the NetworkChange object to fire events when the network state changes 36
  37. 37. NetworkInformation in Windows Phone 8.0 • In Microsoft.Phone.Net.NetworkInformation namespace: • Determine the Network Operator: • DeviceNetworkInformation.CellularMobileOperator • Determine the Network Capabilities: • DeviceNetworkInformation.IsNetworkAvailable • DeviceNetworkInformation.IsCellularDataEnabled • DeviceNetworkInformation.IsCellularDataRoamingEnabled • DeviceNetworkInformation.IsWiFiEnabled •In Windows.Networking.Connectivity namespace: • Get Information about the current internet connection • NetworkInformation.GetInternetConnectionProfile • Get Information about the NetworkAdapter objects that are currently connected to a network • NetworkInformation.GetLanIdentifiers
  38. 38. Determining the Current Internet Connection Type private const int IANA_INTERFACE_TYPE_OTHER = 1; private const int IANA_INTERFACE_TYPE_ETHERNET = 6; private const int IANA_INTERFACE_TYPE_PPP = 23; private const int IANA_INTERFACE_TYPE_WIFI = 71; ... string network = string.Empty; // Get current Internet Connection Profile. ConnectionProfile internetConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile(); switch (internetConnectionProfile.NetworkAdapter.IanaInterfaceType) { case IANA_INTERFACE_TYPE_OTHER: cost += "Network: Other"; break; case IANA_INTERFACE_TYPE_ETHERNET: cost += "Network: Ethernet"; break; case IANA_INTERFACE_TYPE_WIFI: cost += "Network: Wifirn"; break; default: cost += "Network: Unknownrn"; break; }
  39. 39. Tips for Network Efficiency • Mobile devices are often connected to poor quality network connections • Best chance of success in network data transfers achieved by • Keep data volumes as small as possible • Use the most compact data serialization available (If you can, use JSON instead of XML) • Avoid large data transfers • Avoid transferring redundant data • Design your protocol to only transfer precisely the data you need and no more
  40. 40. Demo 4: Wire Serialization 40
  41. 41. Wire Serialization Affects Payroll Size • Simple test case: download 30 data records • Each record just 12 fields • Measured bytes to transfer Wire Serialization Format Size in Bytes ODATA XML 73786 ODATA JSON 34030 REST + JSON 15540 REST + JSON GZip 8680
  42. 42. Implementing Compression on Windows Phone • Windows Phone does not support System.IO.Compression.GZipStream • Use third-party solutions instead • SharpZipLib is a popular C# compression library (http://sharpziplib.com/) – on NuGet • SharpCompress is another (http://sharpcompress.codeplex.com/) • On Windows Phone OS 7.1, get GZipWebClient from NuGet • Replaces WebClient, but adds support for compression • Uses SharpZipLib internally • NuGet release for Windows Phone 8 not yet available (as of October 2012) • Until updated library released on NuGet, source is available online 3/19/201442
  43. 43. HttpWebRequest – With Compression var request = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/Suppliers") as HttpWebRequest; request.Accept = "application/json;odata=verbose"; request.Headers["Accept_Encoding"] = "gzip"; // Use the Task Parallel Library pattern var factory = new TaskFactory(); var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null); var response = await task; // Read the response into a Stream object. System.IO.Stream responseStream = response.GetResponseStream(); string data; var stream = new GZipInputStream(response.GetResponseStream()); using (var reader = new System.IO.StreamReader(stream)) { data = reader.ReadToEnd(); } responseStream.Close();
  44. 44. Compression with OData Client Library private void EnableGZipResponses(DataServiceContext ctx) { ctx.WritingRequest += new EventHandler<ReadingWritingHttpMessageEventArgs>( (_, args) => { args.Headers["Accept-Encoding"] = "gzip"; } ); ctx.ReadingResponse += new EventHandler<ReadingWritingHttpMessageEventArgs>( (_, args) => { if (args.Headers.ContainsKey("Content-Encoding") && args.Headers["Content-Encoding"].Contains("gzip")) { args.Content = new GZipStream(args.Content); } } ); } • Reference: http://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspx 3/19/201444
  45. 45. Demo 5: Compression 45
  46. 46. Data Sense 3/19/2014
  47. 47. • The Data Sense feature allows a user to specify the limits of their data plans and monitors their usage • Your app can use the information provided by the Data Sense APIs to change data usage behavior • Reduce data usage when the user is close to their data limits • Discontinue data usage when the user is over their limit • Or to postpone tasks that transfer data until a Wi-Fi connection is available • Data Sense is a feature that Network Operators optionally support • Provide a Data Sense app and Tiles to allow users to enter their data limits • Routes data via a proxy server in order to monitor data usage • If Data Sense is not enabled, you can still use the APIs to determine if the user is connected to WiFi or is roaming, but you cannot determine the users data limits Data Sense API 3/19/2014
  48. 48. • If on WiFi, no need to limit data usage 1. Get the Network Type from the ConnectionProfile by calling NetworkInformation. GetInternetConnectionClient • Returns Unknown, Unrestricted, Fixed or Variable: If Unrestricted, no need to limit data usage 2. Get the NetworkCostType by calling ConnectionProfile.GetConnectionCost • If any are true, your app can reduce or eliminate data usage 3. Get the ApproachingDataLimit, OverDataLimit and Roaming properties of the ConnectionProfile Using the Data Sense APIs 3/19/2014Microsoft confidential48
  49. 49. Responsible Data Usage in a Data Sense-Aware App 3/19/2014Microsoft confidential49 NetworkCostType ConnectionCost Responsible data usage Examples Unrestricted Not applicable. No restrictions. Stream high-definition video. Download high-resolution pictures. Retrieve email attachments. Fixed or Variable All three of the following properties are false. •ApproachingDataLimit •OverDataLimit •Roaming No restrictions. Stream high-definition video. Download high-resolution pictures. Retrieve email attachments. Fixed or Variable or Unknown ApproachingDataLimit is true, when NetworkCostType is Fixed or Variable. Not applicable when NetworkCostType is Unknown. Transfer less data. Provide option to override. Stream lower-quality video. Download low-resolution pictures. Retrieve only email headers. Postpone tasks that transfer data. Fixed or Variable OverDataLimit or Roaming is true Don’t transfer data. Provide option to override. Stop downloading video. Stop downloading pictures. Do not retrieve email. Postpone tasks that transfer data.
  50. 50. Demo 6: Data Sense APIs 50
  51. 51. Network Security 3/19/2014
  52. 52. Encrypting the Communication • You can use SSL (https://...) to encrypt data communications with servers that have an SSL server cert • Root certificates for the major Certificate Authorities (Digicert, Entrust, Verisign, etc…) are built into Windows Phone 8 • Your app can simply access an https:// resource and the server certificate is automatically verified and the encrypted connection set up • SSL Client certificates are not supported, so mutual authentication scenarios are not possible • You can install a self-signed cert into the Windows Phone Certificate Store • Expose the .cer file on a share or website protected by authentication • Alllows you to access private servers secured by a self-signed server certificate 3/19/201452
  53. 53. Authentication • As well as encrypting data in transit, you also need to authenticate the client to make sure they are allowed to access the requested resource • For communications over the Internet, secure web services using Basic HTTP authentication • Transfers the username and password from client to server in clear text, so this must be used in conjunction with SSL encryption • For Intranet web services, you can secure them using Windows or Digest authentication • Windows Phone 8 supports NTLM and Kerberos authentication 3/19/201453
  54. 54. Adding Credentials to an HttpWebRequest private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { var request = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Suppliers") as HttpWebRequest; request.Credentials = new NetworkCredential("username", "password"); // override allows domain to be specified 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); } • Provide your own UI to request the credentials from the user • If you store the credentials, encrypt them using the ProtectedData class
  55. 55. Encrypting Sensitive Data Using ProtectedData private void StoreCredentials() { // Convert the username and password to a byte[]. byte[] secretByte = Encoding.UTF8.GetBytes(TBusername.Text + "||" + TBpassword.Text); // Encrypt the username by using the Protect() method. byte[] protectedSecretByte = ProtectedData.Protect(secretByte, null); // Create a file in the application's isolated storage. IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream writestream = new IsolatedStorageFileStream(FilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, file); // Write data to the file. Stream writer = new StreamWriter(writestream).BaseStream; writer.Write(protectedSecretByte, 0, protectedSecretByte.Length); writer.Close(); writestream.Close(); }
  56. 56. Decrypting Data Using ProtectedData // Retrieve the protected data from isolated storage. IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream readstream = new IsolatedStorageFileStream(FilePath, System.IO.FileMode.Open, FileAccess.Read, file); // Read the data from the file. Stream reader = new StreamReader(readstream).BaseStream; byte[] encryptedDataArray = new byte[reader.Length]; reader.Read(encryptedDataArray, 0, encryptedDataArray.Length); reader.Close(); readstream.Close(); // Decrypt the data by using the Unprotect method. byte[] clearTextBytes = ProtectedData.Unprotect(encryptedDataArray, null); // Convert the byte array to string. string data = Encoding.UTF8.GetString(clearTextBytes, 0, clearTextBytes.Length);
  57. 57. Summary • 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
  58. 58. The information herein is for informational purposes only an represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×