{"id":6980,"date":"2012-12-19T13:23:00","date_gmt":"2012-12-19T21:23:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/translation\/2012\/12\/19\/creating-a-web-application-with-translation-provided-by-microsoft-translator\/"},"modified":"2012-12-19T13:23:00","modified_gmt":"2012-12-19T21:23:00","slug":"creating-a-web-application-with-translation-provided-by-microsoft-translator","status":"publish","type":"post","link":"https://www.microsoft.com\/en-us\/translator/blog\/2012\/12\/19\/creating-a-web-application-with-translation-provided-by-microsoft-translator\/","title":{"rendered":"Creating a Web Application with Translation provided by Microsoft Translator."},"content":{"rendered":"
In this Walkthrough, you\u2019ll learn how to create a Web application that uses the Microsoft Translator API to translate text that was input by the user. You\u2019ll build the page using ASP.NET and the free Visual Studio Express 2012 for Web. If you already have a Visual Studio installation, you\u2019ll still be able to follow the tutorial, just skip step 1.<\/p>\n
Before beginning, you\u2019ll need to sign up for the Microsoft Translator API in Azure. There are a number of different offerings, including a free one, and you can see how to sign up for the free service, register your app and get your credentials here:<\/p>\n
http:\/\/blogs.msdn.com\/b\/translation\/p\/gettingstarted1.aspx<\/a><\/p>\n The Client ID and Client Secret that you generate here will be used in Step 4, so keep a note of them.<\/p>\n The best way to get started is to visit http:\/\/www.asp.net\/downloads<\/a> and select the \u2018Install Now\u2019 button in the \u2018Get Everything with One Simple Install\u2019 section.<\/p>\n This will launch the Web Platform Installer which will install Visual Studio, ASP.NET, MVC and a whole host of other goodies that you can use to build websites.<\/p>\n Run Visual Studio and from the File menu, select \u2018New Project\u2019. You\u2019ll see a dialog containing a list of different projects that are available for you to build websites with. Select \u2018Visual C#\u2019 on the left, and then select \u2018ASP.NET Web Forms Application\u2019 from the list.<\/p>\n Give your Web Application a name, such as \u2018Translator\u2019, and press \u2018OK\u2019. Visual Studio will now create everything you need to build and run the Web Application. Press F5 to build and run the application and you\u2019ll see something like this:<\/p>\n <\/p>\n <\/p>\n In this section, you\u2019ll add controls to the site that allow your end users to type in some text, press a translate button, and then see the translation of the text they entered. This type of functionality is useful for interacting with your customers when you speak different languages, for example.<\/p>\n From Solution explorer, find the \u2018About.aspx\u2019 page. Open it in the designer, and you\u2019ll see something like this:<\/p>\n Delete the 3 <p> tags that say \u2018Use this area to provide additional information\u2019, and replace with some controls to provide a basic translation UI, like this:<\/p>\n For your convenience, here\u2019s the source for this page:<\/p>\n Note that in the designer you should double-click on the button to generate the \u201cButton1_Click\u201d code. You\u2019ll write this code in the next step.<\/p>\n In the previous section, you created a basic UI for text translation. It would allow the user to write some text, and press a button. In this section, you\u2019ll write the code behind that button which will translate the user\u2019s desired text into Spanish, and render it on the page.<\/p>\n First, you\u2019ll need to add a new class to your solution. Call it AdmAccessToken<\/strong> and give it the following code:<\/p>\n <\/p>\n Note that the names of the 4 strings should match what is here exactly, or you will get errors in your code later.<\/p>\n Next, within Visual Studio, in Solution Explorer, right click on the \u2018References\u2019 folder and select \u2018Add Reference\u2019. Use this dialog that follows to add references to<\/p>\n – System.Runtime.Serialization<\/p>\n – System.XML.Linq<\/p>\n – System.ServiceModel.Web<\/p>\n At the top of your code for About.aspx.cs, you\u2019ll see a number of \u2018using\u2019 statements. Add using System.Xml.Linq to these, so that it looks like this:<\/p>\n <\/p>\n You\u2019ll see that the Button1_Click code is empty. Add the following code to it. This code will get your access token for the translator service, using the Client ID and Client Secret that you created earlier on.<\/p>\n <\/p>\n This code forms a POST to the data market service, passing your ID and secret and getting a JSON object back. You then deserialize that object into an AdmAccessToken. You can then derive the access_token from this.<\/p>\n This token is then added to a string, prefixed with \u201cBearer \u201c (don\u2019t forget the space) to create a header value that will be sent to the translator service.<\/p>\n To then call the translator service with this headerValue, and pass the user\u2019s text, you\u2019ll use code like this:<\/p>\n <\/p>\n <\/p>\n The text box was called \u2018TextBox1\u2019 so the text the user typed in can simply be derived from that. After that, a URI to the translator HTTP service is created, and the text itself is UrlEncoded and added to the URI.<\/p>\n Note that the language \u2018en\u2019 is used for \u2018From\u2019 (i.e., I\u2019m assuming you\u2019re typing in English), and \u2018es\u2019 is used for \u2018To\u2019 (i.e. it will translate into Spanish). The full list of these codes for the supported languages is here: http:\/\/msdn.microsoft.com\/en-us\/library\/hh456380.aspx<\/p>\n The translator service returns XML, so the code calls the service, gets the response as XML and then decodes it into text. It then loads the result into the Literal that you created on About.aspx called Literal1.<\/p>\n You can see it in action here:<\/p>\nStep 1. Getting Visual Studio Express 2012 for Web.<\/h3>\n
<\/a><\/p>\n
Step 2. Create the Web Application<\/h3>\n
<\/a><\/p>\n
<\/a><\/p>\n
Step 3. Creating UI for Text Translation<\/h3>\n
<\/a><\/p>\n
<\/a><\/p>\n
<%@ Page Title=\"About\" Language=\"C#\" MasterPageFile=\"~\/Site.Master\" AutoEventWireup=\"true\" CodeBehind=\"About.aspx.cs\" Inherits=\"Translator.About\" %><\/span>\n\n<<\/span>asp:Content<\/span> runat<\/span>=\"server\"<\/span> ID<\/span>=\"BodyContent\"<\/span> ContentPlaceHolderID<\/span>=\"MainContent\"<\/span>><\/span>\n <<\/span>hgroup<\/span> class<\/span>=\"title\"<\/span>><\/span>\n <<\/span>h1<\/span>><\/span><%<\/span>: Title %><\/span>.<\/<\/span>h1<\/span>><\/span>\n <<\/span>h2<\/span>><\/span>Your app description page.<\/<\/span>h2<\/span>><\/span>\n <\/<\/span>hgroup<\/span>><\/span>\n\n <<\/span>article<\/span>><\/span>\n Enter the text you would like to translate:<<\/span>br<\/span> \/><\/span>\n <<\/span>asp:TextBox<\/span> ID<\/span>=\"TextBox1\"<\/span> runat<\/span>=\"server\"<\/span> Height<\/span>=\"25px\"<\/span> Width<\/span>=\"342px\"<\/span>><\/<\/span>asp:TextBox<\/span>><\/span>\n <<\/span>asp:Button<\/span> ID<\/span>=\"Button1\"<\/span> runat<\/span>=\"server\"<\/span> Height<\/span>=\"37px\"<\/span> OnClick<\/span>=\"Button1_Click\"<\/span> Text<\/span>=\"Translate\"<\/span> \/><\/span>\n <<\/span>br<\/span> \/><\/span>\n Your translated text is:<<\/span>br<\/span> \/><\/span>\n <<\/span>asp:Literal<\/span> ID<\/span>=\"Literal1\"<\/span> runat<\/span>=\"server\"<\/span>><\/<\/span>asp:Literal<\/span>><\/span>\n <\/<\/span>article<\/span>><\/span>\n\n <<\/span>aside<\/span>><\/span>\n <<\/span>h3<\/span>><\/span>Aside Title<\/<\/span>h3<\/span>><\/span>\n <<\/span>p<\/span>><\/span> \n Use this area to provide additional information.\n <\/<\/span>p<\/span>><\/span>\n <<\/span>ul<\/span>><\/span>\n <<\/span>li<\/span>><<\/span>a<\/span> runat<\/span>=\"server\"<\/span> href<\/span>=\"~\/\"<\/span>><\/span>Home<\/<\/span>a<\/span>><\/<\/span>li<\/span>><\/span>\n <<\/span>li<\/span>><<\/span>a<\/span> runat<\/span>=\"server\"<\/span> href<\/span>=\"~\/About.aspx\"<\/span>><\/span>About<\/<\/span>a<\/span>><\/<\/span>li<\/span>><\/span>\n <<\/span>li<\/span>><<\/span>a<\/span> runat<\/span>=\"server\"<\/span> href<\/span>=\"~\/Contact.aspx\"<\/span>><\/span>Contact<\/<\/span>a<\/span>><\/<\/span>li<\/span>><\/span>\n <\/<\/span>ul<\/span>><\/span>\n <\/<\/span>aside<\/span>><\/span>\n<\/<\/span>asp:Content<\/span>><\/span>\n<\/pre>\n
Step 4. Writing code to translate user text<\/h3>\n
using<\/span> System;\nusing<\/span> System.Collections.Generic;\nusing<\/span> System.Linq;\nusing<\/span> System.Web;\n\nnamespace<\/span> Translator\n{\n public<\/span> class<\/span> AdmAccessToken\n {\n public<\/span> string<\/span> access_token { get; set; }\n public<\/span> string<\/span> token_type { get; set; }\n public<\/span> string<\/span> expires_in { get; set; }\n public<\/span> string<\/span> scope { get; set; }\n }\n}\n<\/pre>\n
using<\/span> System;\nusing<\/span> System.Collections.Generic;\nusing<\/span> System.Linq;\nusing<\/span> System.Web;\nusing<\/span> System.Web.UI;\nusing<\/span> System.Web.UI.WebControls;\nusing<\/span> System.Xml.Linq;\n\nnamespace<\/span> Translator\n{\n public<\/span> partial<\/span> class<\/span> About : Page\n {\n protected<\/span> void<\/span> Page_Load(object<\/span> sender, EventArgs e)\n {\n\n }\n\n protected<\/span> void<\/span> Button1_Click(object<\/span> sender, EventArgs e)\n {\n\n }\n }\n}\n<\/pre>\n
string<\/span> clientID = \"<Your ClientID>\"<\/span>;\nstring<\/span> clientSecret = \"<Your Client Secret>\"<\/span>;\nString strTranslatorAccessURI = \n \"https:\/\/datamarket.accesscontrol.windows.net\/v2\/OAuth2-13\"<\/span>;\nString strRequestDetails = \n string<\/span>.Format(\"grant_type=client_credentials&client_id={0}&client_secret={1} &scope=http:\/\/api.microsofttranslator.com\"<\/span>, HttpUtility.UrlEncode(clientID), \n HttpUtility.UrlEncode(clientSecret));\n\nSystem.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);\nwebRequest.ContentType = \"application\/x-www-form-urlencoded\"<\/span>;\nwebRequest.Method = \"POST\"<\/span>;\nbyte<\/span>[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);\nwebRequest.ContentLength = bytes.Length;\nusing<\/span> (System.IO.Stream outputStream = webRequest.GetRequestStream())\n{\n outputStream.Write(bytes, 0, bytes.Length);\n}\n\nSystem.Net.WebResponse webResponse = webRequest.GetResponse();\nSystem.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new<\/span> \n System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof<\/span>(AdmAccessToken));\n\nAdmAccessToken token = \n (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());\n\nstring<\/span> headerValue = \"Bearer \"<\/span> + token.access_token;\n<\/pre>\n
string<\/span> txtToTranslate = TextBox1.Text;\nstring<\/span> uri = \"http:\/\/api.microsofttranslator.com\/v2\/Http.svc\/Translate?text=\"<\/span> + \n System.Web.HttpUtility.UrlEncode(txtToTranslate) + \"&from=en&to=es\"<\/span>;\nSystem.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);\ntranslationWebRequest.Headers.Add(\"Authorization\"<\/span>, headerValue);\n\nSystem.Net.WebResponse response = null<\/span>;\nresponse = translationWebRequest.GetResponse();\nSystem.IO.Stream stream = response.GetResponseStream();\nSystem.Text.Encoding encode = System.Text.Encoding.GetEncoding(\"utf-8\"<\/span>);\n\nSystem.IO.StreamReader translatedStream = new<\/span> System.IO.StreamReader(stream, encode);\nSystem.Xml.XmlDocument xTranslation = new<\/span> System.Xml.XmlDocument();\nxTranslation.LoadXml(translatedStream.ReadToEnd());\n\nLiteral1.Text = xTranslation.InnerText;\n<\/pre>\n