SlideShare a Scribd company logo
1 of 58
Oliver Scheer
Senior Technical Evangelist
Microsoft Deutschland
http://the-oliver.com
Network Communication
in Windows Phone 8
Agenda
ļ‚§ Networking for Windows Phone
ļ‚§ WebClient
ļ‚§ HttpWebRequest
ļ‚§ Sockets
ļ‚§ Web Services and OData
ļ‚§ Simulation Dashboard
ļ‚§ Data Compression
Networking on
Windows Phone
Networking on Windows Phone
ā€¢ Support for networking features
ā€¢Windows Communication Foundation (WCF)
ā€¢HttpWebRequest
ā€¢WebClient
ā€¢Sockets
ā€¢Full HTTP header access on requests
ā€¢NTLM authentication
4
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
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
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
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 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
ā€¢ 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
ā€¢ 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
ā€¢ 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
ā€¢ 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
ā€¢ 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
WebClient
3/19/201415
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"));
}
ā€¢ 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;
}
Demo 1: Simple
HTTP Networking
with WebClient
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
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) ...
}
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;
}
}
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) ...
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;
}
}
Demo 2:
HttpWebRequest
Sockets
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
Web Services
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
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
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
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
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);
}
...
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));
}
}
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 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
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
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;
}
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
Demo 4:
Wire Serialization
40
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
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
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();
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
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 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
ā€¢ 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
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.
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
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
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
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
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();
}
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);
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
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.

More Related Content

What's hot

Web
WebWeb
Webgoogli
Ā 
Bp101-Can Domino Be Hacked
Bp101-Can Domino Be HackedBp101-Can Domino Be Hacked
Bp101-Can Domino Be HackedHoward Greenberg
Ā 
OSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven Nierlein
OSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven NierleinOSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven Nierlein
OSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven NierleinNETWAYS
Ā 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF WorkshopIdo Flatow
Ā 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB APIThang Chung
Ā 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIEyal Vardi
Ā 
02 wireshark http-sept_15_2009
02   wireshark http-sept_15_200902   wireshark http-sept_15_2009
02 wireshark http-sept_15_2009Vothe Dung
Ā 
Using MCollective with Chef - cfgmgmtcamp.eu 2014
Using MCollective with Chef - cfgmgmtcamp.eu 2014Using MCollective with Chef - cfgmgmtcamp.eu 2014
Using MCollective with Chef - cfgmgmtcamp.eu 2014Zachary Stevens
Ā 
File upload-vulnerability-in-fck editor
File upload-vulnerability-in-fck editorFile upload-vulnerability-in-fck editor
File upload-vulnerability-in-fck editorPaolo Dolci
Ā 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theoryMukesh Tekwani
Ā 
Introduction to Apache Web Services using latex
 Introduction to Apache Web Services using latex Introduction to Apache Web Services using latex
Introduction to Apache Web Services using latexManash Kumar Mondal
Ā 
What is Node.js? (ICON UK)
What is Node.js? (ICON UK)What is Node.js? (ICON UK)
What is Node.js? (ICON UK)Tim Davis
Ā 
Web Server(Apache),
Web Server(Apache), Web Server(Apache),
Web Server(Apache), webhostingguy
Ā 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
Ā 
Apache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya KulkarniApache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya Kulkarniwebhostingguy
Ā 

What's hot (20)

Web
WebWeb
Web
Ā 
Bp101-Can Domino Be Hacked
Bp101-Can Domino Be HackedBp101-Can Domino Be Hacked
Bp101-Can Domino Be Hacked
Ā 
java networking
 java networking java networking
java networking
Ā 
OSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven Nierlein
OSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven NierleinOSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven Nierlein
OSMC 2018 | Thruk 2Ā½ ā€“ Current state of development by Sven Nierlein
Ā 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF Workshop
Ā 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
Ā 
A.java
A.javaA.java
A.java
Ā 
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
Ā 
02 wireshark http-sept_15_2009
02   wireshark http-sept_15_200902   wireshark http-sept_15_2009
02 wireshark http-sept_15_2009
Ā 
Using MCollective with Chef - cfgmgmtcamp.eu 2014
Using MCollective with Chef - cfgmgmtcamp.eu 2014Using MCollective with Chef - cfgmgmtcamp.eu 2014
Using MCollective with Chef - cfgmgmtcamp.eu 2014
Ā 
Java Networking
Java NetworkingJava Networking
Java Networking
Ā 
Apache web server
Apache web serverApache web server
Apache web server
Ā 
File upload-vulnerability-in-fck editor
File upload-vulnerability-in-fck editorFile upload-vulnerability-in-fck editor
File upload-vulnerability-in-fck editor
Ā 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theory
Ā 
Apache web service
Apache web serviceApache web service
Apache web service
Ā 
Introduction to Apache Web Services using latex
 Introduction to Apache Web Services using latex Introduction to Apache Web Services using latex
