SlideShare ist ein Scribd-Unternehmen logo
1 von 74
Downloaden Sie, um offline zu lesen
Windows Store +
Silverlight 8.1
30 April 2014
Building Apps for Windows Phone 8.1 Jump Start
API WP7.1/WP8 Windows 8.1 Windows Phone 8.1
System.Net.WebClient   
System.Net.HttpWebRequest  (async only) (async only)
System.Net.Http.HttpClient  (NuGet)  
Windows.Web.Http.HttpClient   
Windows.Web.Syndication.SyndicationClient   
Windows.Web.AtomPub.AtomPubClient   
ASMX Web Services  
 (Windows Store)
 (Silverlight)
WCF Services  
 (Windows Store)
 (Silverlight)
OData Services   
http://manage.windowsazure.com
12
13
14
private async System.Threading.Tasks.Task InsertToDoItem()
{
IMobileServiceTable<TodoItem> TodoTable = App.TaskMasterDemoClient.GetTable<TodoItem>();
TodoItem t = new TodoItem();
t.Title = titleTextBox.Text;
t.Description = descriptionTextBox.Text;
t.DueDate = dueDatePicker.Date.ToString();
t.AssignedTo = assignedToTextBox.Text;
try
{
await TodoTable.InsertAsync(t);
}
catch (Exception)
{ /* TODO: Insert error handling code */ }
}
15
16
1 of 2
async void DownloadFile(Uri sourceUri, string destFilename)
{
cts = new CancellationTokenSource();
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
destFilename, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(sourceUri, destinationFile);
try
{
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
// Start the download and attach a progress handler.
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
catch (TaskCanceledException) { /* User cancelled the transfer */ }
catch (Exception ex) { /* ... */ }
}
2 of 2
private void CancelAll_Click(object sender, RoutedEventArgs e)
{
cts.Cancel();
cts.Dispose();
cts = new CancellationTokenSource(); // Re-create the CancellationTokenSource for future downloads.
}
private void DownloadProgress(DownloadOperation download)
{
double percent = 100;
if (download.Progress.TotalBytesToReceive > 0)
percent = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive;
if (download.Progress.HasRestarted)
{ /* Download restarted */ };
if (download.Progress.HasResponseChanged) // We've received new response headers from the server.
Debug.WriteLine(" - Response updated; Header count: " + download.GetResponseInformation().Headers.Count);
}
try
{
// Create the HttpClient
HttpClient httpClient = new HttpClient();
// Optionally, define HTTP headers
httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
// Make the call
string responseText = await httpClient.GetStringAsync(
new Uri("http://services.odata.org/Northwind/Northwind.svc/Suppliers"));
}
catch (Exception ex)
{
...
}
try
{
var client = new HttpClient();
var uri = new Uri(" http://example.com/customers/1");
var response = await client.GetAsync(uri);
// code and results
var statusCode = response.StatusCode;
// EnsureSuccessStatusCode throws exception if not HTTP 200
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
...
}
HttpClient
If you want response codes, headers, and other information, use GetAsync instead of GetStringAsync
Content
Headers
StatusCode
ReasonPhrase
IsSuccessStatusCode
Source
Version
RequestMessage
try
{
var client = new HttpClient();
var uri = new Uri("http://example.com/customers/1");
var response = await client.GetAsync(uri);
// display headers
foreach (var header in response.Headers)
{
HeadersText.Text += header.Key + " = " + header.Value + "n" ;
}
ResultsText.Text = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{ ...}
var client = new HttpClient();
// set some headers
var headers = client.DefaultRequestHeaders;
headers.Referer = new Uri("http://contoso.com");
var ok = headers.UserAgent.TryParseAdd("testprogram/1.0");
// make the request
var response = await client.GetAsync(uri);
// get response content length
var length = response.Content.Headers.ContentLength.Value;
byte[] buffer = new byte[length];
Headers
Strongly typed headers make setting and getting values simple and safe.
Use the TryParseAdd method to receive a bool on failure rather than an
exception
Header Access
Accept read/write collection
AcceptEncoding read/write collection
AcceptLanguage read/write collection
Authorization read/write
CacheControl read/write collection
Connection read/write collection
Cookie read/write collection
Date read/write
Expect read/write collection
From read/write
Host read/write
IfModifiedSince read/write
IfUnmodifiedSince read/write
MaxForwards read/write
ProxyAuthorization read/write
Referer read/write
TransferEncoding read/write collection
UserAgent read/write collection
SendRequestAsync
The HttpClient includes discrete methods for Put and Post, but you can also use the SendRequestAsync
method to make any type of request, including Delete.
try
{
var client = new HttpClient();
// we're sending a delete request
var request = new HttpRequestMessage(HttpMethod.Delete, uri);
// we don't expect a response, but we'll snag it anyway
var response = await client.SendRequestAsync(request);
// display result code
HeadersText.Text = "Status: " + response.StatusCode + "n";
}
catch (Exception ex)
{ … }
Delete
Get
Head
Options
Patch
Post
Put
Also, new
HttpMethod(string) for
your own methods
var uri = new Uri("http://example.com/customers/1");
try
{
var baseFilter = new HttpBaseProtocolFilter();
var cookieManager = baseFilter.CookieManager;
var cookie = new HttpCookie("favoriteColor", ".example.com", "/")
{ Value = "purple"};
cookieManager.SetCookie(cookie);
var client = new HttpClient(baseFilter);
await client.PostAsync(uri, new HttpStringContent("Pete"));
}
catch (Exception ex) { ... }
var baseFilter = new HttpBaseProtocolFilter();
var cookieManager = baseFilter.CookieManager;
var client = new HttpClient(baseFilter);
var cookies = cookieManager.GetCookies(uri);
// display cookies
foreach (var cookie in cookies)
{
CookieList.Text += cookie.Name + " = " + cookie.Value + "n";
}
REST /
Web
Service
HttpClient
GetAsync
GetBufferAsync
GetInputStreamAsync
GetStringAsync
PostAsync
PutAsync
SendRequestAsync
HttpRequestMessage
HttpResponseMessage
Http Base
Protocol Filter
Has in-depth settings
HttpContent
String • Stream • Buffer •
Multipart • FormUrlEncoded
⛭
Your code This is also a filter
For compression, credentials etc
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
// When AutomaticDecompression is true (the default), the Accept-Encoding header is added
// to the headers and set to allow gzip and compress
filter.AutomaticDecompression = true;
PasswordCredential creds = new PasswordCredential("JumpStart", userName, password);
filter.ServerCredential = creds;
filter.ProxyCredential = creds;
// Create the HttpClient
HttpClient httpClient = new HttpClient(filter);
// Make the call
string responseText = await httpClient.GetStringAsync(uri);
...
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 (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
Wire Serialization Format Size in Bytes
ODATA XML 73786
ODATA JSON 34030
JSON ‘Lite’ 15540
JSON ‘Lite’ GZip 8680
Making Decisions based on Data Connections
Use the NetworkInterfaceType object to detect network type and speed
Subscribe to the NetworkChange event to detect when network state changes
Make your app aware of its networking environment and
state!
41
private bool IsOnWiFi()
{
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile == null) return false;
return InternetConnectionProfile.IsWlanConnectionProfile;
}
private bool IsConnectedtoDataRoaming()
{
bool isRoaming = false;
ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile != null && internetConnectionProfile.IsWwanConnectionProfile)
{
ConnectionCost cc = internetConnectionProfile.GetConnectionCost();
isRoaming = cc.Roaming; // See if user is currently roaming
}
return isRoaming;
}
private void AddEventHandlers()
{
// NetworkStatusChanged fires when the network status changes for a connection
NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;
}
42
43
44
45
ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile != null)
{
if (internetConnectionProfile.IsWlanConnectionProfile)
{
// connected on WiFi interface; double check it is not a metered WiFi hotspot
ConnectionCost cc = internetConnectionProfile.GetConnectionCost();
if ((NetworkCostType.Unknown == cc.NetworkCostType)
|| (NetworkCostType.Unrestricted == cc.NetworkCostType))
{
// assume free network; connect and start streaming content
}
}
else if (internetConnectionProfile.IsWwanConnectionProfile)
{
...
46
else if (InternetConnectionProfile.IsWwanConnectionProfile)
{
ConnectionCost cc = InternetConnectionProfile.GetConnectionCost();
// check the type of data plan - make sure user is not currently roaming
if (!cc.Roaming)
{
if ((NetworkCostType.Unknown == cc.NetworkCostType) || (NetworkCostType.Unrestricted == cc.NetworkCostType))
{
// assume free network; connect and start streaming content
}
else if (NetworkCostType.Fixed == cc.NetworkCostType)
{
// make sure user not currently over limit or near limit
if ((!cc.OverDataLimit) && (!cc.ApproachingDataLimit))
{
// connect and start streaming content
}
}
}
}
47
ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (internetConnectionProfile != null && internetConnectionProfile.IsWwanConnectionProfile)
{
ConnectionCost cc = internetConnectionProfile.GetConnectionCost();
if (!cc.Roaming) // check the type of data plan, make sure user is not currently roaming
{
if (NetworkCostType.Fixed == cc.NetworkCostType)
{
if (cc.ApproachingDataLimit) // making smart decisions if close to data limit
{
DataPlanStatus dps = internetConnectionProfile.GetDataPlanStatus(); // get current data plan status and usage
DataPlanUsage dpu = dps.DataPlanUsage;
UInt32 DataUsed = dpu.MegabytesUsed;
UInt32? DataLimit = dps.DataLimitInMegabytes;
DateTimeOffset? BillingDate = dps.NextBillingCycle;
// calculate how much data plan is still available for use.
// If larger than size of data to be transferred, connect, else wait for WiFi connection to be available
...
}
}
}
}
48
// only want to connect using the WiFi interface; register for network status change notifications
static bool registeredNetworkStatusNotif = false;
NetworkStatusChangedEventHandler networkStatusCallback = null;
private void Setup()
{
networkStatusCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange);
if (!registeredNetworkStatusNotif)
{
NetworkInformation.NetworkStatusChanged += networkStatusCallback;
registeredNetworkStatusNotif = true;
}
}
...
49
// Event handler for Network Status Change event
async void OnNetworkStatusChange(object sender)
{
// get the ConnectionProfile that is currently used to connect to the Internet
ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
// Figure out which network state event is it
if (InternetConnectionProfile != null) // Null if not connected to internet...
{
// check whether the new connection profile is over WiFi
if (InternetConnectionProfile.IsWlanConnectionProfile)
{
// connected on WiFi interface; double check it is not a metered WiFi hotspot
ConnectionCost cc = InternetConnectionProfile.GetConnectionCost();
if ((NetworkCostType.Unknown == cc.NetworkCostType) || (NetworkCostType.Unrestricted == cc.NetworkCostType))
{
// start thread to connect and get content
...
}
}
}
}
3/18/2022
50
The Paradox: Users dislike signing on…
App A
App B
MSA
void SaveCredential(string username, string password)
{
PasswordVault vault = new PasswordVault();
PasswordCredential cred = new PasswordCredential("MyAppResource", username, password);
vault.Add(cred);
}
IReadOnlyList<PasswordCredential> RetrieveCredential(string resource)
{
PasswordVault vault = new PasswordVault();
return vault.FindAllByResource(resource);
}
Online
service
1. Authorization Request (Start URL)
6. Authorization token (Redirect URL)
7. Data access
User
Web auth broker
Online
service
1. Authorization request (Start URL)
6. Authorization token (Redirect URL)
WinRT
Dialog
User
Windows Phone 8.1 app
7. Data access
// Authenticate using WAB
async void Authenticate()
{
WebAuthenticationResult result =
await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None, startUri, endUri);
if (WebAuthenticationResult.ResponseStatus ==
WebAuthenticationStatus.Success)
{
// Parse the returned data to get the token out
// token is used in requests to online service
GetToken(WebAuthenticationResult.ResponseData);
}
else
{
// handle failures (user cancel, HTTP error)
}
}
//Initiate authentication using WAB
void Authenticate()
{
WebAuthenticationBroker.AuthenticateAndContinue(
startUri, endUri);
}
{
// Code runs on reactivation to handle response from WAB
}
protected override async void OnActivated(IActivatedEventArgs args)
{
if (args is WebAuthenticationBrokerContinuationEventArgs)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do standard logic to create the Frame if necessary and restore state
if (rootFrame == null)
{
rootFrame = new Frame();
SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
try { await SuspensionManager.RestoreAsync(); }
catch (SuspensionManagerException) { }
}
// Place the frame in the current Window.
Window.Current.Content = rootFrame;
}
...
...
if (rootFrame.Content == null)
{
if (!rootFrame.Navigate(typeof(MyPageThatDoesAuth)))
{
throw new Exception("Failed to create target page");
}
}
// Pass the continuation event args to the target page
var p = rootFrame.Content as MyPageThatDoesAuth;
// ContinuationArgs is a property that we’ve added to MyPageThatDoesAuth
p.ContinuationArgs = (WebAuthenticationBrokerContinuationEventArgs)args;
// Ensure the current window is active
Window.Current.Activate();
}
}
private WebAuthenticationBrokerContinuationEventArgs _continuationArgs = null;
public WebAuthenticationBrokerContinuationEventArgs ContinuationArgs
{
get { return _continuationArgs; }
set {
_continuationArgs = value;
ContinueWebAuthentication(_continuationArgs); }
}
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
String outputToken = result.ResponseData.ToString();
await DoSomethingWithTheTokenAsync(outputToken);
}
else { /* handle failures (user cancel, HTTP error) */ }
}
Contoso
1 2 3
Credentials
pre-populated
if any app
previously
authenticated
to this
provider
69
Kernel Mode
User Mode (App Container) User Mode (Medium)
https://contoso.com
SID: S-1-5-4321
Contoso verifies the redirect URL for its apps
(e.g. MyPhotoApp registered ms-app://S-1-5-4321)
https://contoso.com?ContosoAppID=MyPhotoApp,
redirectURI=ms-app://S-1-5-4321,…
void AuthenticateSSO()
{
// Not specifying an endUri tells WAB to use SSO mode
WebAuthenticationBroker.AuthenticateAndContinue(startUri);
}
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
GetToken(result.ResponseData);
}
...
}
©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the
U.S. and/or other countries. The information herein is for informational purposes only and 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. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Weitere ähnliche Inhalte

