11.open data protocol(odata)

43
Network Communication Open Data Protocol (ODATA) Nguyen Tuan | Microsoft Certified Trainer

Upload: nguyen-tuan

Post on 07-Dec-2014

172 views

Category:

Mobile


0 download

DESCRIPTION

Open Data protocol

TRANSCRIPT

Page 1: 11.Open Data Protocol(ODATA)

Network CommunicationOpen Data Protocol (ODATA)

Nguyen Tuan | Microsoft Certified Trainer

Page 2: 11.Open Data Protocol(ODATA)

Agenda

• Networking for Windows Phone• WebClient• HttpWebRequest• Sockets• Web Services and OData• Simulation Dashboard• Data Compression

Page 3: 11.Open Data Protocol(ODATA)

Networking on Windows Phone

Page 4: 11.Open Data Protocol(ODATA)

Networking on Windows Phone

• Support for networking features

• Windows Communication Foundation (WCF)

• HttpWebRequest• WebClient

• Sockets

• Full HTTP header access on requests• NTLM authentication

4

Page 5: 11.Open Data Protocol(ODATA)

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

Page 6: 11.Open Data Protocol(ODATA)

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

Page 7: 11.Open Data Protocol(ODATA)

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

Page 8: 11.Open Data Protocol(ODATA)

Connecting the Emulator to Local Services

8/16/20148

Page 9: 11.Open Data Protocol(ODATA)

• 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

Page 10: 11.Open Data Protocol(ODATA)

• 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 8Firewall

8/16/2014

Page 11: 11.Open Data Protocol(ODATA)

• 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 8WCF Service Activation

8/16/2014

Page 12: 11.Open Data Protocol(ODATA)

• 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 ExpressSTEP 1: Create Your Website or Web service

8/16/2014

Page 13: 11.Open Data Protocol(ODATA)

• Remove your website (don’t delete!) from the Visual Studio 2012 solution

• Edit the file C:\Users\yourUsername\Documents\IISExpress\config\applicationhost.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 ExpressSTEP 2: Modify Config to Run on a URI Using Your PC Name

8/16/2014

Page 14: 11.Open Data Protocol(ODATA)

• 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 ExpressSTEP 3: Open Port in the Firewall and Register URL

8/16/2014

Page 15: 11.Open Data Protocol(ODATA)

WebClient

8/16/2014

15

Page 16: 11.Open Data Protocol(ODATA)

Simple Http Operations – WebClient

using System.Net;...

WebClient client;

// Constructorpublic 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"));}

Page 17: 11.Open Data Protocol(ODATA)

• 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;

}

Page 18: 11.Open Data Protocol(ODATA)

More Control – HttpWebRequest

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e){

var request = HttpWebRequest.Create("http://myServer:15500/NorthwindDataService.svc/Suppliers") as HttpWebRequest;

request.Accept = "application/json;odata=verbose";// Must pass the HttpWebRequest object in the state attached to this call// Begin the request…request.BeginGetResponse(new AsyncCallback(GotResponse), request);

}

• HttpWebRequest is a lower level API that allows access to the request and response streams• The state object passed in the BeginGetResponse call must be the initiating HttpWebRequest

object, or a custom state object containing the HttpWebRequest

Page 19: 11.Open Data Protocol(ODATA)

HttpWebRequest – Response Handlingprivate void GotResponse(IAsyncResult asynchronousResult){

try{

string data; // State of request is asynchronousHttpWebRequest 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 threadthis.Dispatcher.BeginInvoke(() =>

{MessageBox.Show("Received payload of " + data.Length + " characters");

} );}

catch (Exception e) ... }

Page 20: 11.Open Data Protocol(ODATA)

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;}

}

Page 21: 11.Open Data Protocol(ODATA)

HttpWebRequest – Using TPL Patternprivate 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 patternvar 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) ...

Page 22: 11.Open Data Protocol(ODATA)

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;}

}

Page 23: 11.Open Data Protocol(ODATA)

DemoPushNotifications

Page 24: 11.Open Data Protocol(ODATA)

Web Services

Page 25: 11.Open Data Protocol(ODATA)

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

Page 26: 11.Open Data Protocol(ODATA)

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 BasicHttpBindingboth 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

Page 27: 11.Open Data Protocol(ODATA)

WCF Data Services: OData

• WCF Data Services provide an extensible tool for publishing data using a REST-based interface • Publishes and consumes data using the OData web

protocol (http://www.odata.org)

• Formatted in XML or JSON

• WCF Data Services Client Library (DataServicesClient) is a separate download from NuGet• Adds ‘Add Service Reference’ for OData V3 Services

Page 28: 11.Open Data Protocol(ODATA)

Generate Client Proxy

• In most cases, Add Service Reference will just work

• Alternatively, open a command prompt as administrator and navigate to C:\Program Files (x86)\Microsoft WCF Data Services\5.0\tools\Phone

• Run this commandDataSvcutil_WindowsPhone.exe /uri:http://odata.netflix.com/v2/Catalog//DataServiceCollection /Version:1.0/out:netflixClientTypes

• Add generated file to your project

Page 29: 11.Open Data Protocol(ODATA)

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);

}...

Page 30: 11.Open Data Protocol(ODATA)

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 collectionApp.ViewModel.Customers.Add(new CustomerViewModel(){SelectedCustomer = c});

}}

}else{

MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message));}

}

Page 31: 11.Open Data Protocol(ODATA)

Digging into OData

Page 32: 11.Open Data Protocol(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

Page 33: 11.Open Data Protocol(ODATA)

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

Page 34: 11.Open Data Protocol(ODATA)

Full SQL like Query “Language”

HTTP Command (Verb) SQL Command

GET SELECT

PUT UPDATE

POST INSERT

DELETE DELETE

Page 35: 11.Open Data Protocol(ODATA)

The $metadata endpoint

Page 36: 11.Open Data Protocol(ODATA)

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?

Page 37: 11.Open Data Protocol(ODATA)

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

Page 38: 11.Open Data Protocol(ODATA)

Who uses OData?

Page 39: 11.Open Data Protocol(ODATA)

What does OData give me and my organization?

Empower Internal Power Users

Empower Existing and Future Customers

Monetize Data for untapped Revenue

Page 40: 11.Open Data Protocol(ODATA)

DEMOWindowsPhoneOData

Page 41: 11.Open Data Protocol(ODATA)

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).

Page 42: 11.Open Data Protocol(ODATA)

Resources

REST

http://www.ics.uci.edu/~taylor/documents/2002-REST-TOIT.pdf

OData

http://odata.org

http://odataprimer.com

Azure Mobile Serviceshttp://www.windowsazure.com/en-us/develop/mobile/

Page 43: 11.Open Data Protocol(ODATA)

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