Charles Petzold www.charlespetzold.com Networking.

Slides:



Advertisements
Similar presentations
What Is Microsoft Marketplace DataMarket What Is Microsoft Marketplace DataMarket? Michael Stiefel
Advertisements

REST &.NET James Crisp.NET Practice Lead ThoughtWorks Australia.
22 мая 2013, Киев Построение Windows 8 приложений для доступа к SharePoint 2013 Бельский Сергей.
Evaluations Submit your evals online.
Staying in Sync with Cloud 2 Device Messaging. About Me Chris Risner Twitter: chrisrisner.
Hypertext Transfer PROTOCOL ----HTTP Sen Wang CSE5232 Network Programming.
Presenter: James Huang Date: Sept. 29,  HTTP and WWW  Bottle Web Framework  Request Routing  Sending Static Files  Handling HTML  HTTP Errors.
XML in the real world (2) SOAP. What is SOAP? ► SOAP stands for Simple Object Access Protocol ► SOAP is a communication protocol ► SOAP is for communication.
Programering af mobile enheder Windows Phone Rss Feed.
SOAP Quang Vinh Pham Simon De Baets Université Libre de Bruxelles1.
1 Configuring Internet- related services (April 22, 2015) © Abdou Illia, Spring 2015.
Push to ALL the iPhones with Azure Chris Risner Senior Technical Microsoft Azure.
1 Configuring Web services (Week 15, Monday 4/17/2006) © Abdou Illia, Spring 2006.
Overview Of Microsoft New Technology ENTER. Processing....
Web Services Rob S. Miles | Microsoft MVP | University of Hull, UK Andy Wigley | Microsoft MVP | Appa Mundi Session 11.0.
Definitions, Definitions, Definitions Lead to Understanding.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
| Basel Discovering Windows Azure Mobile Services and Media Services Ken Casada
Getting Started with WCF Windows Communication Foundation 4.0 Development Chapter 1.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
Name Title Microsoft Corporation Push Notification Introduction and Platform Interaction.
ONLINE CONFERENCE DESIGN.BUILD.DELIVE R with WINDOWS PHONE THURSDAY 24 MARCH 2011.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
Ajax (Asynchronous JavaScript and XML). AJAX  Enable asynchronous communication between a web client and a server.  A client is not blocked when an.
JavaScript & jQuery the missing manual Chapter 11
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CS378 - Mobile Computing Web - WebView and Web Services.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
Silverlight 2 has rich networking support SOAP/XML Web services via WCF proxies Untyped HTTP services (REST, RSS, ATOM) via HttpWebRequest and WebClient.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
HyperText Transfer Protocol (HTTP).  HTTP is the protocol that supports communication between web browsers and web servers.  A “Web Server” is a HTTP.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
Google Cloud Messaging for Android (GCM) is a free service that helps developers send data from servers to their Android.
JavaScript, Fourth Edition
Windows Phone 8 uses Microsoft Push Notifications Windows 8/8.1 uses Windows Notification Service Windows Phone 8.1 uses Windows Notification.
Lets call these the “.NET/MPN APIs” We’re here for you Microsoft.Phone.Notification, Microsoft.Phone.Shell HttpNotificationChannel, ShellTile,
Microsoft Visual Studio 2010 Muhammad Zubair MS (FAST-NU) Experience: 5+ Years Contact:- Cell#:
INFO 344 Web Tools And Development CK Wang University of Washington Spring 2014.
© 2009 Research In Motion Limited Advanced Java Application Development for the BlackBerry Smartphone Trainer name Date.
Microsoft Visual Studio 2010 Muhammad Zubair MS (FAST-NU) Experience: 5+ Years Contact:- Cell#:
Digital Multimedia, 2nd edition Nigel Chapman & Jenny Chapman Chapter 17 This presentation © 2004, MacAvon Media Productions Multimedia and Networks.
Windows 8 Application Microsoft Word with Apps For Office Internal O365 SharePoint Site Windows Azure Cloud Services Windows Azure Workflow Server.
1 Web Services Web and Database Management System.
Interprocess Communications
Appendix E: Overview of HTTP ©SoftMoore ConsultingSlide 1.
Jan 2001C.Watters1 World Wide Web and E-Commerce Client Side Processing.
Lei Xu Saral Shodhan Ashwini Varma Dustin Bachrach Sudipta Dey Joe Bourne Mustafa Almaasrawi Jorge Raastroem Tobin Valenstein Ali Rafiee Ezhilan Rasappa.
2: Application Layer 1 Chapter 2: Application layer r 2.1 Principles of network applications  app architectures  app requirements r 2.2 Web and HTTP.
Digital Multimedia, 2nd edition Nigel Chapman & Jenny Chapman Chapter 17 This presentation © 2004, MacAvon Media Productions Multimedia and Networks.
Internet Applications (Cont’d) Basic Internet Applications – World Wide Web (WWW) Browser Architecture Static Documents Dynamic Documents Active Documents.
Module 11: Internet Access. Overview Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security.
Overview of Servlets and JSP
Really Useful Web Services
COMP2322 Lab 2 HTTP Steven Lee Jan. 29, HTTP Hypertext Transfer Protocol Web’s application layer protocol Client/server model – Client (browser):
Windows Phone Tiles and Notifications Sending alerts to your app.
Exploring Mobile Device Networking Lesson 4. Exam Objective Matrix Skills/ConceptsMTA Exam Objectives Understanding Networking for Mobile Devices Network.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek
The Mechanics of HTTP Requests and Responses and network connections.
App Peripherals CAN BILGIN, Authority Partners Inc.
HTTP – An overview.
Data Virtualization Tutorial… CORS and CIS
Computing with C# and the .NET Framework
Building real-time web apps with WebSockets using IIS, ASP.NET and WCF
WEB API.
Configuring Internet-related services
1/16/2019 8:14 PM SAC-863T Delivering notifications with the Windows Push Notification Service and Windows Azure Darren Louie, Nick Harris Program Manager,
Using tiles and notifications
WCF Data Services and Silverlight
Erik Porter Program Manager ASP.NET Microsoft Corporation
Presentation transcript:

Charles Petzold Networking

Agenda WebClient HttpWebRequest Consuming REST services Consuming ASMX and WCF services Push notification services Tile scheduling

Silverlight vs. SWP FeatureSilverlightSWP Cross-domain networking Requires elevated permissions or policy file No restrictions Cross-protocol networking Requires elevated permissions or policy file No restrictions Networking stacks Browser stack and client stackClient stack only Duplex networking PollingDuplexHttpBinding and NetTcpBinding HttpNotificationChannel Authentication Basic, digest, NTLM, and formsBasic and forms Sockets YesNot supported UDP multicasting YesNot supported

Event-based HTTP networking API –Asynchronous operation only Commonly used to download assets –DownloadStringAsync - String –OpenReadAsync – Stream (binary) –Also features uploading methods Fires progress and completion events and supports cancellation of pending requests –Event handlers execute on calling thread WebClient

Downloading an Image File WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted); wc.OpenReadAsync(new Uri (" private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { BitmapImage bi = new BitmapImage(); bi.SetSource(e.Result); MyImage.Source = bi; }

Downloading a Zipped Image File WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted); wc.OpenReadAsync(new Uri(" private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { StreamResourceInfo sri1 = new StreamResourceInfo(e.Result, null); StreamResourceInfo sri2 = Application.GetResourceStream(sri1, new Uri("Bandit.jpg", UriKind.Relative)); BitmapImage bi = new BitmapImage(); bi.SetSource(sri2.Stream); MyImage.Source = bi; }

Updating a Progress Bar WebClient wc = new WebClient(); wc.DownloadProgressChanged += OnDownloadProgressChanged;... private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { Progress.Value = e.ProgressPercentage; }

Downloading an RSS Feed WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted); wc.OpenReadAsync(new Uri("..."));... private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { using (StreamReader reader = new StreamReader(e.Result)) { string rss = reader.ReadToEnd(); // TODO: Parse the feed }

demo WebClient

Delegate-based HTTP networking API –Asynchronous operation only Generally used to call untyped HTTP services –e.g., REST services Completion methods called on background threads from CLR thread pool –Use Dispatcher.BeginInvoke to update UI HttpWebRequest

Calling a REST Service (GET) HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create (new Uri(" request.BeginGetResponse (new AsyncCallback(OnGetResponseCompleted), request);... private void OnGetResponseCompleted(IAsyncResult ar) { HttpWebRequest request = (HttpWebRequest)ar.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd();... }

Calling a REST Service (POST) HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create (new Uri(" request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetRequestStream(new AsyncCallback (OnGetRequestStreamCompleted), request);... private void OnGetRequestStreamCompleted(IAsyncResult ar) { HttpWebRequest request = (HttpWebRequest)ar.AsyncState; using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(ar))) { writer.Write("98052"); // Write input into body of request } request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request); }... private void OnGetResponseCompleted(IAsyncResult ar) {... }

demo HttpWebRequest

Callable through WCF Web service proxies –Use Visual Studio's "Add Service Reference" command to generate proxies Selected WCF bindings supported –BasicHttpBinding (WS-I Basic Profile 1.0) –Custom HTTP binding with binary message encoding –No PollingDuplexHttpBinding or NetTcpBinding Asynchronous operation only ASMX and WCF Services

Use "Add New Item" -> "Silverlight-Enabled WCF Service" command in Visual Studio Creating a WCF Service

Calling a WCF Service ZipCodeServiceClient proxy = new ZipCodeServiceClient(); proxy.GetCityAndStateFromZipCodeCompleted += new EventHandler (GetCityAndStateFromZipCodeCompleted); proxy.GetCityAndStateFromZipCodeAsync("98052");... private void GetCityAndStateFromZipCodeCompleted(object sender, GetCityAndStateFromZipCodeCompletedEventArgs e) { if (e.Error == null) { Place place = e.Result; // Method returns Place object string city = place.City; string state = place.State;... }

demo WCF Services

Asynchronous notifications delivered to phones Utilize Microsoft Push Notification Service (PNS) –Hosted in Azure; massively scalable and reliable –Battery- and bandwidth-efficient alternative to polling Three types of notifications –Raw notifications –Toast notifications –Tile notifications Toast and tile notifications work if app isn't running Push Notifications

How Push Notifications Work Microsoft Push Notification Service Your Web Service Count 3 4 Phone transmits URI to Web service Service calls PNS using transmitted URI PNS sends notification to phone PNS returns URI Phone app requests URI from PNS

Delivered only when app is active –If app is inactive, call to PNS returns HTTP 200 OK with notification status == "Suppressed" Payload can be text or binary data –1K maximum payload size Raw Notifications

Raw Notification Wire Format POST uri HTTP/1.1 X-NotificationClass: interval Host: uri Content-Type: application/*; charset=UTF-8 Content-Length: length payload

Sending a Raw Notification HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = WebRequestMethods.Http.Post; request.Headers.Add("X-NotificationClass", "3"); // Send immediately using (Stream stream = request.GetRequestStream()) { byte[] payload = Encoding.UTF8.GetBytes(message); stream.Write(payload, 0, payload.Length); } HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Delivered even when application is inactive –Displayed in toast window at top of screen –Clicking toast window activates application Also delivered when application is active –Not automatically displayed –App decides what to do Toast Notifications

Toast Notification Wire Format POST uri HTTP/1.1 X-NotificationClass: interval X-WindowsPhone-Target: toast Host: uri Content-Type: application/*; charset=UTF-8 Content-Length: length MessageCaption MessageText

Sending a Toast Notification HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = WebRequestMethods.Http.Post; request.ContentType = "text/xml"; request.Headers["X-WindowsPhone-Target"] = "toast"; request.Headers.Add("X-NotificationClass", "2"); // Send immediately using (Stream stream = request.GetRequestStream()) { byte[] payload = Encoding.UTF8.GetBytes (String.Format(_template, caption, message)); request.ContentLength = payload.Length; stream.Write(payload, 0, payload.Length); } HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Update tiles pinned on start screen ("live tiles") –Change tile background image Local or remote images Max size 80K; must load in under 15 seconds –Change count displayed in tile's upper-right corner –Change title displayed along tile's bottom border Tile Notifications Title Count

Tile Notification Wire Format POST uri HTTP/1.1 X-NotificationClass: interval X-WindowsPhone-Target: tile Host: uri Content-Type: application/*; charset=UTF-8 Content-Length: length BackgroundImageUri Count Title

Sending a Tile Notification HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = WebRequestMethods.Http.Post; request.ContentType = "text/xml"; request.Headers["X-WindowsPhone-Target"] = "token"; request.Headers.Add("X-NotificationClass", "1"); // Send immediately using (Stream stream = request.GetRequestStream()) { byte[] payload = Encoding.UTF8.GetBytes (String.Format(_template, imageuri, count, title)) request.ContentLength = payload.Length; stream.Write(payload, 0, payload.Length); } HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Calls to PNS return important information in HTTP status codes and custom response headers –X-NotificationStatus –X-SubscriptionStatus –X-DeviceConnectionStatus Certain response codes must not be ignored –Subscription may be expired –Subscription may require server-side throttling Response codes documented at PNS Response Codes

Sample Response Codes HTTP Status Notification Status Subscription Status Device Status Comments 200ReceivedActiveConnectedNotification was accepted 200ReceivedActiveTempDisconnected Notification was accepted, but device is disconnected 200QueueFullActiveAny value Notification queue is full; try again later 200SuppressedActiveAny value Notification could not be delivered because application is not active 404Any value Expired Subscription has expired and should be deleted; do not resend 406Any value Per-day quota has been reached; can try to resend once per hour 412Any value Device is inactive; can try to resend once per hour, but with penalties 503Any value PNS is unavailable

Handling Response Codes HttpWebResponse response = request.GetResponse() as HttpWebResponse; int status = (int)response.StatusCode; string xsubscription = null; if (response.Headers["X-SubscriptionStatus"] != null) xsubscription = response.Headers["X-SubscriptionStatus"].ToString(); if ((xsubscription != null && xsubscription == "Expired") || status == 404 || status == 406 || status == 412) { // Delete the subscription RemoveSubscription(uri); }

Class used to connect phone apps to PNS HttpNotificationChannel MethodDescription BindToShellTile Binds channel to tile notifications BindToShellToast Binds channel to toast notifications Close Close an open channel Find Returns an existing channel if that channel exists Open Opens a channel UnbindToShellTile Unbinds channel to tile notifications UnbindToShellToast Unbinds channel to toast notifications

Opening a Channel channel = HttpNotificationChannel.Find("MyChannel"); if (channel == null) // Create a new channel { channel = new HttpNotificationChannel("MyChannel"); RegisterChannelEventHandlers(channel); channel.Open(); // Generates ChannelUriUpdated event } else // Configure an existing channel { RegisterChannelEventHandlers(channel); BindChannel(channel); // TODO: Send the URI to the Web service }

Binding to Notifications // Configure the channel to report toast notifications if (!channel.IsShellToastBound) channel.BindToShellToast(); // Configure the channel to support tile notifications if (!channel.IsShellTileBound) channel.BindToShellTile();

Handling Raw Notifications channel.HttpNotificationReceived += OnRawNotificationReceived;. void OnHttpNotificationReceived(object sender, HttpNotificationEventArgs e) { // Transfer to UI thread if updating the UI Dispatcher.BeginInvoke(() => { // Payload in e.Notification.Body }); }

Handling Toast Notifications channel.ShellToastNotificationReceived += OnToastReceived;... void OnToastReceived(object sender, NotificationEventArgs e) { // Transfer to UI thread if updating the UI Dispatcher.BeginInvoke(() => { string caption = String.Empty; if (e.Collection.ContainsKey("wp:Text1")) caption = e.Collection["wp:Text1"]; string message = String.Empty; if (e.Collection.ContainsKey("wp:Text2")) message = e.Collection["wp:Text2"];... }); }

Handling Tile Notifications This space intentionally left blank

Limit of one open channel per app Limit of 15 open channels per device –No way to know ahead of time how many are open –HttpNotificationChannel.Open throws InvalidOperationException when limit is exceeded Limit of 500 notifications per day per channel –Limit waived for authenticated Web services Apps that use push notifications must comply with WP7 Application Certification Requirements Constraints and Limitations

demo Push Notifications

ShellTileSchedule class permits tiles to be updated periodically by downloading them from a server –Does not count against push notification limit –Frequency cannot exceed one update per hour Options are hourly, daily, weekly, monthly –Max image size 80K; must load in < 15 seconds Updates suspended when screen is locked or off –Updates fire immediately when screen unlocks Tile Scheduling

Scheduling Hourly Updates ShellTileSchedule sts = new ShellTileSchedule(); sts.Interval = UpdateInterval.EveryHour; sts.MaxUpdateCount = 0; // Run indefinitely sts.Recurrence = UpdateRecurrence.Interval; sts.RemoteImageUri = new sts.Start();

Performing a One-Time Update xShellTileSchedule sts = new ShellTileSchedule(); sts.Recurrence = UpdateRecurrence.OneTime; sts.StartTime = DateTime.Now; sts.RemoteImageUri = new sts.Start();

Detecting Connectivity Status if (NetworkInterface.GetIsNetworkAvailable()) { // App is connected } else { // App is not connected }

Detecting Status Changes NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;. void OnNetworkAddressChanged(object sender, EventArgs e) { if (NetworkInterface.GetIsNetworkAvailable()) { // App is connected } else { // App is not connected }

Charles Petzold Questions?