Was ist angesagt?

Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Mumbai B.Sc.IT Study
 
dotSwift - From Problem to Solution
dotSwift - From Problem to SolutiondotSwift - From Problem to Solution
dotSwift - From Problem to Solutionsoroushkhanlou
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi clientichsanbarokah
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]User1test
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
Descargar datos con JSON en Android
Descargar datos con JSON en AndroidDescargar datos con JSON en Android
Descargar datos con JSON en Android★ Raúl Laza
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harianKhairunnisaPekanbaru
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2RORLAB
 

Was ist angesagt? (18)

Easy Button
Easy ButtonEasy Button
Easy Button
 
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
Internet Technology (Practical Questions Paper) [CBSGS - 75:25 Pattern] {Mast...
 
dotSwift - From Problem to Solution
dotSwift - From Problem to SolutiondotSwift - From Problem to Solution
dotSwift - From Problem to Solution
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi client
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
JSON Android
JSON AndroidJSON Android
JSON Android
 
Descargar datos con JSON en Android
Descargar datos con JSON en AndroidDescargar datos con JSON en Android
Descargar datos con JSON en Android
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2Active Record Query Interface (1), Season 2
Active Record Query Interface (1), Season 2
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Code red SUM
Code red SUMCode red SUM
Code red SUM
 
Kode vb.net
Kode vb.netKode vb.net
Kode vb.net
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 

Andere mochten auch

South thailand conflict
South thailand conflictSouth thailand conflict
South thailand conflictTeeranan
 
проект диспетчеризации
проект диспетчеризациипроект диспетчеризации
проект диспетчеризацииZhivotovskayaA19
 
Cv Jorge Sanz Sande
Cv Jorge Sanz SandeCv Jorge Sanz Sande
Cv Jorge Sanz Sandeguest910468
 
Arch Digitals Brand Strategy
Arch Digitals Brand StrategyArch Digitals Brand Strategy
Arch Digitals Brand StrategyArchDigitals
 
Terrorism threat at the airport
Terrorism threat at the airportTerrorism threat at the airport
Terrorism threat at the airportTeeranan
 
проект диспетчеризации
проект диспетчеризациипроект диспетчеризации
проект диспетчеризацииZhivotovskayaA19
 
Vacaciones de veranoalexispacheco
Vacaciones de veranoalexispachecoVacaciones de veranoalexispacheco
Vacaciones de veranoalexispachecoSextoABicentenario
 
New media and national security contents
New media and national security contentsNew media and national security contents
New media and national security contentsTeeranan
 
Web 2 Karpicius
Web 2 KarpiciusWeb 2 Karpicius
Web 2 Karpiciusrodriz
 
160105 La selección española ha sido recibida este mediodía en la Diputación ...
160105 La selección española ha sido recibida este mediodía en la Diputación ...160105 La selección española ha sido recibida este mediodía en la Diputación ...
160105 La selección española ha sido recibida este mediodía en la Diputación ...Diputación Foral de Gipuzkoa
 
Break Through the Barriers of Small Business Financing
Break Through the Barriers of Small Business FinancingBreak Through the Barriers of Small Business Financing
Break Through the Barriers of Small Business FinancingGreenBizNetwork
 
Θερμοδυναμική
ΘερμοδυναμικήΘερμοδυναμική
ΘερμοδυναμικήIoannisGatsios
 
Presentación formación en inglés
Presentación formación en inglésPresentación formación en inglés
Presentación formación en inglésfundablue
 
Cv Jorge Sanz Sande
Cv Jorge Sanz SandeCv Jorge Sanz Sande
Cv Jorge Sanz Sandeguest910468
 
Political warfare 55
Political warfare 55Political warfare 55
Political warfare 55Teeranan
 
National power in_politics
National power in_politicsNational power in_politics
National power in_politicsTeeranan
 

Andere mochten auch (20)

South thailand conflict
South thailand conflictSouth thailand conflict
South thailand conflict
 
проект диспетчеризации
проект диспетчеризациипроект диспетчеризации
проект диспетчеризации
 
CV4
CV4CV4
CV4
 
Cv Jorge Sanz Sande
Cv Jorge Sanz SandeCv Jorge Sanz Sande
Cv Jorge Sanz Sande
 
Arch Digitals Brand Strategy
Arch Digitals Brand StrategyArch Digitals Brand Strategy
Arch Digitals Brand Strategy
 
Terrorism threat at the airport
Terrorism threat at the airportTerrorism threat at the airport
Terrorism threat at the airport
 
проект диспетчеризации
проект диспетчеризациипроект диспетчеризации
проект диспетчеризации
 
Linkedin_PBV
Linkedin_PBVLinkedin_PBV
Linkedin_PBV
 
Partsofthesis
PartsofthesisPartsofthesis
Partsofthesis
 
Vacaciones de veranoalexispacheco
Vacaciones de veranoalexispachecoVacaciones de veranoalexispacheco
Vacaciones de veranoalexispacheco
 
New media and national security contents
New media and national security contentsNew media and national security contents
New media and national security contents
 
Web 2 Karpicius
Web 2 KarpiciusWeb 2 Karpicius
Web 2 Karpicius
 
160105 La selección española ha sido recibida este mediodía en la Diputación ...
160105 La selección española ha sido recibida este mediodía en la Diputación ...160105 La selección española ha sido recibida este mediodía en la Diputación ...
160105 La selección española ha sido recibida este mediodía en la Diputación ...
 
Break Through the Barriers of Small Business Financing
Break Through the Barriers of Small Business FinancingBreak Through the Barriers of Small Business Financing
Break Through the Barriers of Small Business Financing
 
Keeking
KeekingKeeking
Keeking
 
Θερμοδυναμική
ΘερμοδυναμικήΘερμοδυναμική
Θερμοδυναμική
 
Presentación formación en inglés
Presentación formación en inglésPresentación formación en inglés
Presentación formación en inglés
 
Cv Jorge Sanz Sande
Cv Jorge Sanz SandeCv Jorge Sanz Sande
Cv Jorge Sanz Sande
 
Political warfare 55
Political warfare 55Political warfare 55
Political warfare 55
 
National power in_politics
National power in_politicsNational power in_politics
National power in_politics
 

Ähnlich wie 13 networking, mobile services, and authentication

Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1Cristian González
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
Client server part 12
Client server part 12Client server part 12
Client server part 12fadlihulopi
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the networkMu Chun Wang
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applicationsAlex Golesh
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - AjaxWebStackAcademy
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWRSweNz FixEd
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdfNote Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdffatoryoutlets
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxcelenarouzie
 

Ähnlich wie 13 networking, mobile services, and authentication (20)

Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
Ajax
AjaxAjax
Ajax
 
servlets
servletsservlets
servlets
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
my accadanic project ppt
my accadanic project pptmy accadanic project ppt
my accadanic project ppt
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applications
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdfNote Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
 
State management
State managementState management
State management
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
Ajax
AjaxAjax
Ajax
 

Mehr von WindowsPhoneRocks

23 silverlight apps on windows phone 8.1
23   silverlight apps on windows phone 8.123   silverlight apps on windows phone 8.1
23 silverlight apps on windows phone 8.1WindowsPhoneRocks
 
22 universal apps for windows
22   universal apps for windows22   universal apps for windows
22 universal apps for windowsWindowsPhoneRocks
 
21 app packaging, monetization and publication
21   app packaging, monetization and publication21   app packaging, monetization and publication
21 app packaging, monetization and publicationWindowsPhoneRocks
 
19 programming sq lite on windows phone 8.1
19   programming sq lite on windows phone 8.119   programming sq lite on windows phone 8.1
19 programming sq lite on windows phone 8.1WindowsPhoneRocks
 
17 camera, media, and audio in windows phone 8.1
17   camera, media, and audio in windows phone 8.117   camera, media, and audio in windows phone 8.1
17 camera, media, and audio in windows phone 8.1WindowsPhoneRocks
 
16 interacting with user data contacts and appointments
16   interacting with user data contacts and appointments16   interacting with user data contacts and appointments
16 interacting with user data contacts and appointmentsWindowsPhoneRocks
 
15 sensors and proximity nfc and bluetooth
15   sensors and proximity nfc and bluetooth15   sensors and proximity nfc and bluetooth
15 sensors and proximity nfc and bluetoothWindowsPhoneRocks
 
14 tiles, notifications, and action center
14   tiles, notifications, and action center14   tiles, notifications, and action center
14 tiles, notifications, and action centerWindowsPhoneRocks
 
12 maps, geolocation, and geofencing
12   maps, geolocation, and geofencing12   maps, geolocation, and geofencing
12 maps, geolocation, and geofencingWindowsPhoneRocks
 
11 background tasks and multitasking
11   background tasks and multitasking11   background tasks and multitasking
11 background tasks and multitaskingWindowsPhoneRocks
 
10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8WindowsPhoneRocks
 
09 data storage, backup and roaming
09   data storage, backup and roaming09   data storage, backup and roaming
09 data storage, backup and roamingWindowsPhoneRocks
 
08 localization and globalization in windows runtime apps
08   localization and globalization in windows runtime apps08   localization and globalization in windows runtime apps
08 localization and globalization in windows runtime appsWindowsPhoneRocks
 
07 windows runtime app lifecycle
07   windows runtime app lifecycle07   windows runtime app lifecycle
07 windows runtime app lifecycleWindowsPhoneRocks
 
05 programming page controls and page transitions animations
05   programming page controls and page transitions animations05   programming page controls and page transitions animations
05 programming page controls and page transitions animationsWindowsPhoneRocks
 
04 lists and lists items in windows runtime apps
04   lists and lists items in windows runtime apps04   lists and lists items in windows runtime apps
04 lists and lists items in windows runtime appsWindowsPhoneRocks
 
03 page navigation and data binding in windows runtime apps
03   page navigation and data binding in windows runtime apps03   page navigation and data binding in windows runtime apps
03 page navigation and data binding in windows runtime appsWindowsPhoneRocks
 
02 getting started building windows runtime apps
02   getting started building windows runtime apps02   getting started building windows runtime apps
02 getting started building windows runtime appsWindowsPhoneRocks
 

Mehr von WindowsPhoneRocks (20)

3 554
3 5543 554
3 554
 
23 silverlight apps on windows phone 8.1
23   silverlight apps on windows phone 8.123   silverlight apps on windows phone 8.1
23 silverlight apps on windows phone 8.1
 
22 universal apps for windows
22   universal apps for windows22   universal apps for windows
22 universal apps for windows
 
21 app packaging, monetization and publication
21   app packaging, monetization and publication21   app packaging, monetization and publication
21 app packaging, monetization and publication
 
20 tooling and diagnostics
20   tooling and diagnostics20   tooling and diagnostics
20 tooling and diagnostics
 
19 programming sq lite on windows phone 8.1
19   programming sq lite on windows phone 8.119   programming sq lite on windows phone 8.1
19 programming sq lite on windows phone 8.1
 
17 camera, media, and audio in windows phone 8.1
17   camera, media, and audio in windows phone 8.117   camera, media, and audio in windows phone 8.1
17 camera, media, and audio in windows phone 8.1
 
16 interacting with user data contacts and appointments
16   interacting with user data contacts and appointments16   interacting with user data contacts and appointments
16 interacting with user data contacts and appointments
 
15 sensors and proximity nfc and bluetooth
15   sensors and proximity nfc and bluetooth15   sensors and proximity nfc and bluetooth
15 sensors and proximity nfc and bluetooth
 
14 tiles, notifications, and action center
14   tiles, notifications, and action center14   tiles, notifications, and action center
14 tiles, notifications, and action center
 
12 maps, geolocation, and geofencing
12   maps, geolocation, and geofencing12   maps, geolocation, and geofencing
12 maps, geolocation, and geofencing
 
11 background tasks and multitasking
11   background tasks and multitasking11   background tasks and multitasking
11 background tasks and multitasking
 
10 sharing files and data in windows phone 8
10   sharing files and data in windows phone 810   sharing files and data in windows phone 8
10 sharing files and data in windows phone 8
 
09 data storage, backup and roaming
09   data storage, backup and roaming09   data storage, backup and roaming
09 data storage, backup and roaming
 
08 localization and globalization in windows runtime apps
08   localization and globalization in windows runtime apps08   localization and globalization in windows runtime apps
08 localization and globalization in windows runtime apps
 
07 windows runtime app lifecycle
07   windows runtime app lifecycle07   windows runtime app lifecycle
07 windows runtime app lifecycle
 
05 programming page controls and page transitions animations
05   programming page controls and page transitions animations05   programming page controls and page transitions animations
05 programming page controls and page transitions animations
 
04 lists and lists items in windows runtime apps
04   lists and lists items in windows runtime apps04   lists and lists items in windows runtime apps
04 lists and lists items in windows runtime apps
 
03 page navigation and data binding in windows runtime apps
03   page navigation and data binding in windows runtime apps03   page navigation and data binding in windows runtime apps
03 page navigation and data binding in windows runtime apps
 
02 getting started building windows runtime apps
02   getting started building windows runtime apps02   getting started building windows runtime apps
02 getting started building windows runtime apps
 

Kürzlich hochgeladen

All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialJoão Esperancinha
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Mark Simos
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 

Kürzlich hochgeladen (20)

All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Kuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorialKuma Meshes Part I - The basics - A tutorial
Kuma Meshes Part I - The basics - A tutorial
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
Tampa BSides - The No BS SOC (slides from April 6, 2024 talk)
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 

13 networking, mobile services, and authentication

  • 1. Windows Store + Silverlight 8.1 30 April 2014 Building Apps for Windows Phone 8.1 Jump Start
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7. API WP7.1/WP8 Windows 8.1 Windows Phone 8.1 System.Net.WebClient    System.Net.HttpWebRequest  (async only) (async only) System.Net.Http.HttpClient  (NuGet)   Windows.Web.Http.HttpClient    Windows.Web.Syndication.SyndicationClient    Windows.Web.AtomPub.AtomPubClient    ASMX Web Services    (Windows Store)  (Silverlight) WCF Services    (Windows Store)  (Silverlight) OData Services   
  • 8.
  • 9.
  • 10.
  • 12. 12
  • 13. 13
  • 14. 14 private async System.Threading.Tasks.Task InsertToDoItem() { IMobileServiceTable<TodoItem> TodoTable = App.TaskMasterDemoClient.GetTable<TodoItem>(); TodoItem t = new TodoItem(); t.Title = titleTextBox.Text; t.Description = descriptionTextBox.Text; t.DueDate = dueDatePicker.Date.ToString(); t.AssignedTo = assignedToTextBox.Text; try { await TodoTable.InsertAsync(t); } catch (Exception) { /* TODO: Insert error handling code */ } }
  • 15. 15
  • 16. 16
  • 17.
  • 18.
  • 19.
  • 20. 1 of 2 async void DownloadFile(Uri sourceUri, string destFilename) { cts = new CancellationTokenSource(); StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync( destFilename, CreationCollisionOption.GenerateUniqueName); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(sourceUri, destinationFile); try { Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress); // Start the download and attach a progress handler. await download.StartAsync().AsTask(cts.Token, progressCallback); } catch (TaskCanceledException) { /* User cancelled the transfer */ } catch (Exception ex) { /* ... */ } }
  • 21. 2 of 2 private void CancelAll_Click(object sender, RoutedEventArgs e) { cts.Cancel(); cts.Dispose(); cts = new CancellationTokenSource(); // Re-create the CancellationTokenSource for future downloads. } private void DownloadProgress(DownloadOperation download) { double percent = 100; if (download.Progress.TotalBytesToReceive > 0) percent = download.Progress.BytesReceived * 100 / download.Progress.TotalBytesToReceive; if (download.Progress.HasRestarted) { /* Download restarted */ }; if (download.Progress.HasResponseChanged) // We've received new response headers from the server. Debug.WriteLine(" - Response updated; Header count: " + download.GetResponseInformation().Headers.Count); }
  • 22.
  • 23.
  • 24. try { // Create the HttpClient HttpClient httpClient = new HttpClient(); // Optionally, define HTTP headers httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); // Make the call string responseText = await httpClient.GetStringAsync( new Uri("http://services.odata.org/Northwind/Northwind.svc/Suppliers")); } catch (Exception ex) { ... }
  • 25.
  • 26.
  • 27. try { var client = new HttpClient(); var uri = new Uri(" http://example.com/customers/1"); var response = await client.GetAsync(uri); // code and results var statusCode = response.StatusCode; // EnsureSuccessStatusCode throws exception if not HTTP 200 response.EnsureSuccessStatusCode(); var responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { ... } HttpClient If you want response codes, headers, and other information, use GetAsync instead of GetStringAsync Content Headers StatusCode ReasonPhrase IsSuccessStatusCode Source Version RequestMessage
  • 28. try { var client = new HttpClient(); var uri = new Uri("http://example.com/customers/1"); var response = await client.GetAsync(uri); // display headers foreach (var header in response.Headers) { HeadersText.Text += header.Key + " = " + header.Value + "n" ; } ResultsText.Text = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { ...}
  • 29. var client = new HttpClient(); // set some headers var headers = client.DefaultRequestHeaders; headers.Referer = new Uri("http://contoso.com"); var ok = headers.UserAgent.TryParseAdd("testprogram/1.0"); // make the request var response = await client.GetAsync(uri); // get response content length var length = response.Content.Headers.ContentLength.Value; byte[] buffer = new byte[length]; Headers Strongly typed headers make setting and getting values simple and safe. Use the TryParseAdd method to receive a bool on failure rather than an exception Header Access Accept read/write collection AcceptEncoding read/write collection AcceptLanguage read/write collection Authorization read/write CacheControl read/write collection Connection read/write collection Cookie read/write collection Date read/write Expect read/write collection From read/write Host read/write IfModifiedSince read/write IfUnmodifiedSince read/write MaxForwards read/write ProxyAuthorization read/write Referer read/write TransferEncoding read/write collection UserAgent read/write collection
  • 30.
  • 31. SendRequestAsync The HttpClient includes discrete methods for Put and Post, but you can also use the SendRequestAsync method to make any type of request, including Delete. try { var client = new HttpClient(); // we're sending a delete request var request = new HttpRequestMessage(HttpMethod.Delete, uri); // we don't expect a response, but we'll snag it anyway var response = await client.SendRequestAsync(request); // display result code HeadersText.Text = "Status: " + response.StatusCode + "n"; } catch (Exception ex) { … } Delete Get Head Options Patch Post Put Also, new HttpMethod(string) for your own methods
  • 32. var uri = new Uri("http://example.com/customers/1"); try { var baseFilter = new HttpBaseProtocolFilter(); var cookieManager = baseFilter.CookieManager; var cookie = new HttpCookie("favoriteColor", ".example.com", "/") { Value = "purple"}; cookieManager.SetCookie(cookie); var client = new HttpClient(baseFilter); await client.PostAsync(uri, new HttpStringContent("Pete")); } catch (Exception ex) { ... }
  • 33. var baseFilter = new HttpBaseProtocolFilter(); var cookieManager = baseFilter.CookieManager; var client = new HttpClient(baseFilter); var cookies = cookieManager.GetCookies(uri); // display cookies foreach (var cookie in cookies) { CookieList.Text += cookie.Name + " = " + cookie.Value + "n"; }
  • 34. REST / Web Service HttpClient GetAsync GetBufferAsync GetInputStreamAsync GetStringAsync PostAsync PutAsync SendRequestAsync HttpRequestMessage HttpResponseMessage Http Base Protocol Filter Has in-depth settings HttpContent String • Stream • Buffer • Multipart • FormUrlEncoded ⛭ Your code This is also a filter
  • 35. For compression, credentials etc HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); // When AutomaticDecompression is true (the default), the Accept-Encoding header is added // to the headers and set to allow gzip and compress filter.AutomaticDecompression = true; PasswordCredential creds = new PasswordCredential("JumpStart", userName, password); filter.ServerCredential = creds; filter.ProxyCredential = creds; // Create the HttpClient HttpClient httpClient = new HttpClient(filter); // Make the call string responseText = await httpClient.GetStringAsync(uri); ...
  • 36.
  • 37. 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 (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
  • 38.
  • 39. Wire Serialization Format Size in Bytes ODATA XML 73786 ODATA JSON 34030 JSON ‘Lite’ 15540 JSON ‘Lite’ GZip 8680
  • 40. Making Decisions based on Data Connections Use the NetworkInterfaceType object to detect network type and speed Subscribe to the NetworkChange event to detect when network state changes Make your app aware of its networking environment and state!
  • 41. 41 private bool IsOnWiFi() { ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (internetConnectionProfile == null) return false; return InternetConnectionProfile.IsWlanConnectionProfile; } private bool IsConnectedtoDataRoaming() { bool isRoaming = false; ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (internetConnectionProfile != null && internetConnectionProfile.IsWwanConnectionProfile) { ConnectionCost cc = internetConnectionProfile.GetConnectionCost(); isRoaming = cc.Roaming; // See if user is currently roaming } return isRoaming; } private void AddEventHandlers() { // NetworkStatusChanged fires when the network status changes for a connection NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged; }
  • 42. 42
  • 43. 43
  • 44. 44
  • 45. 45 ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (internetConnectionProfile != null) { if (internetConnectionProfile.IsWlanConnectionProfile) { // connected on WiFi interface; double check it is not a metered WiFi hotspot ConnectionCost cc = internetConnectionProfile.GetConnectionCost(); if ((NetworkCostType.Unknown == cc.NetworkCostType) || (NetworkCostType.Unrestricted == cc.NetworkCostType)) { // assume free network; connect and start streaming content } } else if (internetConnectionProfile.IsWwanConnectionProfile) { ...
  • 46. 46 else if (InternetConnectionProfile.IsWwanConnectionProfile) { ConnectionCost cc = InternetConnectionProfile.GetConnectionCost(); // check the type of data plan - make sure user is not currently roaming if (!cc.Roaming) { if ((NetworkCostType.Unknown == cc.NetworkCostType) || (NetworkCostType.Unrestricted == cc.NetworkCostType)) { // assume free network; connect and start streaming content } else if (NetworkCostType.Fixed == cc.NetworkCostType) { // make sure user not currently over limit or near limit if ((!cc.OverDataLimit) && (!cc.ApproachingDataLimit)) { // connect and start streaming content } } } }
  • 47. 47 ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (internetConnectionProfile != null && internetConnectionProfile.IsWwanConnectionProfile) { ConnectionCost cc = internetConnectionProfile.GetConnectionCost(); if (!cc.Roaming) // check the type of data plan, make sure user is not currently roaming { if (NetworkCostType.Fixed == cc.NetworkCostType) { if (cc.ApproachingDataLimit) // making smart decisions if close to data limit { DataPlanStatus dps = internetConnectionProfile.GetDataPlanStatus(); // get current data plan status and usage DataPlanUsage dpu = dps.DataPlanUsage; UInt32 DataUsed = dpu.MegabytesUsed; UInt32? DataLimit = dps.DataLimitInMegabytes; DateTimeOffset? BillingDate = dps.NextBillingCycle; // calculate how much data plan is still available for use. // If larger than size of data to be transferred, connect, else wait for WiFi connection to be available ... } } } }
  • 48. 48 // only want to connect using the WiFi interface; register for network status change notifications static bool registeredNetworkStatusNotif = false; NetworkStatusChangedEventHandler networkStatusCallback = null; private void Setup() { networkStatusCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange); if (!registeredNetworkStatusNotif) { NetworkInformation.NetworkStatusChanged += networkStatusCallback; registeredNetworkStatusNotif = true; } } ...
  • 49. 49 // Event handler for Network Status Change event async void OnNetworkStatusChange(object sender) { // get the ConnectionProfile that is currently used to connect to the Internet ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); // Figure out which network state event is it if (InternetConnectionProfile != null) // Null if not connected to internet... { // check whether the new connection profile is over WiFi if (InternetConnectionProfile.IsWlanConnectionProfile) { // connected on WiFi interface; double check it is not a metered WiFi hotspot ConnectionCost cc = InternetConnectionProfile.GetConnectionCost(); if ((NetworkCostType.Unknown == cc.NetworkCostType) || (NetworkCostType.Unrestricted == cc.NetworkCostType)) { // start thread to connect and get content ... } } } }
  • 51. The Paradox: Users dislike signing on…
  • 52.
  • 53.
  • 55. MSA
  • 56. void SaveCredential(string username, string password) { PasswordVault vault = new PasswordVault(); PasswordCredential cred = new PasswordCredential("MyAppResource", username, password); vault.Add(cred); } IReadOnlyList<PasswordCredential> RetrieveCredential(string resource) { PasswordVault vault = new PasswordVault(); return vault.FindAllByResource(resource); }
  • 57.
  • 58.
  • 59. Online service 1. Authorization Request (Start URL) 6. Authorization token (Redirect URL) 7. Data access User
  • 60.
  • 61.
  • 62. Web auth broker Online service 1. Authorization request (Start URL) 6. Authorization token (Redirect URL) WinRT Dialog User Windows Phone 8.1 app 7. Data access
  • 63. // Authenticate using WAB async void Authenticate() { WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, startUri, endUri); if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { // Parse the returned data to get the token out // token is used in requests to online service GetToken(WebAuthenticationResult.ResponseData); } else { // handle failures (user cancel, HTTP error) } } //Initiate authentication using WAB void Authenticate() { WebAuthenticationBroker.AuthenticateAndContinue( startUri, endUri); } { // Code runs on reactivation to handle response from WAB }
  • 64. protected override async void OnActivated(IActivatedEventArgs args) { if (args is WebAuthenticationBrokerContinuationEventArgs) { Frame rootFrame = Window.Current.Content as Frame; // Do standard logic to create the Frame if necessary and restore state if (rootFrame == null) { rootFrame = new Frame(); SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { } } // Place the frame in the current Window. Window.Current.Content = rootFrame; } ...
  • 65. ... if (rootFrame.Content == null) { if (!rootFrame.Navigate(typeof(MyPageThatDoesAuth))) { throw new Exception("Failed to create target page"); } } // Pass the continuation event args to the target page var p = rootFrame.Content as MyPageThatDoesAuth; // ContinuationArgs is a property that we’ve added to MyPageThatDoesAuth p.ContinuationArgs = (WebAuthenticationBrokerContinuationEventArgs)args; // Ensure the current window is active Window.Current.Activate(); } }
  • 66. private WebAuthenticationBrokerContinuationEventArgs _continuationArgs = null; public WebAuthenticationBrokerContinuationEventArgs ContinuationArgs { get { return _continuationArgs; } set { _continuationArgs = value; ContinueWebAuthentication(_continuationArgs); } } public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args) { WebAuthenticationResult result = args.WebAuthenticationResult; if (result.ResponseStatus == WebAuthenticationStatus.Success) { String outputToken = result.ResponseData.ToString(); await DoSomethingWithTheTokenAsync(outputToken); } else { /* handle failures (user cancel, HTTP error) */ } }
  • 67. Contoso 1 2 3 Credentials pre-populated if any app previously authenticated to this provider
  • 68.
  • 69. 69
  • 70. Kernel Mode User Mode (App Container) User Mode (Medium) https://contoso.com SID: S-1-5-4321 Contoso verifies the redirect URL for its apps (e.g. MyPhotoApp registered ms-app://S-1-5-4321) https://contoso.com?ContosoAppID=MyPhotoApp, redirectURI=ms-app://S-1-5-4321,…
  • 71. void AuthenticateSSO() { // Not specifying an endUri tells WAB to use SSO mode WebAuthenticationBroker.AuthenticateAndContinue(startUri); } public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args) { WebAuthenticationResult result = args.WebAuthenticationResult; if (result.ResponseStatus == WebAuthenticationStatus.Success) { GetToken(result.ResponseData); } ... }
  • 72.
  • 73.
  • 74. ©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and 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. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.