SlideShare a Scribd company logo
1 of 29
Download to read offline
ITALIAN WEBINAR #4

INTERAGIRE CON LA RETE
Matteo Pagani
Nokia Developer Champion
Microsoft MVP – Windows Phone Development
Software Engineer @ Funambol
AGENDA
•
•
•
•

Determinare la connessione
Upload e download di file
Background transfer
Interagire con i servizi

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
CONNETTIVITA’
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
CONNETTIVITA’
•
•

•
•

E’ importante verificare la presenza di connettività prima di interagire con la
rete
La classe DeviceNetworkInformation nel namespace
Microsoft.Phone.Net.NetworkInformation permette di accedere alle
informazioni sulla connettività
Connessioni dati attive, connettività a Internet, informazioni sull’operatore
Possibilità di sottoscriversi all’evento NetworkAvailabilityChanged, che
viene scatenato ogni qualvolta cambia lo stato della connessione
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.

10/15/2013
CONNETTIVITA’
Demo

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
INTERAGIRE
CON LA RETE
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
INTERAGIRE CON LA RETE
•

•
•

L’SDK di Windows Phone include due classi native per interagire con la rete:
•
WebClient
•
HttpWebRequest
Nessuna delle due supporta, in modo nativo, l’approccio async e await
Hanno entrambe diversi limiti che ne rendono complicato l’utilizzo

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
WEBCLIENT
private async void OnDownloadStringClicked(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("url"));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
UI Thread
MessageBox.Show(e.Result);
}
}
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
HTTPWEBREQUEST
private void OnDownloadStringClicked(object sender, RoutedEventArgs e)
{
webRequest = HttpWebRequest.CreateHttp("url");
webRequest.Method = "GET";
webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), webRequest);
}
private void ResponseCallback(IAsyncResult asyncResult)
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
Stream stream = webResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
MessageBox.Show(result);
}
}
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
WELCOME HTTPCLIENT
•

•
•
•

