SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
Network Communication
Open Data Protocol (ODATA)
Nguyen Tuan | Microsoft Certified Trainer
Agenda
• Networking for Windows Phone
• WebClient
• HttpWebRequest
• Sockets
• Web Services and OData
• Simulation Dashboard
• Data Compression
Networking on Windows Phone
Networking on Windows Phone
• Support for networking features
• Windows Communication Foundation (WCF)
• HttpWebRequest
• WebClient
• Sockets
• Full HTTP header access on requests
• NTLM authentication
4
New Features in WP8
• Two different Networking APIs
• System.Net – Windows Phone 7.1 API, upgraded with new features
• Windows.Networking.Sockets – WinRT API adapted for Windows Phone
• Support for IPV6
• Support for the 128-bit addressing system added to System.Net.Sockets and also is
supported in Windows.Networking.Sockets
• NTLM and Kerberos authentication support
• Incoming Sockets
• Listener sockets supported in both System.Net and in Windows.Networking
• Winsock support
• Winsock supported for native development
8/16/2014 5
Networking APIs Platform Availability
API WP7.1 WP8 W8
System.Net.WebClient   
System.Net.HttpWebRequest   
System.Net.Http.HttpClient   
Windows.Web.Syndication.SyndicationClient   
Windows.Web.AtomPub.AtomPubClient   
ASMX Web Services   
WCF Services   
OData Services   
8/16/2014 6
Async support in WP8 Networking APIs
• C# 5.0 includes the async and await keywords to ease writing of asynchronous
code
• In desktop .NET 4.5, and in Windows 8 .NET for Windows Store Apps, new
Task-based methods allow networking calls as an asynchronous operation
using a Task object
• HttpClient API
• WebClient.DownloadStringTaskAsync(), DownloadFileTaskAsync(),
UploadStringTaskAsync() etc
• HttpWebRequest.GetResponseAsync()
• These methods are not supported on Windows Phone 8
• Task-based networking using WebClient and HttpWebRequest still possible using
TaskFactory.FromAsync()and extension methods
• Coming up later…
8/16/2014 7
Connecting the Emulator to
Local Services
8/16/2014
8
• In Windows Phone 7.x, the emulator shared the networking of the Host
PC
•You could host services on your PC and access them from your code using
http://localhost...
• In Windows Phone 8, the emulator is a Virtual machine running under
Hyper-V
•You cannot access services on your PC using http://localhost...
•You must use the correct host name or raw IP address of your host PC in URIs
WP8 Emulator and localhost
8/16/2014
• If you host your web sites or services in IIS, you must open your firewall
for incoming HTTP requests
Configuring Web Sites Running in Local IIS 8
Firewall
8/16/2014
• If your service is a WCF service, you must also ensure that HTTP
Activation is checked in Turn Windows features on or off
Configuring Web Sites Running in Local IIS 8
WCF Service Activation
8/16/2014
• Create your website or web service in
Visual Studio 2012
• Run it and it is configured to run in
localhost:port
Configuring Sites Running in IIS Express
STEP 1: Create Your Website or Web service
8/16/2014
• Remove your website (don’t delete!) from the Visual Studio 2012 solution
• Edit the file C:UsersyourUsernameDocumentsIISExpressconfigapplicationhost.config
• Find the <sites> section
• Find the entry for the website or service you just created
• Change
<binding protocol="http" bindingInformation="*:nnnn:localhost" />
to
<binding protocol="http" bindingInformation="*:nnnn:YourPCName" />
• Save changes
• Use ‘Add Existing Website’ to add the website folder back into your solution
Configuring Sites Running in IIS Express
STEP 2: Modify Config to Run on a URI Using Your PC Name
8/16/2014
• From a Command Prompt (Run as Administrator), open the port in the Firewall:
netsh advfirewall firewall add rule name="IIS Express (non-SSL)" action=allow
protocol=TCP dir=in localport=nnnn
• Also run the following at the command prompt:
netsh http add urlacl url=http://yourPC:nnnn/ user=everyone
• Substitute yourPC with the host name of your Host PC
• Substitute 8080 for the port where your service is running
• Run it and access from your desktop browser – Now it is hosted at YourPCName:port
Useful References:
• How to: Specify a Port for the Development Server
http://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspx
Configuring Sites Running in IIS Express
STEP 3: Open Port in the Firewalland RegisterURL
8/16/2014
WebClient
8/16/2014
1
5
Simple Http Operations – WebClient
using System.Net;
...
WebClient client;
// Constructor
public MainPage()
{
...
client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.downloadedText = e.Result;
}
private void loadButton_Click(object sender, RoutedEventArgs e)
{
client.DownloadStringAsync(new Uri("http://MyServer/ServicesApplication/rssdump.xml"));
}
• No Task-based async methods have been added to WebClient
• Async operation possible using custom extension methods, allowing usage
such as:
WebClient using async/await
17
using System.Net;
using System.Threading.Tasks;
...
private async void loadButton_Click(object sender, RoutedEventArgs e)
{
var client = new WebClient();
string response = await client.DownloadStringTaskAsync(new Uri("http://MyServer/ServicesApplication/rssdump.xml"));
this.downloadedText = response;
}
More Control – HttpWebRequest
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Suppliers")
as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
// Must pass the HttpWebRequest object in the state attached to this call
// Begin the request…
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
• HttpWebRequestis a lower level API that allows access to the requestand response streams
• The state object passed in the BeginGetResponsecall must be the initiating HttpWebRequest
object, or a custom state object containing the HttpWebRequest
HttpWebRequest – Response Handling
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
string data;
// State of request is asynchronous
HttpWebRequest myHttpWebRequest = (HttpWebRequest)asynchronousResult.AsyncState; ;
using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult))
{
// Read the response into a Stream object.
System.IO.Stream responseStream = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
// Callback occurs on a background thread, so use Dispatcher to marshal back to the UI thread
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Received payload of " + data.Length + " characters");
} );
}
catch (Exception e) ...
}
HttpWebRequest – Error Handling
private void GotResponse(IAsyncResult asynchronousResult)
{
try
{
// Handle the Response
...
}
catch (Exception e)
{
var we = e.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("RespCallback Exception raised! Message:" + we.Message +
"HTTP Status: " + we.Status);
});
}
else
throw;
}
}
HttpWebRequest – Using TPL Pattern
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var request = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/Suppliers")
as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
// Use the Task Parallel Library pattern
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
try
{
var response = await task;
// Read the response into a Stream object.
System.IO.Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
MessageBox.Show("Received payload of " + data.Length + " characters");
}
catch (Exception ex) ...
HttpWebRequest (TPL) – Error Handling
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
// Make the call and handle the Response
...
}
catch (Exception e)
{
var we = e.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
var code = resp.StatusCode;
MessageBox.Show("RespCallback Exception raised! Message:" + we.Message +
"HTTP Status: " + we.Status);
}
else
throw e;
}
}
Demo
PushNotifications
Web Services
WCF/ASMX Services
• Can ‘Add Reference’ from
Windows Phone projects to
automatically generate proxy
classes
• ASMX should ‘just work’
• WCF requires that you use
basicHttpBinding
25
RESTful Web Services
Building them
• Rather than building “walled gardens,” data should be published in a way
that allows it to reach the broadest range of mobile clients
• Old-style ASMX SOAP 1.1 Web Services using ASP.NET or Windows
Communication Foundation (WCF) require clients to implement SOAP
protocol
• With Windows Phone 7 and Silverlight, we use WCF with BasicHttpBinding
both on-premise and as a Web Role in Windows Azure to publish our data
from local and cloud-based data sources like SQL Azure
• Recommend using lightweight REST + JSON Web Services that are better
optimized for high-latency, slow, intermittent wireless data connections
26
WCF Data Services: OData
• WCF Data Services provide an
extensible tool for publishingdata
using a REST-based interface
• Publishes and consumes data using the OData web
protocol (http://www.odata.org)
• Formatted in XML or JSON
• WCF Data Services Client Library
(DataServicesClient) is a separate
download from
NuGet
• Adds ‘Add Service Reference’ for OData V3 Services
Generate Client Proxy
• In most cases, Add Service Reference will just work
• Alternatively, open a command prompt as administrator and navigate
to
C:Program Files (x86)Microsoft WCF Data
Services5.0toolsPhone
• Run this command
DataSvcutil_WindowsPhone.exe
/uri:http://odata.netflix.com/v2/Catalog/
/DataServiceCollection /Version:1.0/out:netflixClientTypes
• Add generated file to your project
Fetching Data
29
public partial class NorthwindModel
{
NorthwindEntities context;
private DataServiceCollection<Customer> customers;
private override void LoadData()
{
context = new NorthwindEntities(new Uri("http://services.odata.org/V3/Northwind/Northwind.svc/"));
// Initialize the context and the binding collection
customers = new DataServiceCollection<Customer>(context);
// Define a LINQ query that returns all customers.
var query = from cust in context.Customers
select cust;
// Register for the LoadCompleted event.
customers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(customers_LoadCompleted);
// Load the customers feed by executing the LINQ query.
customers.LoadAsync(query);
}
...
Fetching Data - LoadCompleted
30
...
void customers_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error == null)
{
// Handling for a paged data feed.
if (customers.Continuation != null)
{
// Automatically load the next page.
customers.LoadNextPartialSetAsync();
}
else
{
foreach (Customer c in customers)
{
//Add each customer to our View Model collection
App.ViewModel.Customers.Add(new CustomerViewModel(){SelectedCustomer = c});
}
}
}
else
{
MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message));
}
}
Digging into OData
Open Data Protocol (OData)
• “RESTful” Web protocol
• Designed to work with data across HTTP
• Built on existing Web standards
• Uses popular formats to return data payloads to consumer
• Uses self-describing metadata
• Has multiple options to build implementation based on standard
protocol
• Soon to be a full web standard
The Basics of OData
Feeds, which are Collections of typed Entities
OData services can expose Actions and Functions
(v4), Services (v3)
OData services expose all these constructs via
URIs
OData service may also expose a Service Metadata
Document
Full SQL like Query “Language”
HTTP Command (Verb) SQL Command
GET SELECT
PUT UPDATE
POST INSERT
DELETE DELETE
The $metadata endpoint
http://services.odata.org/OData/OData.svc
_______________________________________/
|
service root URI
http://services.odata.org/OData/OData.svc/Category(1)/Products?$top=2&$orderby=name
_______________________________________/ __________________/ _________________/
| | |
service root URI resource path query options
What is a URI?
OData Best Practices (Producer)
• Always design your OData feed will server-side paging if your entity
collections hold large amounts of data.
• Looks at server-side validation of queries and data updates based on
the user credentials sent through HTTP
Who uses OData?
What does OData give me and my
organization?
Empower Internal
Power Users
Empower Existing and
Future Customers
Monetize Data for
untapped Revenue
DEMO
WindowsPhoneOData
OData Best Practices (Consumer)
• Use Query Projection to only bring back the entity properties you or
your app needs.
• Think about client-side paging even if their exists server-side paging.
• Design and implement a client-side data caching function in your app
(unless sensitive data).
Resources
REST
http://www.ics.uci.edu/~taylor/documents/2002-REST-TOIT.pdf
OData
http://odata.org
http://odataprimer.com
Azure Mobile Services
http://www.windowsazure.com/en-us/develop/mobile/
Summaries
• WebClient and HttpWebRequest for HTTP communications
• Windows Phone has a sockets API to support connection-oriented
and connectionless TCP/IP and UDP/IP networking
• Support for ASMX, WCF and REST Web Services
• DataServicesClient for OData service access out of the box in 7.1 SDK
• Consider JSON serialization for maximum data transfer efficiency
• Windows Phone 8 supports Basic, NTLM, digest and Kerberos
authentication
• Encrypt sensitive data on the phone using the ProtectedData class