Introduction to Apache Web Services using latex
Ā 
What is Node.js? (ICON UK)
What is Node.js? (ICON UK)What is Node.js? (ICON UK)
What is Node.js? (ICON UK)
Ā 
Web Server(Apache),
Web Server(Apache), Web Server(Apache),
Web Server(Apache),
Ā 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Ā 
Apache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya KulkarniApache Web Server Architecture Chaitanya Kulkarni
Apache Web Server Architecture Chaitanya Kulkarni
Ā 

Similar to Windows Phone 8 - 12 Network Communication

16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming ServersAdil Jafri
Ā 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
Ā 
HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014Christian Wenz
Ā 
signalr
signalrsignalr
signalrOwen Chen
Ā 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescueMarko Heijnen
Ā 
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysUsing communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysCodemotion Tel Aviv
Ā 
Web servers for the Internet of Things
Web servers for the Internet of ThingsWeb servers for the Internet of Things
Web servers for the Internet of ThingsAlexandru Radovici
Ā 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldPrabhakaran Soundarapandian
Ā 
Add a web server
Add a web serverAdd a web server
Add a web serverAgCharu
Ā 
SignalR: Add real-time to your applications
SignalR: Add real-time to your applicationsSignalR: Add real-time to your applications
SignalR: Add real-time to your applicationsEugene Zharkov
Ā 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIKevin Hazzard
Ā 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.pptwebhostingguy
Ā 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servletsdeepak kumar
Ā 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
Ā 
Using Communication and Messaging API in the HTML5 World
Using Communication and Messaging API in the HTML5 WorldUsing Communication and Messaging API in the HTML5 World
Using Communication and Messaging API in the HTML5 WorldGil Fink
Ā 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at ScaleJUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at ScaleC2B2 Consulting
Ā 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
Ā 

Similar to Windows Phone 8 - 12 Network Communication (20)

Philly Tech Fest Iis
Philly Tech Fest IisPhilly Tech Fest Iis
Philly Tech Fest Iis
Ā 
16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming Servers
Ā 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Ā 
HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014
Ā 
signalr
signalrsignalr
signalr
Ā 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescue
Ā 
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysUsing communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Ā 
Web servers for the Internet of Things
Web servers for the Internet of ThingsWeb servers for the Internet of Things
Web servers for the Internet of Things
Ā 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
Ā 
Web server
Web serverWeb server
Web server
Ā 
Add a web server
Add a web serverAdd a web server
Add a web server
Ā 
Web servers
Web serversWeb servers
Web servers
Ā 
SignalR: Add real-time to your applications
SignalR: Add real-time to your applicationsSignalR: Add real-time to your applications
SignalR: Add real-time to your applications
Ā 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
Ā 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
Ā 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
Ā 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
Ā 
Using Communication and Messaging API in the HTML5 World
Using Communication and Messaging API in the HTML5 WorldUsing Communication and Messaging API in the HTML5 World
Using Communication and Messaging API in the HTML5 World
Ā 
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at ScaleJUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
JUDCon 2013- JBoss Data Grid and WebSockets: Delivering Real Time Push at Scale
Ā 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Ā 

More from Oliver Scheer

Windows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone StoreWindows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone StoreOliver Scheer
Ā 
Windows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app PurchaseWindows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app PurchaseOliver Scheer
Ā 
Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsOliver Scheer
Ā 
Windows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using SpeechWindows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using SpeechOliver Scheer
Ā 
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and BluetoothWindows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and BluetoothOliver Scheer
Ā 
Windows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationWindows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationOliver Scheer
Ā 
Windows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesWindows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesOliver Scheer
Ā 
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen NotificationsWindows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen NotificationsOliver Scheer
Ā 
Windows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsWindows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsOliver Scheer
Ā 
Windows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application LifecycleWindows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application LifecycleOliver Scheer
Ā 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
Ā 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentWindows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentOliver Scheer
Ā 
Windows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 ApplicationsWindows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 ApplicationsOliver Scheer
Ā 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageOliver Scheer
Ā 
Windows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 ApplicationsWindows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 ApplicationsOliver Scheer
Ā 

