S11 Network Communication

Embed Size (px)

Citation preview

  • 8/12/2019 S11 Network Communication

    1/63

    M11: Network Communication

    in Windows Phone 8

  • 8/12/2019 S11 Network Communication

    2/63

    Target Agenda | Day 1

    Module and Topic | 10-minute breaks after each session / 60-minute meal break

    1a - Introducing Windows Phone 8 Application Development | Part 1 1b - Introducing Windows Phone 8 Application Development | Part 2

    2 - Designing Windows Phone Apps

    3 - Building Windows Phone Apps

    4 - Files and Storage on Windows Phone 8

    Meal Break | 60-minutes

    5 - Windows Phone 8 Application Lifecycle

    6 - Background Agents

    7 - Tiles and Lock Screen Notifications

    8 - Push Notifications

    9 - Using Phone Resources on Windows Phone 8

  • 8/12/2019 S11 Network Communication

    3/63

    Target Agenda | Day 2

    Module and Topic | 10-minute breaks after each session / 60-minute meal break

    10 - App to App Communication 11 - Network Communication on Windows Phone 8

    12 - Proximity Sensors and Bluetooth

    13 - Speech Input on Windows Phone 8

    14 - Maps and Location on Windows Phone 8

    15 - Wallet Support

    16 - In App Purchasing

    Meal Break | 60-minutes

    17 - The Windows Phone Store

    18 - Enterprise Applications in Windows Phone 8: Architecture and Publishing

    19 - Windows 8 and Windows Phone 8 Cross Platform Development

    20 Mobile Web

  • 8/12/2019 S11 Network Communication

    4/63

    Networking for Windows Phone

    WebClient

    HttpWebRequest

    Sockets

    Web Services and OData

    Simulation Dashboard

    Data Compression

    Module Agenda

  • 8/12/2019 S11 Network Communication

    5/63

    Networking for

    Windows Phone

  • 8/12/2019 S11 Network Communication

    6/63

    Support for networking features

    Windows Communication Foundation (WCF)

    HttpWebRequest

    WebClient

    Sockets

    Full HTTP header access on requests

    NTLM authentication

    Networking for Windows Phone

    6

  • 8/12/2019 S11 Network Communication

    7/63

    Two different Networking APIs

    System.Net Windows Phone 7.1 API, upgraded with new features

    Windows.Networking.Sockets WinRT API adapted for Windows Phon

    Support for IPV6

    Support for the 128-bit addressing system added to System.Net.Socke

    supported in Windows.Networking.Sockets

    NTLM and Kerberos authentication support

    Incoming Sockets

    Listener sockets supported in both System.Net and in Windows.Netwo

    Winsock support

    Winsock supported for native development

    New Features in Windows Phone 8

  • 8/12/2019 S11 Network Communication

    8/63

    Networking APIs Platform Availability

    API WP7.1 WP8

    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

  • 8/12/2019 S11 Network Communication

    9/63

    C# 5.0 includes the async and await keywords to ease writing of asynchrono

    In desktop .NET 4.5, and in Windows 8 .NET for Windows Store Apps, new T

    methods allow networking calls as an asynchronous operation using a Task

    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 pos

    TaskFactory.FromAsync() and extension methods

    Coming up later

    Async support in WP8 Networking APIs

  • 8/12/2019 S11 Network Communication

    10/63

    Connecting the Emulator

    to Local Services

  • 8/12/2019 S11 Network Communication

    11/63

    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 u

    http://localhost...

    In Windows Phone 8, the emulator is a Virtual machine running under Hype

    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

    Windows Phone 8 Emulator and localhost

    http://localhost/http://localhost/
  • 8/12/2019 S11 Network Communication

    12/63

    WCF Service Activation

    If your service is a WCF service, you must also ensure that HTTP Activation

    Turn Windows features on or off

    Configuring Web Sites Running in Local IIS 8

  • 8/12/2019 S11 Network Communication

    13/63

    Create your website or web service in Visual Studio 2012

    Run it and it is configured to run in localhost:port

    Note the port number. Here it is: 18009

    Configuring Sites Running in IIS ExpressSTEP 1: Create Your Website or Web service

  • 8/12/2019 S11 Network Communication

    14/63

    Remove your website (dont delete!) from the Visual Studio 2012 solution

    Edit the file C:\Users\yourUsername\Documents\IISExpress\config\applicatio

    Find the section

    Find the entry for the website or service you just created

    Change

    to

  • 8/12/2019 S11 Network Communication

    15/63

    From a Command Prompt (Run as Administrator), open the port in the Firew

    netsh advfirewall firewall add rule name="IIS Express (non-SSL)" action=allo

    protocol=TCP dir=in localport=18009

    Also run the following at the command prompt:

    netsh http add urlacl url=http://yourPC:18009/ 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 YourPCN

    Configuring Sites Running in IIS ExpressSTEP 3: Open Port in the Firewall and Register URL

    Useful References | How to: Specify a Port for the Development Server

    http://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspx

    http://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspxhttp://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspxhttp://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspxhttp://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspxhttp://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspx
  • 8/12/2019 S11 Network Communication

    16/63

    WebClient

  • 8/12/2019 S11 Network Communication

    17/63

    Simple Http Operations WebClient

    usingSystem.Net;...

    WebClientclient;

    // ConstructorpublicMainPage(){

    ...client = newWebClient();client.DownloadStringCompleted += client_DownloadStringCompleted;

    }

    voidclient_DownloadStringCompleted(objectsender, DownloadStringCompletedEvent{

    this.downloadedText = e.Result;}

    privatevoidloadButton_Click(objectsender, RoutedEventArgse){

    client.DownloadStringAsync(newUri("http://MyServer/ServicesApplication/rss

    }

  • 8/12/2019 S11 Network Communication

    18/63

    WebClient using async/await

    No Task-based async methods have been added to WebClient

    Async operation possible using custom extension methods, allowing usage s

    usingSystem.Net;usingSystem.Threading.Tasks;...

    privateasyncvoidloadButton_Click(objectsender, RoutedEventArgse){

    varclient = newWebClient();stringresponse = awaitclient.DownloadStringTaskAsync(newUri("http://MyServer/ServicesApplication/r

    this.downloadedText = response;}

  • 8/12/2019 S11 Network Communication

    19/63

    Demo 1: Simple HTTP

    Networking

    with WebClient

  • 8/12/2019 S11 Network Communication

    20/63

    More Control HttpWebRequest

    privatevoidPhoneApplicationPage_Loaded(objectsender, RoutedEventArgse){varrequest = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Supplie

    as HttpWebRequest;request.Accept = "application/json;odata=verbose";// Must pass the HttpWebRequest object in the state attached to this call// Begin the requestrequest.BeginGetResponse(newAsyncCallback(GotResponse), request);

    }

    HttpWebRequest is a lower level API that allows access to the request and

    response streams

    That state object passed in the BeginGetResponse call must be the initiating

    HttpWebREquest object or a custom state object containing the HttpWebRe

  • 8/12/2019 S11 Network Communication

    21/63

    HttpWebRequest Response HandlingprivatevoidGotResponse(IAsyncResultasynchronousResult){

    try{stringdata;// State of request is asynchronousHttpWebRequestmyHttpWebRequest = (HttpWebRequest)asynchronousResult.AsyncState; ;using(HttpWebResponseresponse = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asyn{// Read the response into a Stream object.System.IO.StreamresponseStream = response.GetResponseStream();using(varreader = newSystem.IO.StreamReader(responseStream)){data = reader.ReadToEnd();

    }responseStream.Close();

    }

    // Callback occurs on a background thread, so use Dispatcher to marshal back to the UI this.Dispatcher.BeginInvoke(() =>{MessageBox.Show("Received payload of "+ data.Length + " characters");

    } );}

    catch(Exceptione) ...}

  • 8/12/2019 S11 Network Communication

    22/63

    HttpWebRequest Error Handling

    privatevoidGotResponse(IAsyncResultasynchronousResult){

    try{

    // Handle the Response...

    }catch(Exceptione){varwe = e.InnerException asWebException;if(we != null){varresp = we.Response asHttpWebResponse;varcode = resp.StatusCode;

    this.Dispatcher.BeginInvoke(() =>{MessageBox.Show("RespCallback Exception raised! Message:"+ we.Message +

    "HTTP Status: " + we.Status);});

    }elsethrow;

    }}

  • 8/12/2019 S11 Network Communication

    23/63

    HttpWebRequest Using TPL PatternprivateasyncvoidPhoneApplicationPage_Loaded(objectsender, RoutedEventArgse){varrequest = HttpWebRequest.Create("http://rockstar:15500/NorthwindDataService.svc/Supplie

    asHttpWebRequest;request.Accept = "application/json;odata=verbose";

    // Use the Task Parallel Library patternvarfactory = newTaskFactory();vartask = factory.FromAsync(request.BeginGetResponse, request.EndGetResponse,

    try{varresponse = awaittask;

    // Read the response into a Stream object.System.IO.StreamresponseStream = response.GetResponseStream();

    stringdata;using(varreader = newSystem.IO.StreamReader(responseStream)){data = reader.ReadToEnd();

    }responseStream.Close();

    MessageBox.Show("Received payload of "+ data.Length + " characters");}catch(Exceptionex)...

  • 8/12/2019 S11 Network Communication

    24/63

    HttpWebRequest (TPL) Error Handling

    privateasyncvoidPhoneApplicationPage_Loaded(objectsender, RoutedEventArgse){

    try{// Make the call and handle the Response...

    }catch(Exceptione){varwe = e.InnerException asWebException;if(we != null){

    varresp = we.Response asHttpWebResponse;varcode = resp.StatusCode;MessageBox.Show("RespCallback Exception raised! Message:"+ we.Message +

    "HTTP Status: " + we.Status);}elsethrowe;

    }}

  • 8/12/2019 S11 Network Communication

    25/63

    Demo 2:

    HttpWebRequest

  • 8/12/2019 S11 Network Communication

    26/63

    Sockets

  • 8/12/2019 S11 Network Communication

    27/63

    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

    Windows.Networking.SocketsWindows Phone Runtime API Compatible with Windows 8 WinRT Revamped API Much more concise!

  • 8/12/2019 S11 Network Communication

    28/63

    Web Services

  • 8/12/2019 S11 Network Communication

    29/63

    Can Add Reference from Windows

    Phone projects to automatically

    generate proxy classes

    ASMX should just work

    WCF requires that you use

    basicHttpBinding

    WCF/ASMX Services

  • 8/12/2019 S11 Network Communication

    30/63

    RESTful Web Services

    Building them

    Rather than building walled gardens, data should be published in a way tha

    reach the broadest range of mobile clients

    Old-style ASMX SOAP 1.1 Web Services using ASP.NET or Windows CommunFoundation (WCF) require clients to implement SOAP protocol

    With Windows Phone 7 and Silverlight, we use WCF with BasicHttpBinding band as a Web Role in Windows Azure to publish our data from local and clousources like SQL Azure

    Recommend using lightweight REST + JSON Web Services that are better ophigh-latency, slow, intermittent wireless data connections

  • 8/12/2019 S11 Network Communication

    31/63

    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

  • 8/12/2019 S11 Network Communication

    32/63

    WCF Data Services 5.1

    Download WCF Data services 5.1 Tools Installer to update item templates forcomponents

    Major release: Adds support for new JSON Light serialization format

  • 8/12/2019 S11 Network Communication

    33/63

    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 Services\5.0\tools\Phone 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

    http://odata.netflix.com/Catalog/http://odata.netflix.com/Catalog/http://odata.netflix.com/Catalog/http://odata.netflix.com/Catalog/http://odata.netflix.com/Catalog/
  • 8/12/2019 S11 Network Communication

    34/63

    Fetching Data

    publicpartialclassNorthwindModel{

    NorthwindEntitiescontext;privateDataServiceCollection customers;

    privateoverridevoidLoadData(){

    context = newNorthwindEntities(newUri("http://services.odata.org/V3/Northwind/N// Initialize the context and the binding collectioncustomers = newDataServiceCollection(context);

    // Define a LINQ query that returns all customers.varquery = fromcust incontext.Customers

    selectcust;

    // Register for the LoadCompleted event.customers.LoadCompleted += newEventHandler(customers_Loa

    // Load the customers feed by executing the LINQ query.customers.LoadAsync(query);

    }...

  • 8/12/2019 S11 Network Communication

    35/63

    Fetching Data - LoadCompleted

    36

    ...

    void customers_LoadCompleted(objectsender, LoadCompletedEventArgse){

    if(e.Error == null)

    {// Handling for a paged data feed.if(customers.Continuation != null){

    // Automatically load the next page.customers.LoadNextPartialSetAsync();

    }else{

    foreach(Customerc incustomers){

    //Add each customer to our View Model collectionApp.ViewModel.Customers.Add( newCustomerViewModel(){SelectedCustomer = c}

    }}

    }else{

    MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message));}

    }

  • 8/12/2019 S11 Network Communication

    36/63

    Demo 3:

    OData Services

  • 8/12/2019 S11 Network Communication

    37/63

    Network Information

    and Efficiency

    k

  • 8/12/2019 S11 Network Communication

    38/63

    Making Decisions based on Data Connections

    Mobile apps shouldnt diminish the user experience by trying to send or rec

    the absence of network connectivity

    Mobile apps should be intelligent about performing heavy data transfers or

    remote method calls only when the appropriate data connection is available

    With Windows Phone, we use the NetworkInterfaceType object to detect nespeed and the NetworkChange object to fire events when the network

    state changes

    Network Awareness

    39

    N kI f i i Wi d Ph 8 0

  • 8/12/2019 S11 Network Communication

    39/63

    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 currently connected to

    NetworkInformation.GetLanIdentifiers

    D t i i th C t I t t C ti T

  • 8/12/2019 S11 Network Communication

    40/63

    Determining the Current Internet Connection Type

    privateconstintIANA_INTERFACE_TYPE_OTHER = 1;privateconstintIANA_INTERFACE_TYPE_ETHERNET = 6;privateconstintIANA_INTERFACE_TYPE_PPP = 23;privateconstintIANA_INTERFACE_TYPE_WIFI = 71;...stringnetwork = string.Empty;

    // Get current Internet Connection Profile.ConnectionProfileinternetConnectionProfile =

    Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfi

    switch(internetConnectionProfile.NetworkAdapter.IanaInterfaceType){

    caseIANA_INTERFACE_TYPE_OTHER:

    cost += "Network: Other"; break;caseIANA_INTERFACE_TYPE_ETHERNET:

    cost += "Network: Ethernet"; break;caseIANA_INTERFACE_TYPE_WIFI:

    cost += "Network: Wifi\r\n"; break;default:

    cost += "Network: Unknown\r\n"; break;}

    Ti f N t k Effi i

  • 8/12/2019 S11 Network Communication

    41/63

    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 ins Avoid large data transfers

    Avoid transferring redundant data

    Design your protocol to only transfer precisely the data you need and no mo

  • 8/12/2019 S11 Network Communication

    42/63

    Wi e Se iali ation Affects Pa oll Si e

  • 8/12/2019 S11 Network Communication

    43/63

    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

    ODATA XML

    ODATA JSON

    REST + JSON

    REST + JSON GZip

    Implementing Compression on Windows Phone

  • 8/12/2019 S11 Network Communication

    44/63

    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/) 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

    HttpWebRequest With Compression

    http://sharpcompress.codeplex.com/http://sharpcompress.codeplex.com/http://sharpziplib.com/http://sharpcompress.codeplex.com/http://sharpcompress.codeplex.com/http://sharpziplib.com/
  • 8/12/2019 S11 Network Communication

    45/63

    HttpWebRequest With Compression

    varrequest = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/SuppliasHttpWebRequest;

    request.Accept = "application/json;odata=verbose";

    request.Headers["Accept_Encoding"] = "gzip";

    // Use the Task Parallel Library patternvarfactory = newTaskFactory();vartask = factory.FromAsync(request.BeginGetResponse, request.EndGetRespon

    varresponse = awaittask;

    // Read the response into a Stream object.System.IO.StreamresponseStream = response.GetResponseStream();stringdata;varstream = newGZipInputStream(response.GetResponseStream());using(varreader = newSystem.IO.StreamReader(stream)){data = reader.ReadToEnd();

    }responseStream.Close();

    Compression with OData Client Library

  • 8/12/2019 S11 Network Communication

    46/63

    Compression with OData Client Library

    privatevoidEnableGZipResponses(DataServiceContextctx){

    ctx.WritingRequest += newEventHandler((_, args) =>{

    args.Headers["Accept-Encoding"] = "gzip";} );

    ctx.ReadingResponse += newEventHandler((_, args) =>{

    if(args.Headers.ContainsKey("Content-Encoding") &&args.Headers["Content-Encoding"].Contains("gzip"))

    {

    args.Content = newGZipStream(args.Content);}

    } );}

    Reference: http://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7

    http://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspxhttp://blogs.msdn.com/b/astoriateam/archive/2011/10/04/odata-compression-in-windows-phone-7-5-mango.aspx
  • 8/12/2019 S11 Network Communication

    47/63

    Demo 5:

    Compression

    48

  • 8/12/2019 S11 Network Communication

    48/63

    Data Sense

    Data Sense API

  • 8/12/2019 S11 Network Communication

    49/63

    The Data Sense feature allows a user to specify the limits of their data plans and moni

    Your app can use the information provided by the Data Sense APIs to change data usa

    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 conne

    is roaming, but you cannot determine the users data limits

    Data Sense API

    Using the Data Sense APIs

  • 8/12/2019 S11 Network Communication

    50/63

    Using the Data Sense APIs

    1. Get the Network Type from the

    ConnectionProfile by calling NetworkInformation.GetInternetConnectionClient

    2. Get the NetworkCostTypeby callingConnectionProfile.GetConnectionCost

    3. Get the ApproachingDataLimit,OverDataLimitand Roamingproperties of theConnectionProfile

    If on WiFi, no need t

    usage

    Returns Unknown, UFixed or Variable: If Uno need to limit data

    If any are true, your reduce or eliminate

    Responsible Data Usage in a Data Sense-Aware Ap

  • 8/12/2019 S11 Network Communication

    51/63

    Responsible Data Usage in a Data Sense Aware Ap

    NetworkCostType ConnectionCost Responsible data usage Example

    Unrestricted Not applicable. No restrictions.

    Stream hiDownload

    pictures.Retrieve e

    Fixedor Variable

    All three of the followingproperties are false.ApproachingDataLimitOverDataLimitRoaming

    No restrictions.

    Stream hDownloapictures.Retrieve

    Fixedor VariableorUnknown

    ApproachingDataLimit is true,

    when NetworkCostType is Fixedor Variable.

    Not applicable whenNetworkCostType is Unknown.

    Transfer less data.Provide option to override.

    Stream lo

    Downloapictures.Retrieve oPostponedata.

    Fixedor VariableOverDataLimitor Roamingistrue

    Dont transfer data.Provide option to override.

    Stop dowStop dowDo not rePostpone

  • 8/12/2019 S11 Network Communication

    52/63

    Network Security

    Encrypting the Communication

  • 8/12/2019 S11 Network Communication

    53/63

    You can use SSL (https://...) to encrypt data communications with servers tha

    server cert

    Root certificates for the major Certificate Authorities (Digicert, Entrust, Veris

    built into Windows Phone 8

    Your app can simply access an https:// resource and the server certifica

    automatically verified and the encrypted connection set up

    SSL Client certificates are not supported, so mutual authentication scenpossible

    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 ce

    Encrypting the Communication

    Authentication

  • 8/12/2019 S11 Network Communication

    54/63

    Authentication

    As well as encrypting data in transit, you also need to authenticate the clientthey are allowed to access the requested resource

    For communications over the Internet, secure web services using Basic HTTP Transfers the username and password from client to server in clear text, so used in conjunction with SSL encryption

    For Intranet web services, you can secure them using Windows or Digest aut Windows Phone 8 supports NTLM and Kerberos authentication

    Adding Credentials to an HttpWebRequest

  • 8/12/2019 S11 Network Communication

    55/63

    dd g C ede t a s to a ttp eb equest

    privatevoidPhoneApplicationPage_Loaded(objectsender, RoutedEventArgse){varrequest = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Supplie

    as HttpWebRequest;request.Credentials = newCredentials("username", "password"); // override allows domain to

    request.Accept = "application/json;odata=verbose";// Must pass the HttpWebRequest object in the state attached to this call// Begin the requestrequest.BeginGetResponse(newAsyncCallback(GotResponse), request);

    }

    Provide your own UI to request the credentials from the user

    If you store the credentials, encrypt them using the ProtectedData class

    Encrypting Sensitive Data Using ProtectedData

  • 8/12/2019 S11 Network Communication

    56/63

    yp g g

    privatevoidStoreCredentials(){

    // 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.IsolatedStorageFilefile = IsolatedStorageFile.GetUserStoreForApplication();IsolatedStorageFileStreamwritestream =

    newIsolatedStorageFileStream(FilePath, System.IO.FileMode.Create, System.IO.FileAcc

    // Write data to the file.Streamwriter = newStreamWriter(writestream).BaseStream;writer.Write(protectedSecretByte, 0, protectedSecretByte.Length);writer.Close();writestream.Close();

    }

    Decrypting Data Using ProtectedData

  • 8/12/2019 S11 Network Communication

    57/63

    yp g g

    // Retrieve the protected data from isolated storage.IsolatedStorageFilefile = IsolatedStorageFile.GetUserStoreForApplication();IsolatedStorageFileStreamreadstream =

    newIsolatedStorageFileStream(FilePath, System.IO.FileMode.Open, FileAccess.Read, file

    // Read the data from the file.Streamreader = newStreamReader(readstream).BaseStream;byte[] encryptedDataArray = newbyte[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.stringdata = Encoding.UTF8.GetString(clearTextBytes, 0, clearTextBytes.Length);

  • 8/12/2019 S11 Network Communication

    58/63

    Storing Data in the Cloud

    Live SDK

  • 8/12/2019 S11 Network Communication

    59/63

    Windows Live SDK Makes it easy to use SkyDrive in your

    Windows Phone and Windows 8 apps Live SDK also available for iOS and Android

    Store data in the cloud in the MicrosoftAccount users SkyDrive Restriction on acceptable file types now

    removed!

    Share data between Windows 8 and mobile device apps

    http://msdn.microsoft.com/en-us/live/default.aspx

    Windows Azure Mobile Services

  • 8/12/2019 S11 Network Communication

    60/63

    http://www.windowsazure.com/en-us/develop/mobile/

    Easily build a cloud backend for your app Easy to create a Windows Azure database

    accessed via RESTful services Authentication against Microsoft Account,

    Facebook, Twitter or Google Push Notifications

    Client SDKs for Windows 8, Windows Phone

    and iOS Android coming soon Great tutorials on the website

    http://www.windowsazure.com/en-us/develop/overview/http://www.windowsazure.com/en-us/develop/overview/http://www.windowsazure.com/en-us/develop/overview/http://www.windowsazure.com/en-us/develop/overview/http://www.windowsazure.com/en-us/develop/overview/http://www.windowsazure.com/en-us/develop/overview/
  • 8/12/2019 S11 Network Communication

    61/63

    Demo :Windows Azure Mobile Services

    Summary

  • 8/12/2019 S11 Network Communication

    62/63

    WebClient and HttpWebRequest for HTTP communications

    Windows Phone has a sockets API to support connection-oriented and connTCP/IP and UDP/IP networking

    Support for ASMX, WCF and REST Web Services

    DataServicesClient for OData service access

    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

    Live SDK and Windows Azure Mobile Services ease integration with the cloud

  • 8/12/2019 S11 Network Communication

    63/63

    The information herein is for informationalpurposes 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 ofMicrosoft, 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.