Más contenido relacionado

La actualidad más candente

Debugging the Web with Fiddler
Debugging the Web with FiddlerDebugging the Web with Fiddler
Debugging the Web with FiddlerIdo Flatow
 
Adminlicious - A Guide To TCO Features In Domino v10
Adminlicious - A Guide To TCO Features In Domino v10Adminlicious - A Guide To TCO Features In Domino v10
Adminlicious - A Guide To TCO Features In Domino v10Gabriella Davis
 
Integration Of Mulesoft and Apache Active MQ
Integration Of Mulesoft and Apache Active MQIntegration Of Mulesoft and Apache Active MQ
Integration Of Mulesoft and Apache Active MQGaurav Talwadker
 
June OpenNTF Webinar - Domino V12 Certification Manager
June OpenNTF Webinar - Domino V12 Certification ManagerJune OpenNTF Webinar - Domino V12 Certification Manager
June OpenNTF Webinar - Domino V12 Certification ManagerHoward Greenberg
 
Smuggling TCP traffic through HTTP
Smuggling TCP traffic through HTTPSmuggling TCP traffic through HTTP
Smuggling TCP traffic through HTTPDávid Halász
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadWASdev Community
 
Web Server-Side Programming Techniques
Web Server-Side Programming TechniquesWeb Server-Side Programming Techniques
Web Server-Side Programming Techniquesguest8899ec02
 
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...Alexander Lisachenko
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction HandlingGaurav Arora
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF WorkshopIdo Flatow
 
