S11 Network Communication.pdf
-
Upload
edmundo-lozada -
Category
Documents
-
view
236 -
download
0
Transcript of S11 Network Communication.pdf
-
7/22/2019 S11 Network Communication.pdf
1/63
M11: Network Communication
in Windows Phone 8
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
4/63
Networking for Windows Phone
WebClient
HttpWebRequest
Sockets
Web Services and OData
Simulation Dashboard
Data Compression
Module Agenda
-
7/22/2019 S11 Network Communication.pdf
5/63
Networking for
Windows Phone
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
10/63
Connecting the Emulator
to Local Services
-
7/22/2019 S11 Network Communication.pdf
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/ -
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
13/63
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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 -
7/22/2019 S11 Network Communication.pdf
16/63
WebClient
-
7/22/2019 S11 Network Communication.pdf
17/63
Simple Http Operations WebClient
usingSystem.Net;...
WebClient client;
// Constructorpublic MainPage(){
...client = newWebClient();client.DownloadStringCompleted += client_DownloadStringCompleted;
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEvent{
this.downloadedText = e.Result;}
privatevoid loadButton_Click(object sender, RoutedEventArgs e){
client.DownloadStringAsync(newUri("http://MyServer/ServicesApplication/rss
}
-
7/22/2019 S11 Network Communication.pdf
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;...
privateasyncvoid loadButton_Click(object sender, RoutedEventArgs e){
var client = newWebClient();string response = await client.DownloadStringTaskAsync(newUri("http://MyServer/ServicesApplication/r
this.downloadedText = response;}
-
7/22/2019 S11 Network Communication.pdf
19/63
Demo 1: Simple HTTP
Networking
with WebClient
-
7/22/2019 S11 Network Communication.pdf
20/63
More Control HttpWebRequest
privatevoid PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){var request = 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
-
7/22/2019 S11 Network Communication.pdf
21/63
HttpWebRequest Response Handlingprivatevoid GotResponse(IAsyncResult asynchronousResult){
try{string data;// State of request is asynchronousHttpWebRequest myHttpWebRequest = (HttpWebRequest)asynchronousResult.AsyncState; ;using(HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asyn{// 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 this.Dispatcher.BeginInvoke(() =>{MessageBox.Show("Received payload of " + data.Length + " characters");
} );}
catch (Exception e) ...}
-
7/22/2019 S11 Network Communication.pdf
22/63
HttpWebRequest Error Handling
privatevoid GotResponse(IAsyncResult asynchronousResult){
try{
// Handle the Response...
}catch (Exception e){var we = e.InnerException asWebException;if (we != null){var resp = we.Response asHttpWebResponse;var code = resp.StatusCode;
this.Dispatcher.BeginInvoke(() =>{MessageBox.Show("RespCallback Exception raised! Message:" + we.Message +
"HTTP Status: " + we.Status);});
}elsethrow;
}}
-
7/22/2019 S11 Network Communication.pdf
23/63
HttpWebRequest Using TPL Patternprivateasyncvoid PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){var request = HttpWebRequest.Create("http://rockstar:15500/NorthwindDataService.svc/Supplie
asHttpWebRequest;request.Accept = "application/json;odata=verbose";
// Use the Task Parallel Library patternvar factory = newTaskFactory();var task = factory.FromAsync(request.BeginGetResponse, request.EndGetResponse,
try{var response = await task;
// Read the response into a Stream object.System.IO.StreamresponseStream = response.GetResponseStream();
stringdata;using (var reader = new System.IO.StreamReader(responseStream)){data = reader.ReadToEnd();
}responseStream.Close();
MessageBox.Show("Received payload of " + data.Length + " characters");}catch (Exception ex)...
-
7/22/2019 S11 Network Communication.pdf
24/63
HttpWebRequest (TPL) Error Handling
privateasyncvoid PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){
try{// Make the call and handle the Response...
}catch (Exception e){var we = e.InnerException asWebException;if (we != null){
var resp = we.Response asHttpWebResponse;var code = resp.StatusCode;MessageBox.Show("RespCallback Exception raised! Message:" + we.Message +
"HTTP Status: " + we.Status);}elsethrow e;
}}
-
7/22/2019 S11 Network Communication.pdf
25/63
Demo 2:
HttpWebRequest
-
7/22/2019 S11 Network Communication.pdf
26/63
Sockets
-
7/22/2019 S11 Network Communication.pdf
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!
-
7/22/2019 S11 Network Communication.pdf
28/63
Web Services
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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/ -
7/22/2019 S11 Network Communication.pdf
34/63
Fetching Data
publicpartialclassNorthwindModel{
NorthwindEntities context;privateDataServiceCollection customers;
privateoverridevoid LoadData(){
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.var query = from cust in context.Customers
select cust;
// Register for the LoadCompleted event.customers.LoadCompleted += newEventHandler(customers_Loa
// Load the customers feed by executing the LINQ query.customers.LoadAsync(query);
}...
-
7/22/2019 S11 Network Communication.pdf
35/63
Fetching Data - LoadCompleted
36
...
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 collectionApp.ViewModel.Customers.Add( newCustomerViewModel(){SelectedCustomer = c}
}}
}else{
MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message));}
}
-
7/22/2019 S11 Network Communication.pdf
36/63
Demo 3:
OData Services
-
7/22/2019 S11 Network Communication.pdf
37/63
Network Information
and Efficiency
k
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
40/63
Determining the Current Internet Connection Type
privateconstint IANA_INTERFACE_TYPE_OTHER = 1;privateconstint IANA_INTERFACE_TYPE_ETHERNET = 6;privateconstint IANA_INTERFACE_TYPE_PPP = 23;privateconstint IANA_INTERFACE_TYPE_WIFI = 71;...string network = string.Empty;
// Get current Internet Connection Profile.ConnectionProfile internetConnectionProfile =
Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfil
switch (internetConnectionProfile.NetworkAdapter.IanaInterfaceType){
case IANA_INTERFACE_TYPE_OTHER:
cost += "Network: Other"; break;caseIANA_INTERFACE_TYPE_ETHERNET:
cost += "Network: Ethernet"; break;case IANA_INTERFACE_TYPE_WIFI:
cost += "Network: Wifi\r\n"; break;default:
cost += "Network: Unknown\r\n"; break;}
Ti f N t k Effi i
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
42/63
Demo 4: Wire Serialization
Wi e Se iali ation Affects Pa oll Si e
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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/ -
7/22/2019 S11 Network Communication.pdf
45/63
HttpWebRequest With Compression
var request = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/SuppliasHttpWebRequest;
request.Accept = "application/json;odata=verbose";
request.Headers["Accept_Encoding"] = "gzip";
// Use the Task Parallel Library patternvar factory = newTaskFactory();var task = factory.FromAsync(request.BeginGetResponse, request.EndGetRespon
var response = await task;
// Read the response into a Stream object.System.IO.Stream responseStream = response.GetResponseStream();string data;var stream = newGZipInputStream(response.GetResponseStream());using (var reader = new System.IO.StreamReader(stream)){data = reader.ReadToEnd();
}responseStream.Close();
Compression with OData Client Library
-
7/22/2019 S11 Network Communication.pdf
46/63
Compression with OData Client Library
privatevoid EnableGZipResponses(DataServiceContext ctx){
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 -
7/22/2019 S11 Network Communication.pdf
47/63
Demo 5:
Compression
48
-
7/22/2019 S11 Network Communication.pdf
48/63
Data Sense
Data Sense API
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
50/63
Using the Data Sense APIs
1. Get the Network Type from the
ConnectionProfile by calling NetworkInformation.GetInternetConnectionClient
2. Get the NetworkCostType by callingConnectionProfile.GetConnectionCost
3. Get the ApproachingDataLimit,OverDataLimit and Roaming properties 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
-
7/22/2019 S11 Network Communication.pdf
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
Fixed or Variable
All three of the followingproperties are false.ApproachingDataLimitOverDataLimitRoaming
No restrictions.
Stream hDownloapictures.Retrieve e
Fixed or 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.
Fixed or VariableOverDataLimit or Roaming istrue
Dont transfer data.Provide option to override.
Stop dowStop dowDo not rePostpone
-
7/22/2019 S11 Network Communication.pdf
52/63
Network Security
Encrypting the Communication
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
55/63
dd g C ede t a s to a ttp eb equest
privatevoid PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){var request = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Supplie
as HttpWebRequest;request.Credentials = new Credentials("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
-
7/22/2019 S11 Network Communication.pdf
56/63
yp g g
privatevoid 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();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
-
7/22/2019 S11 Network Communication.pdf
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.Stream reader = 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.string data = Encoding.UTF8.GetString(clearTextBytes, 0, clearTextBytes.Length);
-
7/22/2019 S11 Network Communication.pdf
58/63
Storing Data in the Cloud
Live SDK
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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/ -
7/22/2019 S11 Network Communication.pdf
61/63
Demo :Windows Azure Mobile Services
Summary
-
7/22/2019 S11 Network Communication.pdf
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
-
7/22/2019 S11 Network Communication.pdf
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.