Using the HTTP GET service to integrate Microsoft Translator services in application

Source: Internet
Author: User

I. Creating a Project

First, let's create an ASP. Application

Choose the most stylish and fashionable MVC, in order to make the demo more simple, here choose No authentication

Two. Creating related classes

The project needs to introduce the previous two classes Admaccesstoken and admauthentication in order to get access tokens and add a controller named translator to facilitate the handling of related business

Note You need to add an assembly System.Runtime.Serialization

Add a Language_codes

public class Language_codes    {public        int Id {get; set;}        public string code {get; set;}        public string Name {get; set;}    }

Three. Create a database context class

First we need to introduce the Entity Framework framework, where NuGet package management is used

Add the class codeentity and let it inherit DbContext

 Public codeentity ()             Base ("defaultconnection")        {        }        public dbset<language_codes> language_code{get;  Set;}
}

Next Modify Webconfig

< connectionStrings >    <  name= "DefaultConnection"  connectionString= "server=.; database=languagecode;uid=sa;pwd= "      providerName=" System.Data.SqlClient "/ >  </connectionStrings>

Add in Translatorcontroller

Codeentity DbContext = new codeentity ();

So we can get the code for the language.

Four. Build the interface

1. Modify the Index method

 Public actionresult Index ()        {            List<Language_Codes> list=  dbcontext. Language_code.tolist ();             return View (list);        }

Add a view to the index of Translatorcontroller

@model ienumerable<translator.models.language_codes>@{Viewbag.title="Index";}<tableclass="Table table-striped"> <tr> <td> <label> text to translate </label> <textarea id="text" class="Form-control"Rows="5"></textarea> </td> <td>will be<SelectId=" from" class="Form-control"> <option value="1"> Please select </option>@foreach (varIteminchModel) {                    <option id="@item. Id"Value="@item. Code"> @item. Name</option>                }            </Select>translated into<SelectId=" to" class="Form-control"> <option value="1"> Please select </option> </Select> <button id="Submit" class="btn Btn-default"> Translation </button> </td> <td> <label> translated text </label> <text Area id="Transtext" class="Form-control"Rows="5"></textarea> </td> </tr> </table>
Add in layout.cshtml
1<divclass="navbar-collapse collapse">2<ulclass="nav Navbar-nav">3<li> @Html. ActionLink ("Home Page","Index","Home") </li>4<li> @Html. ActionLink ("about the"," About","Home") </li>5<li> @Html. ActionLink ("Contact Information"," Contact","Home") </li>6<li> @Html. ActionLink ("translation","Index","Translator") </li>7</ul>8</div>

The effect is as follows


Five. Dynamically loading data with Ajax

1. Load Languagecode
First, add a loadlanguagecode to the controller to handle the load language code request

 Public ActionResult loadlanguagecode (int  ID)        {            list<Language_Codes> list = DbContext. Language_code.where (c=>c.id!=Id). ToList ();             return Json (list);        }


Add a translator.js file to the Scripts folder and add a reference to the file in the view <script src= "~/scripts/translator.js" ></script>
To register an event with the first select, each time we go to the option to load the second select when the Select selection changes
document.getElementById ("from"). Onchange=function ()
{
var Selectedid = $ (": Selected", "#from"). attr ("id");
$.ajax (
{
URL: ".. /translator/loadlanguagecode ",
Type: "Post",
Data: {Id:selectedid},
Success:function (_jsondata)
{
$ (' #to '). empty ();
for (var i = 0; i < _jsondata.length; i++) {
$ (' #to '). Append ($ (' <option ' + ' id= ' + _jsondata[i]. Id + ' value= ' + _jsondata[i].code + ' > ' + _jsondata[i]. Name + ' </option> ');
}
}
})
}
2. Request a service from Microsoft
Adding Translate methods in Translatorcontroller
[HttpPost] PublicActionResult Translate (string  from,stringTo,stringtext) {Admauthentication adm=NewAdmauthentication ("Zuin","ursm3pji3fcha+70pljfrabht/y00f7vykdxlwlusmc="); //string text = TextBox1.Text; //string from = "Zh-chs";//"Zh-chs"//string to = "en";            stringURI ="http://api.microsofttranslator.com/v2/Http.svc/Translate?text="+ System.Web.HttpUtility.UrlEncode (text) +"&from="+ from+"&to="+to ; stringAuthToken ="Bearer"+" "+Adm.token.access_token; HttpWebRequest HttpWebRequest=(HttpWebRequest) webrequest.create (URI); HTTPWEBREQUEST.HEADERS.ADD ("Authorization", AuthToken); WebResponse response=NULL; Try{Response=HttpWebRequest.GetResponse (); using(Stream stream =Response. GetResponseStream ()) {System.Runtime.Serialization.DataContractSerializer DCs=NewSystem.Runtime.Serialization.DataContractSerializer (Type.GetType ("System.String")); stringTranslation = (string) DCs.                    ReadObject (stream); returnJson (translation); }            }            Catch            {                stringCode ="fail"; returnJson (code); }        }
Registering events for the "Translate" button
$ (' #submit '). Click (function ()    {        varFormvalue =$ ("#from"). Val (); varTovalue = $ ("#to"). Val (); varTextValue = $ ("#text"). Val (); $.ajax ({URL:".. /translator/translate ", type:"POST", data: {from:formvalue, To:tovalue, Text:textvalue}, Success:function(_jsondata) {$ (' #transtext '). empty (); if(_jsondata== ' fail ') {alert (Failed , contact your administrator or use Microsoft Bing online Translator "); }                    Else{document.getElementById ("Transtext"). InnerHTML =_jsondata; }                }            })    }    )

Okay, now we can use the service.

Because the business is very complex, even if the network is very good delay is very serious, need to optimize the



Using the HTTP GET service to integrate Microsoft Translator services in application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.