HTTP - The Other Face Of Domino
HTTP - The Other Face Of DominoHTTP - The Other Face Of Domino
HTTP - The Other Face Of DominoGabriella Davis
 
Server-Side Programming Primer
Server-Side Programming PrimerServer-Side Programming Primer
Server-Side Programming PrimerIvano Malavolta
 
Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...
Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...
Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...VMware Tanzu
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaYevgeniy Brikman
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...ColdFusionConference
 
CollabSphere 2018: How to build your SmartCloud Notes hybrid environment
CollabSphere 2018: How to build your SmartCloud Notes hybrid environmentCollabSphere 2018: How to build your SmartCloud Notes hybrid environment
CollabSphere 2018: How to build your SmartCloud Notes hybrid environmentDavid Hablewitz
 
Introduction to vSphere APIs Using pyVmomi
Introduction to vSphere APIs Using pyVmomiIntroduction to vSphere APIs Using pyVmomi
Introduction to vSphere APIs Using pyVmomiMichael Rice
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket basedMukesh Tekwani
 
× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...
× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...
× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...Gabriella Davis
 

La actualidad más candente (20)

Debugging the Web with Fiddler
Debugging the Web with FiddlerDebugging the Web with Fiddler
Debugging the Web with Fiddler
 
Nginx
NginxNginx
Nginx
 
