11.Open Data Protocol(ODATA)

345 views
272 views

Published on

Open Data protocol

Published in: Mobile
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
345
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

11.Open Data Protocol(ODATA)

  1. 1. [IE Network Communication GE’ Open Data Protocol (ODATA) Nguyen Tuan [ Microsoft Certified Trainer
  2. 2. Agenda Networking for Windows Phone WebC| ient HttpWebRequest Sockets Web Services and OData Simulation Dashboard Data Compression
  3. 3. Networking on Windows Phone
  4. 4. Networking on Windows Phone - Support for networking features - Windows Communication Foundation (WCF) - HttpWebRequest - WebC| ient - Sockets - Full HTTP header access on requests - NTLM authentication
  5. 5. New Features in WP8 - Two different Networking AP| s - System. Net—Windows Phone 7.1 API, upgraded with new features - Windows. Networking. Sockets — WinRT API adapted for Windows Phone - Support for | PV6 - 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
  6. 6. Networking AP| s Platform Availability System. Net. WebC| ient . / System. Net. HttpWebRequest V System. Net. Http. HttpC| ient Windows. Web. Syndication. SyndicationC| ient Windows. Web. Atom Pub. Atom PubC| ient ASMX Web Services V WCF Services OData Services .
  7. 7. Async support in WP8 Networking AP| s - C3! 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. Down| oadStringTaskAsynCl). Down| oadFi| eTaskAsync(), Up| oadStringTaskAsync() 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. 8. Connecting the Emulator to Local Services
  9. 9. WP8 Emulator and Iocalhost - 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: //Iocalhost. .. - In Windows Phone 8, the emulator is a Virtual machine running under Hyper-V -You cannot access services on your PC using httQ: [[| oca| host. .. -You must use the correct host name or raw IP address of your host PC in UR| s
  10. 10. Configuring Web Sites Running in Local IIS 8 Firewall - If you host your web sites or services in IIS, you must open yourfirewall for incoming HTTP requests
  11. 11. Configuring Web Sites Running in Local IIS 8 WCF Service Activation - If your sen/ ice is a WCF service, you must also ensure that HTTP Activation is checked in Turn windows features on or off
  12. 12. Configuring Sites Running in IIS Express STEP 1: create Vaur website or web service - Create your website or web service in Visual Studio 2012 - Run it and it is configured to run in Iocalhostzport —, i _. marry ml: lemplau In lump-nun your ASP war we . p¢«. .n. .. >- m | — Li
  13. 13. Configuring Sites Running in IIS Express STEP 1: Madlfytnnllgla Run on a URI uslrg Your PC Marne I Remove your website (don't delete! ) from the fisua| Studio 2012 solution - Edit the file C: UsersyourU5ernameDocumervts| |SE)q. zressi: orvfigapp| ii: ationhost. i:onfig ' Find the <sites>se: tion - Find the entry for the website or service you iiist createo - change (binding pr‘ata(a1="http" bindingInfnmatian= ' to (binding pr‘ata(a1="http" bindingInfnr~matian= ' - save changes I Use ‘Add Existing Website’ to add the website folder back into your solution ZflflflflZ1K1(31l'IK1St" / > zririnrizvaur-Pcuame" / >
  14. 14. Configuring Sites Running in IIS Express srzp 2: Open Portinthe Firewalland Regis(erURL inistrator), open the port in the Firewall: - From a Command Prompt (Run as Ad IIS Express (non—SSL)" a(t1on: allow notsh advhrcwall firewall add rule nam pr‘oto(ol: TCP d1r*:1n lo(alpor‘t: rmrm - Also run the following at the command prompt: netsn http add urlacl ur1=nttp: //yourPc: nnrm/ user= e/ eryune - Substitute vaurPEwilh the hnslname nlynur Hnsl VC - Substitute Ealialnr the pnrlwhereynur servize l5 running - Run it and access from your desktop browser— Now it is hosted at YourPCName: port Uselul Referenres - Haw Imspeclfya Parllarlhe Develapmem Server hllp/ /msdri. miLrasall. :um/ en—u5/library/ m5]7BlO9(v: VS. lOO). a5px
  15. 15. W: -.tfx<i2Iu; :rn“[
  16. 16. Simple Http Operations — WebC| ient using Systeni. Net; . -iebtweri client; / / Eunstructur public MainPage() { client - new Neb£))en((); client. nawn1aa. istringcamp1ma += clientjawnlaadstringcalipleted; ) void dientyawniaaiistringcampietea(anjut sender, Di>. vr, i>; c J‘g(i)/ Hp, er: A~gs 2) { this. dawnlaadedText = e. Result; ) private void loadfluttaniclizkwbjett sender, m: ec: .er: A~gs 2) { client. DawnlaadStringAsyn((new U‘; (“Http: //M)/ Server/ Servicesnpplicatiun/ rssflump. xml“)); )
  17. 17. WebC| ient using async/ await - No Task-based async methods have been added to Webclient - Async operation possible using custom extension methods, allowing usage such as' using SyStAlii. N!t; using Sy§telii. Thr‘eid)ng. Tisks; mm. asynz / am )oadButton_C)): klob]zzt sender‘, l«: L!(cL. (l! r"vV‘iS .7 ( var‘ .11.": = n. .. / mhU)mvt()3 strung response = malt (Dent. Doun]oidStr*)ngTiskAsyn: (new uni http / /MyServer/ Serv)zempp]natlnn/ rssdump. xmJ' 77; tms. du>4n1uidedText . response; 1
  18. 18. More Control — HttpWebRequest private void PhcneAppli(atianPage_Laaded(obje(t sender, rzouteusverznrgs e) { var request = Htzpwlebfiecuest. Create(“http: //m)/ Server:1SSEE/ NL7r*trvwirmDataSeNi(e. sv(/ Suppliers“) as Httpnwlebfiequesti request. A((ept = “applicatiorl/ jsL7rI; m1ata= verbL7se“; // Must pass the httpwehrzequest objett in the state attached to this call / / Begin the request request. BeginGetRespcnse(r| ew As)r'<(; ,,b; <K(GatRespcnse), request); ' HttpWebReq uestis a tower ‘eve! API that aHows access to the requestand response streams ' The state object passed In the BegIr1GetRespor1se caH must be the initiating HttpWebRequest object, or a custom state object contaimhgthe HttpWebRequest
  19. 19. HttpWebRequest— Response Handling private void GctRespanse(IAsyn(Result asynchronouskesult) { try { String data; // State of request is asynchronous Hupueoxeuues: nvyHtt; MebRequest (Httpwebfiiequest)asyn(hranousResu1t. Asyn(State; ; using (Httprlebkespanse resoonse (moweoaesponse)ny>moweoxeouest. :naceu2esoonse(asynenronousxesult)) { / / Read the response into . i stream abject. System. IU. Stream respcnsestrean response. GetRespcnseStream(); using (var reader e new System. IO. StreamReaI1er(respcnsestream)) { data = reader. ReadToEnd(); ) respanseStream. C1ase(); } / / (allback atturs on a batkgraund thread, so use Dispatcher to marshal back to the M thread this. Dispat(her. BeginInvake(() e; { Messagefiux. Shaw("Re(eived payload of } ): + data. Length + characters“); } catch (Exception e)
  20. 20. HttpWebRequest — Error Handling private ma GotRespanse(IAsyn: Resul( asynchronouskesult) { try { / / Handle the Response ) catch (Exception e) { var we e. IrmerEx(eptian as NebEx(ep(iL7n; if (we null) { var resp = we. Respanse as HttpNebRespL7rse; var code = resp. Status(ode; this. Dispat(her. BeginIrwoke(() = > { Messagefiux. Show(“RespCallba(k Exteptian raised! Messagew + we. I-lessage + “Hrw Status: “ + we. Status); H: } e1se throw; }
  21. 21. HttpWebRequest — Using TPL Pattern private asynt void PhL7neApp1i(atianPage_Laaded(abje(t sender, RL7utedEvenlArgs e) { var request = Httpwebkeuuest. (reate(“http: //yourP(:15568/Nurtmindbataservite. svt/ Suppliers“) as Htlpwebkequest; request. A((ept e “applitatiun/ jszm; udata= verbase"; / / use tne task Parallel Library pattern var Factory = new IasKFa(tL7ry(); var task e factory. FramAsyn(<NebRespunse>(request. EeginGetRespL7nse, request. EndGetRespL7nse, null); try { var response = await task; / / aead the response into a stream abjett. System. IU. S(ream respansestrean e response. GetRespanseStream(); string data; using (var reader e new System. IU. Streamkeader(respunsestream)) { data 5 reader. ReadToEnd(); ) respansestream . c1ase( ); Messagefiux. Shuw(“Re(eived payload of “ + data. tengtn 0 } tattn (txteptiun ex) tharatters“ );
  22. 22. HttpWebRequest (TPL) — Error Handling private asynt void v»aneApp1ieacianvage_Laadea(anje(c sender, mmeasvenurgs e) { try { / / make the (all and handle the Response ) mm. (Exception e) { var we e. IrmerEx(eptian as NebEx(ep(iL7n; if (we null) { var resp = we. Respcnse as HttpNebRespL7rse; var code = resp. Status(ade; MessageEux. Sm1w(“kesptallbatk Exteptiun raised! Messag "Hrw Status: " + we. Status); 4 weJ-lessage 4 ) e1se throw e;
  23. 23. Demo PushNotifications
  24. 24. Web Services
  25. 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 we am. :. ».m t v. N. M . . h. .1.u. ... K.« . ... ms-(W-( lfflfi mu. . HVVVKQ nu . ,.. mu Co v. M. ..‘ 1.. .. .w. «max (. <.o. m- mu’ . ».ms. ... (.. Am. ... «z. msM. M . 6»: Du-<w~v' Ovevmom m. .us. M. comm x. ,.. .us. .«. Xnvv-(I-1)lvur-dnmlrnu ». .. ». ... .,. /s. ... x-u. .x. ... ... /c. ,«. .ns. .V. ‘.. .< ¢. m.(. . »«. ..L 0-: cm.
  26. 26. RESTfu| 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—| atency, slow, intermittent wireless data connections
  27. 27. 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 (hng: [[www. odata. org) ' Formatted in XML or JSDN - WCF Data Services Client Library (DataServicesC| ient) is a separate download from NuGet ' Adds ‘Add Service Reference’ for OData V3 Services om: vzvsum: (sew. xmlns. V <wuIk>DALe> 2n: udm9=“uH—H’ standalone: ‘- P1/Iwww .3 erg/ voamvr V (awn! u: ie>Dzlaull</ Mum KiK|2> . eeuemm hr-l—'Eenr1s ) <alum LiLIe>K: enres</ alum lvlle> </ tallnmmw <rall: clIan hre4='YilIe§'> atom LiLlu>Yll| es</ zmm mle: A/ tullemmw (rail-Ryan we-nu. e.. aae: ... ... :.~> <al0m LiLIe>YllJeAudiaFarmnI5(/ atom title) mm) s lenmn hrel: ‘Yi| IeAwnrdi > (atom Ll[le>YllleAwnrd5(/ atom mm) </ zu mun; rrnlllflrnn ms, -e. .., ... -s
  28. 28. Generate Client Proxy - In most cases, Add Service Reference will just work - Alternatively, open a command prompt as administratorand navigate to C: Program Files (x86)Microsoft WCF Data Services5.0too| sPhone - Run this command Datasvcuti| _WindowsPhone. exe / u ri zhttgfioda ta. net[/ ix. cam[v2[Catalag[ / DataSe rviceCo| |ection / Version:1.0/out: netf| ixC| ientTypes - Add generated file to your project
  29. 29. Fetching Data publit partial class Nartnwinmeqei { Nartnwinqsntities (ontext; private Dataservi(e(ulle(tiL7n<(ustL7mer> custaners; private override void LaadData() { tantext = new Nar*thwindEntities(new Uri("http: //services. adata. arg/ V3/Morthwind/ Narthl-dud. sv(/ ")); // Initialize tne tantext and the binding tauectian (ustaners e new Dataservi(ecu}le(tiL7n<CustL7mer>((antext); / / Define a um; query tnat returns all tustaners. var query = eran (ust in tantext. custaners seiect (us / / negister for tne taaqcanpieteq event. (ustamers. LaadCampleted 4: new sventHanqier<tuaqcenpieteqsventArgs>(tustaners_taa. icanp1eteq); / / Load tne (ustcmers feed by exetuting tne um; query. tustaners. taaqnsynqquery);
  30. 30. Fetching Data — LoadComp| eted mm : usmmers_lnafl(nmp1e(efl(abject sender, LDad(MvIp]etedEventArg5 e7 ( if (e. Ermr 7 M117 ( / / nananng for a paged am feed. if (cusmmers. (nnunuaunn x: M1117 ( / / Automatically ma the next page. cusmmers. lnaflMex(Part1a1Se(Asyn<(7; ) else ( fnreach (mszmer : in customers) ( / /ma each customer m nur View Made] tnllecunn App. V1e14l1nfle1.(us(m| ers. Aflfl(ne14 Iustmuervxevnvdel(7(SeIe: (efl(us(mer = ()7; ) ) ) else ( Ne5sageBox. ShnM(s(ring. Fnrma(("An error has ntturre (er-, e. Errnr. l1essage77; )
  31. 31. Digging into OData
  32. 32. Open Data Protocol (OData) - "RESTfu| ” 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. 33. The Basics of OData Feeds, which are Collections of typed Entlties OData se es 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. 34. Full SQL like Query ”Language” HTl'P Command (Verb) SQL Command GET SELECT PUT UPDATE POST INSERT DELETE DELETE
  35. 35. The Smetadata endpoint nu. .. ma ma. ea. .. “. .. n. us. m=. . um —-nu»: //. cn. .u. .ncmon. ca. ./. ao/ zoo: /an/ m.m~uc. ./. u.¢. : - nup: //Icnena xeranok. can/ Ado/2001/as/ ea-x‘ Vernlmw 1.0‘) nlvu ‘nun: /Inchunu. -ucrosofz. cou/ nae/200!/02/eon‘ u-«pm 'IueI>ausuuuo¢e1'> v<KnuKYlYPI I1.. .--Au: .m. u-> V<I(| y) mopmm: me 'nlAyerxn'/ > ompmym n. .- ‘yuan-/ > azep-umx u. .- ‘VI-ultu-'/ ) anew <prol>uc¥ ~. .e ‘m. ymu- fypu m. .smnq- IluIlnhle- 1. . .- um. .m; u.. -m- u. .:= ... .-m. m. ¢u. ..u. /> 'vuun- Type ‘Ea-. !nuS' Iullablu hue‘/ > -m. u.. .- typo m. .n. us~ mmn. --1.1.. -/> 'v-. m- | ‘yn¢-‘Ed-.5:nnu' uuum. -mm uxl. -nun--12' u. .nc. ... .--u. ..- nxe¢unom. - u-/ > <Propex(y u. ..-¢. ..ur Type-'zd-. szr. nu' Ivulhhle-'zxue' mm. qn. .-a- u. ..m. --. ... .- nuau-nun. --uln-/ > mos-my u. ..—-mn- me Ea-. su. nu‘ u-. u.m. .-. .u. - u. u.. ..u. r| xeauna: h-'1-he‘/ > mwmy >4.. . -59- man m. .x. .us- u. .u. u. -u. ..-/ > <PKuperty Ill-: x'IKaztu-ql‘cu' ryp-—-ns. .x. .us- u. .u. m.x-2.. .;-/ > ouvlqquenrrovury u. —x"K~nye: ' . .x. ua. ..mp—-a. m.: :s: .z. «m: .n<_mu. m.u_n. yu- rnuznlc. 'lunoI: x'PIaver'/ > </ z.. myrype> v<znnr. v1'vx>< lnl¢= 'Ipo<nxnnce'> - u. .:u. .s. .-m. .-
  36. 36. What is a URI? «»('Scheme ]->(Hnst ammpat esouroePa1.h ue! y0puons http: // services . m'£ata. nrg/ onata/ aoata. svc service mat mu http: // services . ndata. nrg/ onata/ ooata. svc/ Categnry(1)/ Pmducts? Stnp= Z&$nrderhy= name / / / service mat mu respuree path query npfinns
  37. 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
  38. 38. Who uses OData? Xtelerik eorest a §F§? 'eP6int'2o1o Q Windowé Azure I gmf Server'2o12 Microsoft 3 ' Q Dynamics’ CRM 5
  39. 39. What does OData give me and my organization? Empower Internal Power Users Empower Existing and Future Customers Monetize Data for untapped Revenue
  40. 40. E *E MPH VAVl| Ilq‘lcmua? ‘hun= lClDn. Ii= |
  41. 41. OData Best Practices (Consumer) ' Use Query Projection to only bring back the entity properties you or your app needs. - Think about c| ient—side paging even if their exists server—side paging. - Design and implement a c| ient—side data caching function in your app (unless sensitive data).
  42. 42. Resources REST http: [/www. ics. uci. edu/ ”'tay| or/ documents/2002-R EST-TOIT. pdf 0Data htt : odata. or htt : odata rimer. com Azure Mobile Services http: [/www. windowsazure. com/ en-us/ deve| oymobi| e[
  43. 43. Summaries - WebC| ient 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 - DataServicesC| ient 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

×