Il Windows Runtime ha introdotto una nuova classe: HttpClient
Per Windows Phone è disponibile come pacchetto su NuGet:
http://www.nuget.org/packages/Microsoft.Net.Http/
E’ utilizzabile anche nelle Portable Class Libraries
Espone un metodo asincrono per ogni comando del protocolo HTTP:
•
PostAsync()
•
PutAsync()
•
GetAsync()
•
DeleteAsync()
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
DOWNLOAD
HttpClient client = new HttpClient();
Stream stream = await client.GetStreamAsync(“url");
HttpClient client = new HttpClient();
string result = await client.GetStringAsync(“url");

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
UPLOAD
private async void OnSendPostClicked(object sender, RoutedEventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.0.12:4484");
Stream stream = await
ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("image.png");
StreamContent content = new StreamContent(stream);
var result = await client.PostAsync("/api/values", content);

}
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
HTTPCLIENT
Demo

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
BACKGROUND
TRANSFER

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
BACKGROUND TRANSFER
•
•
•
•

Le classi viste in precedenza funzionano solo se l’applicazione è in uso
Se l’applicazione viene sospesa, il trasferimento viene terminato
API introdotte in Windows Phone 7.5 per effettuare operazioni di download
e upload in grado di proseguire in background
Al centro l’utente: vincoli da rispettare per evitare l’eccessivo consumo di
batteria e il degrado delle performance

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
BACKGROUND TRANSFER
•

•

•

Il sistema operativo mette a disposizione una coda
(BackgroundTransferService), nella quale aggiungere le operazioni di
trasferimento in background (BackgroundTransferRequest)
E’ possibile specificare le condizioni da rispettare per avviare il
trasferimento (solo rete WI-Fi, solo se in ricarica, in qualsiasi caso)
(TransferPreferences)
L’applicazione aggiunge le operazioni alla coda e, quando le condizioni
vengono rispettate, vengono eseguite

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
VINCOLI
•

•
•

•

Dimensione massima download file:
•
20 MB se collegato alla rete cellulare
•
100 MB se collegato alla rete Wi-Fi
•
Illimitato se collegato alla rete Wi-Fi e in ricarica
Un’applicazione può mettere in coda massimo 25 operazioni
Il sistema operativo può gestire una coda di massimo 500 operazioni
Il sistema operativo può eseguire massimo due operazioni
contemporaneamente
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
ALCUNI CONSIGLI
•
•
•

I download in background devono necessariamente salvare i file nella
cartella /Shared/Transfers nello storage
Ad ogni caricamento dell’app, bisogna verificare lo stato delle operazioni:
potrebbero essere terminate in background
Ogni volta che un’operazione è terminata, occorre rimuoverla manualmente
dalla coda

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
WINDOWS PHONE TOOLKIT
•

•
•

Include un controllo, TransferControl, e una classe, TransferMonitor, che
permettono di gestire la rappresentazione visuale dello stato del
trasferimento
TransferControl è un controllo XAML, che mostra una progress bar con una
descrizione testuale
TransferMonitor è una classe che funge da «wrapper» verso il gestore della
coda (BackgroundTransferService)

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
BACKGROUND
TRANSFER
Demo

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
SERVIZI
© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
SERVIZI WCF, SOAP O ODATA
•
•
•

Per i servizi WCF, SOAP e oData Visual Studio è in grado di generare una
classe proxy, che permette di interagire mantenedo l’approccio a oggetti
Per oData, è necessarie installare un plugin per VS:
http://s.qmatteoq.com/oDataWP8
Vengono aggiunti al progetto tramite il menu Add service reference di
Visual Studio

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
SERVIZI REST
•
•

•

Le interazioni con il servizio sono gestite con i comandi standard del
protocollo HTTP (POST, GET, PUT, DELETE)
Le risposte vengono formattate utilizzando gli standard XML o JSON
Sono i più diffusi al giorno d’oggi:
•
Compatibilità con tutte le piattaforme
•
Semplicità di uso
•
Utilizzo di formati standard

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
SERIALIZZAZIONE
•
•
•
•

L’unico inconveniente nel lavorare con i servizi REST è che restituiscono
strutture dati «piatte», al contrario della logica ad oggetti dell’applicazione
Serializzare = trasformare in oggetti una struttura di dati espressa in XML o
JSON
Deserializzare = trasformare una struttura dati XML o JSON in oggetti
Esistono librerie in grado di effettuare questa procedura in automatico

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
HTTPCLIENT
•

HttpClient:
•
semplice da utilizzare
•
supporta async e await
•
compatibile con tutte le tecnologie Microsoft
•
supporta tutti i comandi standard del protocollo HTTP
•
serializzazione e deserializzazione vanno gestite manualmente

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
JSON.NET
•
•

•
•

Libreria open source disponibile su NuGet:
http://www.nuget.org/packages/Newtonsoft.Json/
Supporta funzionalità di serializzazione e deserializzazione
Supporta LINQ to JSON, un linguaggio di manipolazione di dati in JSON
analogo a LINQ to XML
Offre performance e funzionalità superiori rispetto alla serializzazione
nativa inclusa nel framework (DataContractJsonSerializer)

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
RESTSHARP
•

RestSharp:
•
più completa
•
serializza e deserializza in automatico i dati
•
utilizza l’approccio asincrono basato su callback
•
poco flessibile in alcuni scenari
•
non disponibile per tutte le tecnologie Microsoft (esempio: no Windows
Store Apps).

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
SERVIZI
Demo

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.
Grazie!
Blog:
http://www.qmatteoq.com
http://wp.qmatteoq.com
Twitter: @qmatteoq
Mail: info@qmatteoq.com
Materiale su http://sdrv.ms/164szm0

© 2012 Nokia. All rights reserved.
© 2012 Microsoft. All rights reserved.

10/15/2013

More Related Content

More from Microsoft Mobile Developer

More from Microsoft Mobile Developer (20)

Intro to Nokia X software platform 2.0 and tools
Intro to Nokia X software platform 2.0 and toolsIntro to Nokia X software platform 2.0 and tools
Intro to Nokia X software platform 2.0 and tools
 
Lumia App Labs: Lumia SensorCore SDK beta
Lumia App Labs: Lumia SensorCore SDK betaLumia App Labs: Lumia SensorCore SDK beta
Lumia App Labs: Lumia SensorCore SDK beta
 
Nokia Asha from idea to app - Imaging
Nokia Asha from idea to app - ImagingNokia Asha from idea to app - Imaging
Nokia Asha from idea to app - Imaging
 
Healthcare apps for Nokia X and Nokia Asha
Healthcare apps for Nokia X and Nokia AshaHealthcare apps for Nokia X and Nokia Asha
Healthcare apps for Nokia X and Nokia Asha
 
Push notifications on Nokia X
Push notifications on Nokia XPush notifications on Nokia X
Push notifications on Nokia X
 
DIY Nokia Asha app usability studies
DIY Nokia Asha app usability studiesDIY Nokia Asha app usability studies
DIY Nokia Asha app usability studies
 
Lessons learned from Nokia X UI reviews
Lessons learned from Nokia X UI reviewsLessons learned from Nokia X UI reviews
Lessons learned from Nokia X UI reviews
 
Location based services for Nokia X and Nokia Asha using Geo2tag
Location based services for Nokia X and Nokia Asha using Geo2tagLocation based services for Nokia X and Nokia Asha using Geo2tag
Location based services for Nokia X and Nokia Asha using Geo2tag
 
HERE Maps for the Nokia X platform
HERE Maps for the Nokia X platformHERE Maps for the Nokia X platform
HERE Maps for the Nokia X platform
 
Nokia In-App Payment - UX considerations
Nokia In-App Payment - UX considerationsNokia In-App Payment - UX considerations
Nokia In-App Payment - UX considerations
 
Introduction to Nokia Asha SDK 1.2 (beta)
Introduction to Nokia Asha SDK 1.2 (beta)Introduction to Nokia Asha SDK 1.2 (beta)
Introduction to Nokia Asha SDK 1.2 (beta)
 
UX considerations when porting to Nokia X
UX considerations when porting to Nokia XUX considerations when porting to Nokia X
UX considerations when porting to Nokia X
 
Kids' games and educational app design
Kids' games and educational app designKids' games and educational app design
Kids' games and educational app design
 
Nokia X: opportunities for developers
Nokia X: opportunities for developersNokia X: opportunities for developers
Nokia X: opportunities for developers
 
Lumia App Labs: Nokia Imaging SDK 1.1
Lumia App Labs: Nokia Imaging SDK 1.1Lumia App Labs: Nokia Imaging SDK 1.1
Lumia App Labs: Nokia Imaging SDK 1.1
 
Intro to Nokia X software platform and tools
Intro to Nokia X software platform and toolsIntro to Nokia X software platform and tools
Intro to Nokia X software platform and tools
 
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultations
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultationsLumia App Labs: Lessons learned from 50 windows phone 8 design consultations
Lumia App Labs: Lessons learned from 50 windows phone 8 design consultations
 
Windows Phone 8 speech: parliamo con la nostra app
Windows Phone 8 speech: parliamo con la nostra appWindows Phone 8 speech: parliamo con la nostra app
Windows Phone 8 speech: parliamo con la nostra app
 
La pubblicazione di un'applicazione sullo store
La pubblicazione di un'applicazione sullo storeLa pubblicazione di un'applicazione sullo store
La pubblicazione di un'applicazione sullo store
 
Il pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progettoIl pattern mvvm come strutturare al meglio il vostro progetto
Il pattern mvvm come strutturare al meglio il vostro progetto
 

Interagire con la Rete

  • 1. ITALIAN WEBINAR #4 INTERAGIRE CON LA RETE Matteo Pagani Nokia Developer Champion Microsoft MVP – Windows Phone Development Software Engineer @ Funambol
  • 2. AGENDA • • • • Determinare la connessione Upload e download di file Background transfer Interagire con i servizi © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 3. CONNETTIVITA’ © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 4. CONNETTIVITA’ • • • • E’ importante verificare la presenza di connettività prima di interagire con la rete La classe DeviceNetworkInformation nel namespace Microsoft.Phone.Net.NetworkInformation permette di accedere alle informazioni sulla connettività Connessioni dati attive, connettività a Internet, informazioni sull’operatore Possibilità di sottoscriversi all’evento NetworkAvailabilityChanged, che viene scatenato ogni qualvolta cambia lo stato della connessione © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved. 10/15/2013
  • 5. CONNETTIVITA’ Demo © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 6. INTERAGIRE CON LA RETE © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 7. INTERAGIRE CON LA RETE • • • L’SDK di Windows Phone include due classi native per interagire con la rete: • WebClient • HttpWebRequest Nessuna delle due supporta, in modo nativo, l’approccio async e await Hanno entrambe diversi limiti che ne rendono complicato l’utilizzo © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 8. WEBCLIENT private async void OnDownloadStringClicked(object sender, RoutedEventArgs e) { WebClient client = new WebClient(); client.DownloadStringCompleted += client_DownloadStringCompleted; client.DownloadStringAsync(new Uri("url")); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { UI Thread MessageBox.Show(e.Result); } } © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 9. HTTPWEBREQUEST private void OnDownloadStringClicked(object sender, RoutedEventArgs e) { webRequest = HttpWebRequest.CreateHttp("url"); webRequest.Method = "GET"; webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), webRequest); } private void ResponseCallback(IAsyncResult asyncResult) { HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult); Stream stream = webResponse.GetResponseStream(); using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); MessageBox.Show(result); } } © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 10. WELCOME HTTPCLIENT • • • • Il Windows Runtime ha introdotto una nuova classe: HttpClient Per Windows Phone è disponibile come pacchetto su NuGet: http://www.nuget.org/packages/Microsoft.Net.Http/ E’ utilizzabile anche nelle Portable Class Libraries Espone un metodo asincrono per ogni comando del protocolo HTTP: • PostAsync() • PutAsync() • GetAsync() • DeleteAsync() © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 11. DOWNLOAD HttpClient client = new HttpClient(); Stream stream = await client.GetStreamAsync(“url"); HttpClient client = new HttpClient(); string result = await client.GetStringAsync(“url"); © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 12. UPLOAD private async void OnSendPostClicked(object sender, RoutedEventArgs e) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://192.168.0.12:4484"); Stream stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync("image.png"); StreamContent content = new StreamContent(stream); var result = await client.PostAsync("/api/values", content); } © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 13. HTTPCLIENT Demo © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 14. BACKGROUND TRANSFER © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 15. BACKGROUND TRANSFER • • • • Le classi viste in precedenza funzionano solo se l’applicazione è in uso Se l’applicazione viene sospesa, il trasferimento viene terminato API introdotte in Windows Phone 7.5 per effettuare operazioni di download e upload in grado di proseguire in background Al centro l’utente: vincoli da rispettare per evitare l’eccessivo consumo di batteria e il degrado delle performance © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 16. BACKGROUND TRANSFER • • • Il sistema operativo mette a disposizione una coda (BackgroundTransferService), nella quale aggiungere le operazioni di trasferimento in background (BackgroundTransferRequest) E’ possibile specificare le condizioni da rispettare per avviare il trasferimento (solo rete WI-Fi, solo se in ricarica, in qualsiasi caso) (TransferPreferences) L’applicazione aggiunge le operazioni alla coda e, quando le condizioni vengono rispettate, vengono eseguite © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 17. VINCOLI • • • • Dimensione massima download file: • 20 MB se collegato alla rete cellulare • 100 MB se collegato alla rete Wi-Fi • Illimitato se collegato alla rete Wi-Fi e in ricarica Un’applicazione può mettere in coda massimo 25 operazioni Il sistema operativo può gestire una coda di massimo 500 operazioni Il sistema operativo può eseguire massimo due operazioni contemporaneamente © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 18. ALCUNI CONSIGLI • • • I download in background devono necessariamente salvare i file nella cartella /Shared/Transfers nello storage Ad ogni caricamento dell’app, bisogna verificare lo stato delle operazioni: potrebbero essere terminate in background Ogni volta che un’operazione è terminata, occorre rimuoverla manualmente dalla coda © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 19. WINDOWS PHONE TOOLKIT • • • Include un controllo, TransferControl, e una classe, TransferMonitor, che permettono di gestire la rappresentazione visuale dello stato del trasferimento TransferControl è un controllo XAML, che mostra una progress bar con una descrizione testuale TransferMonitor è una classe che funge da «wrapper» verso il gestore della coda (BackgroundTransferService) © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 20. BACKGROUND TRANSFER Demo © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 21. SERVIZI © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 22. SERVIZI WCF, SOAP O ODATA • • • Per i servizi WCF, SOAP e oData Visual Studio è in grado di generare una classe proxy, che permette di interagire mantenedo l’approccio a oggetti Per oData, è necessarie installare un plugin per VS: http://s.qmatteoq.com/oDataWP8 Vengono aggiunti al progetto tramite il menu Add service reference di Visual Studio © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 23. SERVIZI REST • • • Le interazioni con il servizio sono gestite con i comandi standard del protocollo HTTP (POST, GET, PUT, DELETE) Le risposte vengono formattate utilizzando gli standard XML o JSON Sono i più diffusi al giorno d’oggi: • Compatibilità con tutte le piattaforme • Semplicità di uso • Utilizzo di formati standard © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 24. SERIALIZZAZIONE • • • • L’unico inconveniente nel lavorare con i servizi REST è che restituiscono strutture dati «piatte», al contrario della logica ad oggetti dell’applicazione Serializzare = trasformare in oggetti una struttura di dati espressa in XML o JSON Deserializzare = trasformare una struttura dati XML o JSON in oggetti Esistono librerie in grado di effettuare questa procedura in automatico © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 25. HTTPCLIENT • HttpClient: • semplice da utilizzare • supporta async e await • compatibile con tutte le tecnologie Microsoft • supporta tutti i comandi standard del protocollo HTTP • serializzazione e deserializzazione vanno gestite manualmente © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 26. JSON.NET • • • • Libreria open source disponibile su NuGet: http://www.nuget.org/packages/Newtonsoft.Json/ Supporta funzionalità di serializzazione e deserializzazione Supporta LINQ to JSON, un linguaggio di manipolazione di dati in JSON analogo a LINQ to XML Offre performance e funzionalità superiori rispetto alla serializzazione nativa inclusa nel framework (DataContractJsonSerializer) © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 27. RESTSHARP • RestSharp: • più completa • serializza e deserializza in automatico i dati • utilizza l’approccio asincrono basato su callback • poco flessibile in alcuni scenari • non disponibile per tutte le tecnologie Microsoft (esempio: no Windows Store Apps). © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 28. SERVIZI Demo © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved.
  • 29. Grazie! Blog: http://www.qmatteoq.com http://wp.qmatteoq.com Twitter: @qmatteoq Mail: info@qmatteoq.com Materiale su http://sdrv.ms/164szm0 © 2012 Nokia. All rights reserved. © 2012 Microsoft. All rights reserved. 10/15/2013