Adminlicious - A Guide To TCO Features In Domino v10
Adminlicious - A Guide To TCO Features In Domino v10Adminlicious - A Guide To TCO Features In Domino v10
Adminlicious - A Guide To TCO Features In Domino v10
 
Integration Of Mulesoft and Apache Active MQ
Integration Of Mulesoft and Apache Active MQIntegration Of Mulesoft and Apache Active MQ
Integration Of Mulesoft and Apache Active MQ
 
June OpenNTF Webinar - Domino V12 Certification Manager
June OpenNTF Webinar - Domino V12 Certification ManagerJune OpenNTF Webinar - Domino V12 Certification Manager
June OpenNTF Webinar - Domino V12 Certification Manager
 
Smuggling TCP traffic through HTTP
Smuggling TCP traffic through HTTPSmuggling TCP traffic through HTTP
Smuggling TCP traffic through HTTP
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
Web Server-Side Programming Techniques
Web Server-Side Programming TechniquesWeb Server-Side Programming Techniques
Web Server-Side Programming Techniques
 
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
Handling 10k requests per second with Symfony and Varnish - SymfonyCon Berlin...
 
Wcf Transaction Handling
Wcf Transaction HandlingWcf Transaction Handling
Wcf Transaction Handling
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF Workshop
 
HTTP - The Other Face Of Domino
HTTP - The Other Face Of DominoHTTP - The Other Face Of Domino
HTTP - The Other Face Of Domino
 
Server-Side Programming Primer
Server-Side Programming PrimerServer-Side Programming Primer
Server-Side Programming Primer
 
Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...
Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...
Benefits of Reactive Programming with Reactor and Spring Boot 2 - Violeta Geo...
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...
 
CollabSphere 2018: How to build your SmartCloud Notes hybrid environment
CollabSphere 2018: How to build your SmartCloud Notes hybrid environmentCollabSphere 2018: How to build your SmartCloud Notes hybrid environment
CollabSphere 2018: How to build your SmartCloud Notes hybrid environment
 
Introduction to vSphere APIs Using pyVmomi
Introduction to vSphere APIs Using pyVmomiIntroduction to vSphere APIs Using pyVmomi
Introduction to vSphere APIs Using pyVmomi
 
Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
 
× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...
× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...
× The Road To A #Perfect10 - How To Get Ready For Domino, Sametime, VOP and T...
 

Destacado

Yedirenk THM korosu Resimleri
Yedirenk THM korosu ResimleriYedirenk THM korosu Resimleri
Yedirenk THM korosu Resimleriaokutur
 
Leervoorkeuren - Social Friday Seats 2 Meet Happiness@Work
Leervoorkeuren - Social Friday Seats 2 Meet Happiness@WorkLeervoorkeuren - Social Friday Seats 2 Meet Happiness@Work
Leervoorkeuren - Social Friday Seats 2 Meet Happiness@WorkTauros Marketing
 
OneCafé: The future of membership organizations facilitated by CRM and collab...
OneCafé: The future of membership organizations facilitated by CRM and collab...OneCafé: The future of membership organizations facilitated by CRM and collab...
OneCafé: The future of membership organizations facilitated by CRM and collab...Orbit One - We create coherence
 
EPiServer CMS 6 UI
EPiServer CMS 6 UIEPiServer CMS 6 UI
EPiServer CMS 6 UITed Nyberg
 
Serap mutlu akbulut 21 şubat 2014 konserinden resimler
Serap mutlu akbulut 21 şubat 2014 konserinden resimlerSerap mutlu akbulut 21 şubat 2014 konserinden resimler
Serap mutlu akbulut 21 şubat 2014 konserinden resimleraokutur
 
Participation meeting
Participation meetingParticipation meeting
Participation meetingHyde School
 
Citrexindisinfectionofshrimpseng
CitrexindisinfectionofshrimpsengCitrexindisinfectionofshrimpseng
CitrexindisinfectionofshrimpsengCITREX
 
TWTRCON SF 10 BrainPop: Stickybits
TWTRCON SF 10 BrainPop: StickybitsTWTRCON SF 10 BrainPop: Stickybits
TWTRCON SF 10 BrainPop: StickybitsEdelman
 
WTR 平台介紹
WTR 平台介紹WTR 平台介紹
WTR 平台介紹waytorich
 
