Integration of Microsoft Translator Services optimization in application

Source: Internet
Author: User

In one article we have implemented functionality, but one obvious problem is that the response time is very long and the user experience is very bad, and this article will take you through the problem and optimize it.

To find the culprit, use System.Diagnostics.Stopwatch to clock our application execution.

Modify the code in translate in Translatorcontroller

System.Diagnostics.Stopwatch Watch1 =NewSystem.Diagnostics.Stopwatch (); System.Diagnostics.Stopwatch WATCH2=NewSystem.Diagnostics.Stopwatch (); Watch1.            Start (); Admauthentication ADM=NewAdmauthentication ("Zuin","ursm3pji3fcha+70pljfrabht/y00f7vykdxlwlusmc="); Watch1.            Stop (); Watch2.            Start (); 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); Watch2.                    Stop (); returnJson (translation+"the time to get the token is"+watch1. Elapsed.tostring () +"the time to get the translation is"+WATCH2.                Elapsed.tostring ()); }            }            Catch{watch2.                Stop (); stringCode ="fail"; returnJson (code); }

Let's take a look at the effect

It can be seen from the above data that the time to get the translation is very short, generally not more than half a minute, and the time to get the token is very long and unstable, this is the key to optimization

I. Using cookies and session to save tokens

Here's an example of a cookie.

    stringAccess_token =""; if( This. httpcontext.request.cookies["AuthToken"]==NULL) {Admauthentication adm=NewAdmauthentication ("Zuin","ursm3pji3fcha+70pljfrabht/y00f7vykdxlwlusmc="); Access_token=Adm.token.access_token; HttpCookie Cookies=NewHttpCookie ("AuthToken"); Cookies. Value=Adm.token.access_token; Cookies. Expires= DateTime.Now.AddMinutes (9);            RESPONSE.COOKIES.ADD (cookie); }            Else{Access_token= This. httpcontext.request.cookies["AuthToken"].            ToString (); } stringAuthToken ="Bearer"+" "+ Access_token;

Look at the effect.

Cookies can be used for our purposes without having to obtain tokens every time, can be obtained directly in the cookie, the token is valid within 10 minutes, so there is no need to consider security issues. The impact on bandwidth is also not very large.

Two. Use httpruntime to cache tokens

The data of the cookie and session are used by individual users, and the data should be shared, and the httpruntime to solve this problem, first modify the code,

String access_token = "";            if (this. httpcontext.cache["AuthToken"]==null)            {                Admauthentication adm = new Admauthentication ("Zuin", " Ursm3pji3fcha+70pljfrabht/y00f7vykdxlwlusmc= ");                Access_token = Adm.token.access_token;                This. HttpContext.Cache.Insert ("AuthToken", Access_token, NULL, DateTime.Now.AddMinutes (9), TimeSpan.Zero);            }            else            {                Access_token = this. httpcontext.cache["AuthToken"]. ToString ();            }

Before using the Edge browser, this time use the Firefox browser to see the effect

Apparently, it's our goal.

Note:

the Cache class cannot be used outside of an ASP. It is designed and tested to provide caching for WEB applications in ASP. In other types of applications, such as console applications or Windows forms applications, the ASP. NET cache may not work correctly. (from MSDN)

This cache can be accessed by our ASP. NET application and still cannot replace distributed caches such as memcached.

Three. Using memcached distributed Cache

First need to install memcached (http://memcached.org/) on the computer

Referencing Memcached.clientlibrary.dll,log4net.dll,icsharpcode.sharpziplib.dll,commons.dll four assemblies in a project

Package the control memcached.

 Public classMmhelper {Privatememcachedclient Client;  PublicMmhelper () {string[] ips = system.configuration.configurationmanager.appsettings["memcachedservers"]. Split (','); Sockiopool Pool=sockiopool.getinstance (); Pool.            Setservers (IPS); Pool.            Initialize (); Client=Newmemcachedclient (); Client. EnableCompression=true; }         Public BOOLSet (stringKeyObjectvalue, DateTime expirytime) {            returnclient.        Set (key, value, Expirytime); }         Public ObjectGet (stringkey) {            returnclient.        Get (key); }         Public BOOLDelete (stringkey) {            returnclient.        Delete (key); }    }

Modify the previous Code

Mmhelper mm =NewMmhelper (); if(MM. Get ("AuthToken")==NULL) {Admauthentication adm=NewAdmauthentication ("Zuin","ursm3pji3fcha+70pljfrabht/y00f7vykdxlwlusmc="); Access_token=Adm.token.access_token; Mm. Set ("AuthToken", Access_token, DateTime.Now.AddMinutes (9)); }            Else{Access_token= mm. Get ("AuthToken").            ToString (); }

Now look at the effect

Ok!

Integration of Microsoft Translator Services optimization 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.