Charles Petzold Networking

  • View
    220

  • Download
    0

Embed Size (px)

Text of Charles Petzold Networking

  • Slide 1

Charles Petzold www.charlespetzold.com Networking Slide 2 Agenda WebClient HttpWebRequest Consuming REST services Consuming ASMX and WCF services Push notification services Tile scheduling Slide 3 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 Slide 4 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 Slide 5 Downloading an Image File WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted); wc.OpenReadAsync(new Uri ("http://www.wintellect.com/images/Bandit.jpg"));... private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { BitmapImage bi = new BitmapImage(); bi.SetSource(e.Result); MyImage.Source = bi; } Slide 6 Downloading a Zipped Image File WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted); wc.OpenReadAsync(new Uri("http://www.wintellect.com/images/Images.zip"));... 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; } Slide 7 Updating a Progress Bar WebClient wc = new WebClient(); wc.DownloadProgressChanged += OnDownloadProgressChanged;... private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { Progress.Value = e.ProgressPercentage; } Slide 8 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 } Slide 9 demo WebClient Slide 10 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 Slide 11 Calling a REST Service (GET) HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create (new Uri("http://contoso.com/weather/98052")); 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();... } Slide 12 Calling a REST Service (POST) HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create (new Uri("http://contoso.com/weather")); 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) {... } Slide 13 demo HttpWebRequest Slide 14 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 Slide 15 "Silverlight-Enabled WCF Service" command in Visual Studio Creating a WCF Service">"Silverlight-Enabled WCF Service" command in Visual Studio Creating a WCF Service">"Silverlight-Enabled WCF Service" command in Visual Studio Creating a WCF Service" title="Use "Add New Item" -> "Silverlight-Enabled WCF Service" command in Visual Studio Creating a WCF Service"> Use "Add New Item" -> "Silverlight-Enabled WCF Service" command in Visual Studio Creating a WCF Service Slide 16 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;... } Slide 17 demo WCF Services Slide 18 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 Slide 19 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 5 1 2 PNS sends notification to phone PNS returns URI Phone app requests URI from PNS Slide 20 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 Slide 21 Raw Notification Wire Format POST uri HTTP/1.1 X-NotificationClass: interval Host: uri Content-Type: application/*; charset=UTF-8 Content-Length: length payload Slide 22 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; Slide 23 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 Slide 24 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 Slide 25 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; Slide 26 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 Slide 27 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 Slide 28 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; Slide 29 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 http://msdn.microsoft.com/en-us/library/ff941100(v=vs.92).aspx PNS Response Codes Slide 30 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 late