Информационный вестник Сентябрь 2013
Информационный вестник Сентябрь 2013 Информационный вестник Сентябрь 2013
Информационный вестник Сентябрь 2013 Ingria. Technopark St. Petersburg
 
07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact07.Notifications & Reminder, Contact
07.Notifications & Reminder, ContactNguyen Tuan
 

Destacado (20)

Yedirenk THM korosu Resimleri
Yedirenk THM korosu ResimleriYedirenk THM korosu Resimleri
Yedirenk THM korosu Resimleri
 
Micky Ds
Micky DsMicky Ds
Micky Ds
 
Leervoorkeuren - Social Friday Seats 2 Meet Happiness@Work
Leervoorkeuren - Social Friday Seats 2 Meet Happiness@WorkLeervoorkeuren - Social Friday Seats 2 Meet Happiness@Work
Leervoorkeuren - Social Friday Seats 2 Meet Happiness@Work
 
OneCafé: The future of membership organizations facilitated by CRM and collab...
OneCafé: The future of membership organizations facilitated by CRM and collab...OneCafé: The future of membership organizations facilitated by CRM and collab...
OneCafé: The future of membership organizations facilitated by CRM and collab...
 
Evan & ethan
Evan & ethanEvan & ethan
Evan & ethan
 
EPiServer CMS 6 UI
EPiServer CMS 6 UIEPiServer CMS 6 UI
EPiServer CMS 6 UI
 
Serap mutlu akbulut 21 şubat 2014 konserinden resimler
Serap mutlu akbulut 21 şubat 2014 konserinden resimlerSerap mutlu akbulut 21 şubat 2014 konserinden resimler
Serap mutlu akbulut 21 şubat 2014 konserinden resimler
 
Inbound Marketing - SEO
Inbound Marketing - SEOInbound Marketing - SEO
Inbound Marketing - SEO
 
Cpd 102 ab fall10session1
Cpd 102 ab fall10session1Cpd 102 ab fall10session1
Cpd 102 ab fall10session1
 
Participation meeting
Participation meetingParticipation meeting
Participation meeting
 
Citrexindisinfectionofshrimpseng
CitrexindisinfectionofshrimpsengCitrexindisinfectionofshrimpseng
Citrexindisinfectionofshrimpseng
 
Becoming a Web 2.0 Philanthropy
Becoming a Web 2.0 PhilanthropyBecoming a Web 2.0 Philanthropy
Becoming a Web 2.0 Philanthropy
 
Information Literacy
Information LiteracyInformation Literacy
Information Literacy
 
Delta M
Delta MDelta M
Delta M
 
TWTRCON SF 10 BrainPop: Stickybits
TWTRCON SF 10 BrainPop: StickybitsTWTRCON SF 10 BrainPop: Stickybits
TWTRCON SF 10 BrainPop: Stickybits
 
Vestnik april 2014
Vestnik april 2014Vestnik april 2014
Vestnik april 2014
 
WTR 平台介紹
WTR 平台介紹WTR 平台介紹
WTR 平台介紹
 
Информационный вестник Сентябрь 2013
Информационный вестник Сентябрь 2013 Информационный вестник Сентябрь 2013
Информационный вестник Сентябрь 2013
 
07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact07.Notifications & Reminder, Contact
07.Notifications & Reminder, Contact
 
最小化
最小化最小化
最小化
 

Similar a 11.Open Data Protocol(ODATA)

16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming ServersAdil Jafri
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSPGary Yeh
 
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysUsing communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysCodemotion Tel Aviv
 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescueMarko Heijnen
 
HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014Christian Wenz
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The ApproachHaci Murat Yaman
 
SharePoint 2013 APIs
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIsJohn Calvert
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#caohansnnuedu
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajaxSynapseindiappsdevelopment
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...SPTechCon
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0Ido Flatow
 
SignalR: Add real-time to your applications
SignalR: Add real-time to your applicationsSignalR: Add real-time to your applications
SignalR: Add real-time to your applicationsEugene Zharkov
 

Similar a 11.Open Data Protocol(ODATA) (20)

Philly Tech Fest Iis
Philly Tech Fest IisPhilly Tech Fest Iis
Philly Tech Fest Iis
 
16network Programming Servers
16network Programming Servers16network Programming Servers
16network Programming Servers
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsysUsing communication and messaging API in the HTML5 world - GIl Fink, sparXsys
Using communication and messaging API in the HTML5 world - GIl Fink, sparXsys
 
Node.js to the rescue
Node.js to the rescueNode.js to the rescue
Node.js to the rescue
 
HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014HTML5/JavaScript Communication APIs - DPC 2014
HTML5/JavaScript Communication APIs - DPC 2014
 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
SharePoint 2013 APIs
SharePoint 2013 APIsSharePoint 2013 APIs
SharePoint 2013 APIs
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
 