More from Oliver Scheer (15)

Windows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone StoreWindows Phone 8 - 17 The Windows Phone Store
Windows Phone 8 - 17 The Windows Phone Store
Ā 
Windows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app PurchaseWindows Phone 8 - 16 Wallet and In-app Purchase
Windows Phone 8 - 16 Wallet and In-app Purchase
Ā 
Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and Maps
Ā 
Windows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using SpeechWindows Phone 8 - 14 Using Speech
Windows Phone 8 - 14 Using Speech
Ā 
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and BluetoothWindows Phone 8 - 13 Near Field Communcations and Bluetooth
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Ā 
Windows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App CommunicationWindows Phone 8 - 11 App to App Communication
Windows Phone 8 - 11 App to App Communication
Ā 
Windows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone ResourcesWindows Phone 8 - 10 Using Phone Resources
Windows Phone 8 - 10 Using Phone Resources
Ā 
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen NotificationsWindows Phone 8 - 8 Tiles and Lock Screen Notifications
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Ā 
Windows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background AgentsWindows Phone 8 - 6 Background Agents
Windows Phone 8 - 6 Background Agents
Ā 
Windows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application LifecycleWindows Phone 8 - 5 Application Lifecycle
Windows Phone 8 - 5 Application Lifecycle
Ā 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
Ā 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 DevelopmentWindows Phone 8 - 1 Introducing Windows Phone 8 Development
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Ā 
Windows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 ApplicationsWindows Phone 8 - 3 Building WP8 Applications
Windows Phone 8 - 3 Building WP8 Applications
Ā 
Windows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and StorageWindows Phone 8 - 4 Files and Storage
Windows Phone 8 - 4 Files and Storage
Ā 
Windows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 ApplicationsWindows Phone 8 - 2 Designing WP8 Applications
Windows Phone 8 - 2 Designing WP8 Applications
Ā 

Recently uploaded

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
Ā 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
Ā 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
Ā 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
Ā 
FULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | DelhiFULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | Delhisoniya singh
Ā 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
Ā 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
Ā 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
Ā 
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...Patryk Bandurski
Ā 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
Ā 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
Ā 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
Ā 
SIEMENS: RAPUNZEL ā€“ A Tale About Knowledge Graph
SIEMENS: RAPUNZEL ā€“ A Tale About Knowledge GraphSIEMENS: RAPUNZEL ā€“ A Tale About Knowledge Graph
SIEMENS: RAPUNZEL ā€“ A Tale About Knowledge GraphNeo4j
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
Ā 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
Ā 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
Ā 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
Ā 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
Ā 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
Ā 

Recently uploaded (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
Ā 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
Ā 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
Ā 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
Ā 
FULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | DelhiFULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY šŸ” 8264348440 šŸ” Call Girls in Diplomatic Enclave | Delhi
Ā 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Ā 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
Ā 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
Ā 
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Integration and Automation in Practice: CI/CD in MuleĀ Integration and Automat...
Ā 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
Ā 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Ā 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Ā 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
Ā 
SIEMENS: RAPUNZEL ā€“ A Tale About Knowledge Graph
SIEMENS: RAPUNZEL ā€“ A Tale About Knowledge GraphSIEMENS: RAPUNZEL ā€“ A Tale About Knowledge Graph
SIEMENS: RAPUNZEL ā€“ A Tale About Knowledge Graph
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
Ā 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
Ā 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
Ā 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
Ā 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
Ā 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
Ā 

Windows Phone 8 - 12 Network Communication

  • 1. Oliver Scheer Senior Technical Evangelist Microsoft Deutschland http://the-oliver.com Network Communication in Windows Phone 8
  • 2. Agenda ļ‚§ Networking for Windows Phone ļ‚§ WebClient ļ‚§ HttpWebRequest ļ‚§ Sockets ļ‚§ Web Services and OData ļ‚§ Simulation Dashboard ļ‚§ Data Compression
  • 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 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. 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. 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. Connecting the Emulator to Local Services 3/19/20148
  • 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. ā€¢ 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. ā€¢ 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. ā€¢ 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. ā€¢ 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. ā€¢ 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
  • 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. ā€¢ 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. Demo 1: Simple HTTP Networking with WebClient
  • 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. 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. 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. 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. 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; } }
  • 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
  • 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. 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. 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. 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. 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. 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)); } }
  • 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. 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. 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. 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
  • 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. 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. 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. 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
  • 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. ā€¢ 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. 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.
  • 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. 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. 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. 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. 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. 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. 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.