Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Windows 8 Web Sevices

Windows 8 Web Sevices

This Presentation talks about how to create your first web service in windows 8 applications and using the bing translator API as an example

Avatar for amrabulnaga

amrabulnaga

October 01, 2012
Tweet

More Decks by amrabulnaga

Other Decks in Programming

Transcript

  1. Microsoft Student Partners Windows 8 Training How to develop a

    Windows 8 “Web Service App” ? Example: Bing Translator API
  2. Agenda Technical Concepts Bing Translator API Access Token UI Design

    Connection – Request – Response – Translate Surprise ! Brain Storming “Web Service Apps”
  3. Bing Translator API http://api.microsofttranslator.com Bing Translator API (Application Programming Interface)

    is an online service made for developers to have access to the online Bing Translation service and add it to their applications easily
  4. Bing Translator API Bing Translator API is part of Windows

    Azure marketplace https://datamarket.azure.com/dataset/bing/microsofttranslator To access Bing Translator, it must be authorized via OAuth, and an access_token.
  5. Bing Translator API - Access Token What is an access_token?

    Its an object that contains the security information for a login session identifying the user. How to get an access_token? You must register your application via https://datamarket.azure.com/developer/applications/
  6. Bing Translator API - Access Token You’ll be given a

    Client Secret Key which you’ll use further in your app. Write your Client ID and Application Name and a Redirect URI if available if not then write any valid URL
  7. UI Design 1- Now that we have registered our app

    and reserved an access token let’s start developing the application  2- Drag and drop controls from the Toolbox 3- We will use 3 controls a TextBox to allow the user input string then a TextBlock to output the translated string and a button that when pressed the string will be processed for translation
  8. Developing: Connection Double Click on the button, a function opens!

    Create the request for the OAuth service that will get us our access tokens and the request connection type will be POST.
  9. Developing: Connection Code Using Windows.Networking.Connectivity; private async void Button_Click_1(object sender,

    RoutedEventArgs e) { if (NetworkInformation.GetInternetConnectionProfile() != null && NetworkInformation.GetInternetConnectionProfile().GetNetworkConnectivityLevel() != false && NetworkConnectivityLevel.InternetAccess != false) { // Initialize the strTextToTranslate here, while we're on the UI thread strTextToTranslate = txtbox1.Text; // STEP 1: Create the request for OAuth service that will get us our access tokens. String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; WebRequest req = WebRequest.Create(strTranslatorAccessURI); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; IAsyncResult writeRequestStreamCallback = (IAsyncResult)req.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), req); } }
  10. Developing: Request Now we will use the access token that

    we created before to complete our request to the azure service using the clientID , the clientSecret and send it in a postStream via a HttpWebRequest
  11. Developing: Request Code private void RequestStreamReady(IAsyncResult ar) { string clientID

    = "dicta123"; string clientSecret = "BJf5LqpyNrFQwANKuoyoUNeHBAGQxpBTtQAwvPd7RLE="; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http ://api.microsofttranslator.com", WebUtility.UrlEncode(clientID), WebUtility.UrlEncode(clientSecret)); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)ar.AsyncState; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strRequestDetails); System.IO.Stream postStream = request.EndGetRequestStream(ar); postStream.Write(bytes, 0, bytes.Length); request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); }
  12. Developing: Response This method we will use to get the

    response from the token after being processed We used the serializer here to read the response stream an then store it in a token The most important part is the translation URI which calls the translator service via a HttpWebRequest and sends the text that needs translation the last part of the URI is what decides the requested language for translation and the current language than the user used “&from=&to=ar” if we left the from empty it will auto detect the language used.
  13. Developing: Response Code private void GetResponseCallback(IAsyncResult ar) { HttpWebRequest request

    = (HttpWebRequest)ar.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(response.GetResponseStream()); string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Net.WebUtility.UrlEncode(strTextToTranslate) + "&from=&to=ar"; System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uri); string headerValue = "Bearer " + token.access_token; translationWebRequest.Headers["Authorization"] = headerValue; IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(translationReady), translationWebRequest); }
  14. Developing: Translation This function retrieves the result translated from the

    WebResponse as an XML then points to the First node to convert it to string and display it to the user. First we created a response string which carries the response stream Then it was parsed as an XML At last we used the Dispatcher.RunAsync to update part of the page only not to reload all of the page then the translated string appears finally in the text block
  15. Developing: Translation Code private async void translationReady(IAsyncResult ar) { HttpWebRequest

    request = (HttpWebRequest)ar.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar); System.IO.Stream streamResponse = response.GetResponseStream(); System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); System.Xml.Linq.XDocument xTranslation = System.Xml.Linq.XDocument.Parse(responseString); string strTest = xTranslation.Root.FirstNode.ToString(); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { txtblock1.Text = strTest;}); }
  16. Demo Get the Access Token Explore Architecture of a Windows

    8 project Add App Assets (Images) Redefine App, Windows Store Data (Package.appxmanifest) Build UI Build connection functions
  17. What’s Next ? – Windows Store Microsoft Windows Store Guidelines

    - Windows 8 app certification requirements http://msdn.microsoft.com/en-US/library/windows/apps/hh694083 - Resolving certification errors http://msdn.microsoft.com/en-us/library/windows/apps/hh921583.aspx
  18. What’s Next ? – Extra Features Accelerometer sensor - App

    tiles - Background task - Toast notifications - media playback - Search contract - Trial app and in-app purchase - Snapping - Secondary tiles - Sharing content source - Sharing content target - Responding to the appearance of the on-screen keyboard - Removable Storage - Push and periodic notifications client-side & many more …