signalr
signalrsignalr
signalr
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
 
SignalR: Add real-time to your applications
SignalR: Add real-time to your applicationsSignalR: Add real-time to your applications
SignalR: Add real-time to your applications
 
Servlet
ServletServlet
Servlet
 

Más de Nguyen Tuan

12.Maps and Location
12.Maps and Location12.Maps and Location
12.Maps and LocationNguyen Tuan
 
10.Local Database & LINQ
10.Local Database & LINQ10.Local Database & LINQ
10.Local Database & LINQNguyen Tuan
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
08.Push Notifications
08.Push Notifications 08.Push Notifications
08.Push Notifications Nguyen Tuan
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone StoreNguyen Tuan
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows PhoneNguyen Tuan
 
05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & AnimationNguyen Tuan
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows PhoneNguyen Tuan
 
04.Navigation on Windows Phone
04.Navigation on Windows Phone04.Navigation on Windows Phone
04.Navigation on Windows PhoneNguyen Tuan
 
02.Designing Windows Phone Application
02.Designing Windows Phone Application02.Designing Windows Phone Application
02.Designing Windows Phone ApplicationNguyen Tuan
 

Más de Nguyen Tuan (10)

12.Maps and Location
12.Maps and Location12.Maps and Location
12.Maps and Location
 
10.Local Database & LINQ
10.Local Database & LINQ10.Local Database & LINQ
10.Local Database & LINQ
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 
08.Push Notifications
08.Push Notifications 08.Push Notifications
08.Push Notifications
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone Store
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows Phone
 
05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation05.Blend Expression, Transformation & Animation
05.Blend Expression, Transformation & Animation
 
03.Controls in Windows Phone
03.Controls in Windows Phone03.Controls in Windows Phone
03.Controls in Windows Phone
 
04.Navigation on Windows Phone
04.Navigation on Windows Phone04.Navigation on Windows Phone
04.Navigation on Windows Phone
 
02.Designing Windows Phone Application
02.Designing Windows Phone Application02.Designing Windows Phone Application
02.Designing Windows Phone Application
 

Último

9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Servicenishacall1
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfCWS Technology
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 

Último (6)

9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 

11.Open Data Protocol(ODATA)

  • 1. Network Communication Open Data Protocol (ODATA) Nguyen Tuan | Microsoft Certified Trainer
  • 2. Agenda • Networking for Windows Phone • WebClient • HttpWebRequest • Sockets • Web Services and OData • Simulation Dashboard • Data Compression
  • 4. Networking on Windows Phone • Support for networking features • Windows Communication Foundation (WCF) • HttpWebRequest • WebClient • Sockets • Full HTTP header access on requests • NTLM authentication 4
  • 5. New Features in WP8 • Two different Networking APIs • System.Net – Windows Phone 7.1 API, upgraded with new features • Windows.Networking.Sockets – WinRT API adapted for Windows Phone • Support for IPV6 • Support for the 128-bit addressing system added to System.Net.Sockets and also is supported in Windows.Networking.Sockets • NTLM and Kerberos authentication support • Incoming Sockets • Listener sockets supported in both System.Net and in Windows.Networking • Winsock support • Winsock supported for native development 8/16/2014 5
  • 6. Networking APIs Platform Availability API WP7.1 WP8 W8 System.Net.WebClient    System.Net.HttpWebRequest    System.Net.Http.HttpClient    Windows.Web.Syndication.SyndicationClient    Windows.Web.AtomPub.AtomPubClient    ASMX Web Services    WCF Services    OData Services    8/16/2014 6
  • 7. Async support in WP8 Networking APIs • C# 5.0 includes the async and await keywords to ease writing of asynchronous code • In desktop .NET 4.5, and in Windows 8 .NET for Windows Store Apps, new Task-based methods allow networking calls as an asynchronous operation using a Task object • HttpClient API • WebClient.DownloadStringTaskAsync(), DownloadFileTaskAsync(), UploadStringTaskAsync() etc • HttpWebRequest.GetResponseAsync() • These methods are not supported on Windows Phone 8 • Task-based networking using WebClient and HttpWebRequest still possible using TaskFactory.FromAsync()and extension methods • Coming up later… 8/16/2014 7
  • 8. Connecting the Emulator to Local Services 8/16/2014 8
  • 9. • In Windows Phone 7.x, the emulator shared the networking of the Host PC •You could host services on your PC and access them from your code using http://localhost... • In Windows Phone 8, the emulator is a Virtual machine running under Hyper-V •You cannot access services on your PC using http://localhost... •You must use the correct host name or raw IP address of your host PC in URIs WP8 Emulator and localhost 8/16/2014
  • 10. • If you host your web sites or services in IIS, you must open your firewall for incoming HTTP requests Configuring Web Sites Running in Local IIS 8 Firewall 8/16/2014
  • 11. • If your service is a WCF service, you must also ensure that HTTP Activation is checked in Turn Windows features on or off Configuring Web Sites Running in Local IIS 8 WCF Service Activation 8/16/2014
  • 12. • Create your website or web service in Visual Studio 2012 • Run it and it is configured to run in localhost:port Configuring Sites Running in IIS Express STEP 1: Create Your Website or Web service 8/16/2014
  • 13. • Remove your website (don’t delete!) from the Visual Studio 2012 solution • Edit the file C:UsersyourUsernameDocumentsIISExpressconfigapplicationhost.config • Find the <sites> section • Find the entry for the website or service you just created • Change <binding protocol="http" bindingInformation="*:nnnn:localhost" /> to <binding protocol="http" bindingInformation="*:nnnn:YourPCName" /> • Save changes • Use ‘Add Existing Website’ to add the website folder back into your solution Configuring Sites Running in IIS Express STEP 2: Modify Config to Run on a URI Using Your PC Name 8/16/2014
  • 14. • From a Command Prompt (Run as Administrator), open the port in the Firewall: netsh advfirewall firewall add rule name="IIS Express (non-SSL)" action=allow protocol=TCP dir=in localport=nnnn • Also run the following at the command prompt: netsh http add urlacl url=http://yourPC:nnnn/ user=everyone • Substitute yourPC with the host name of your Host PC • Substitute 8080 for the port where your service is running • Run it and access from your desktop browser – Now it is hosted at YourPCName:port Useful References: • How to: Specify a Port for the Development Server http://msdn.microsoft.com/en-us/library/ms178109(v=VS.100).aspx Configuring Sites Running in IIS Express STEP 3: Open Port in the Firewalland RegisterURL 8/16/2014
  • 16. Simple Http Operations – WebClient using System.Net; ... WebClient client; // Constructor public MainPage() { ... client = new WebClient(); client.DownloadStringCompleted += client_DownloadStringCompleted; } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { this.downloadedText = e.Result; } private void loadButton_Click(object sender, RoutedEventArgs e) { client.DownloadStringAsync(new Uri("http://MyServer/ServicesApplication/rssdump.xml")); }
  • 17. • No Task-based async methods have been added to WebClient • Async operation possible using custom extension methods, allowing usage such as: WebClient using async/await 17 using System.Net; using System.Threading.Tasks; ... private async void loadButton_Click(object sender, RoutedEventArgs e) { var client = new WebClient(); string response = await client.DownloadStringTaskAsync(new Uri("http://MyServer/ServicesApplication/rssdump.xml")); this.downloadedText = response; }
  • 18. More Control – HttpWebRequest private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { var request = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Suppliers") as HttpWebRequest; request.Accept = "application/json;odata=verbose"; // Must pass the HttpWebRequest object in the state attached to this call // Begin the request… request.BeginGetResponse(new AsyncCallback(GotResponse), request); } • HttpWebRequestis a lower level API that allows access to the requestand response streams • The state object passed in the BeginGetResponsecall must be the initiating HttpWebRequest object, or a custom state object containing the HttpWebRequest
  • 19. HttpWebRequest – Response Handling private void GotResponse(IAsyncResult asynchronousResult) { try { string data; // State of request is asynchronous HttpWebRequest myHttpWebRequest = (HttpWebRequest)asynchronousResult.AsyncState; ; using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult)) { // Read the response into a Stream object. System.IO.Stream responseStream = response.GetResponseStream(); using (var reader = new System.IO.StreamReader(responseStream)) { data = reader.ReadToEnd(); } responseStream.Close(); } // Callback occurs on a background thread, so use Dispatcher to marshal back to the UI thread this.Dispatcher.BeginInvoke(() => { MessageBox.Show("Received payload of " + data.Length + " characters"); } ); } catch (Exception e) ... }
  • 20. HttpWebRequest – Error Handling private void GotResponse(IAsyncResult asynchronousResult) { try { // Handle the Response ... } catch (Exception e) { var we = e.InnerException as WebException; if (we != null) { var resp = we.Response as HttpWebResponse; var code = resp.StatusCode; this.Dispatcher.BeginInvoke(() => { MessageBox.Show("RespCallback Exception raised! Message:" + we.Message + "HTTP Status: " + we.Status); }); } else throw; } }
  • 21. HttpWebRequest – Using TPL Pattern private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { var request = HttpWebRequest.Create("http://yourPC:15500/NorthwindDataService.svc/Suppliers") as HttpWebRequest; request.Accept = "application/json;odata=verbose"; // Use the Task Parallel Library pattern var factory = new TaskFactory(); var task = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null); try { var response = await task; // Read the response into a Stream object. System.IO.Stream responseStream = response.GetResponseStream(); string data; using (var reader = new System.IO.StreamReader(responseStream)) { data = reader.ReadToEnd(); } responseStream.Close(); MessageBox.Show("Received payload of " + data.Length + " characters"); } catch (Exception ex) ...
  • 22. HttpWebRequest (TPL) – Error Handling private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { try { // Make the call and handle the Response ... } catch (Exception e) { var we = e.InnerException as WebException; if (we != null) { var resp = we.Response as HttpWebResponse; var code = resp.StatusCode; MessageBox.Show("RespCallback Exception raised! Message:" + we.Message + "HTTP Status: " + we.Status); } else throw e; } }
  • 25. WCF/ASMX Services • Can ‘Add Reference’ from Windows Phone projects to automatically generate proxy classes • ASMX should ‘just work’ • WCF requires that you use basicHttpBinding 25
  • 26. RESTful Web Services Building them • Rather than building “walled gardens,” data should be published in a way that allows it to reach the broadest range of mobile clients • Old-style ASMX SOAP 1.1 Web Services using ASP.NET or Windows Communication Foundation (WCF) require clients to implement SOAP protocol • With Windows Phone 7 and Silverlight, we use WCF with BasicHttpBinding both on-premise and as a Web Role in Windows Azure to publish our data from local and cloud-based data sources like SQL Azure • Recommend using lightweight REST + JSON Web Services that are better optimized for high-latency, slow, intermittent wireless data connections 26
  • 27. WCF Data Services: OData • WCF Data Services provide an extensible tool for publishingdata 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
  • 28. Generate Client Proxy • In most cases, Add Service Reference will just work • Alternatively, open a command prompt as administrator and navigate to C:Program Files (x86)Microsoft WCF Data Services5.0toolsPhone • Run this command DataSvcutil_WindowsPhone.exe /uri:http://odata.netflix.com/v2/Catalog/ /DataServiceCollection /Version:1.0/out:netflixClientTypes • Add generated file to your project
  • 29. Fetching Data 29 public partial class NorthwindModel { NorthwindEntities context; private DataServiceCollection<Customer> customers; private override void LoadData() { context = new NorthwindEntities(new Uri("http://services.odata.org/V3/Northwind/Northwind.svc/")); // Initialize the context and the binding collection customers = new DataServiceCollection<Customer>(context); // Define a LINQ query that returns all customers. var query = from cust in context.Customers select cust; // Register for the LoadCompleted event. customers.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(customers_LoadCompleted); // Load the customers feed by executing the LINQ query. customers.LoadAsync(query); } ...
  • 30. Fetching Data - LoadCompleted 30 ... void customers_LoadCompleted(object sender, LoadCompletedEventArgs e) { if (e.Error == null) { // Handling for a paged data feed. if (customers.Continuation != null) { // Automatically load the next page. customers.LoadNextPartialSetAsync(); } else { foreach (Customer c in customers) { //Add each customer to our View Model collection App.ViewModel.Customers.Add(new CustomerViewModel(){SelectedCustomer = c}); } } } else { MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message)); } }
  • 32. Open Data Protocol (OData) • “RESTful” Web protocol • Designed to work with data across HTTP • Built on existing Web standards • Uses popular formats to return data payloads to consumer • Uses self-describing metadata • Has multiple options to build implementation based on standard protocol • Soon to be a full web standard
  • 33. The Basics of OData Feeds, which are Collections of typed Entities OData services can expose Actions and Functions (v4), Services (v3) OData services expose all these constructs via URIs OData service may also expose a Service Metadata Document
  • 34. Full SQL like Query “Language” HTTP Command (Verb) SQL Command GET SELECT PUT UPDATE POST INSERT DELETE DELETE
  • 37. OData Best Practices (Producer) • Always design your OData feed will server-side paging if your entity collections hold large amounts of data. • Looks at server-side validation of queries and data updates based on the user credentials sent through HTTP
  • 39. What does OData give me and my organization? Empower Internal Power Users Empower Existing and Future Customers Monetize Data for untapped Revenue
  • 41. OData Best Practices (Consumer) • Use Query Projection to only bring back the entity properties you or your app needs. • Think about client-side paging even if their exists server-side paging. • Design and implement a client-side data caching function in your app (unless sensitive data).
  • 43. Summaries • WebClient and HttpWebRequest for HTTP communications • Windows Phone has a sockets API to support connection-oriented and connectionless TCP/IP and UDP/IP networking • Support for ASMX, WCF and REST Web Services • DataServicesClient for OData service access out of the box in 7.1 SDK • Consider JSON serialization for maximum data transfer efficiency • Windows Phone 8 supports Basic, NTLM, digest and Kerberos authentication • Encrypt sensitive data on the phone using the ProtectedData class