How to use the Microsoft Translator API over Windows Azure, for Windows Phone?

心不动则不痛 提交于 2019-12-04 14:46:19

With help from Bing Translator team I got it working in my Silverlight Application:

  1. UseDefaultCredentials needs to be turned off on the proxy

  2. On the async callback, you were casting the result to a DSQ, but it’s the result’s AsyncState that needs to be casted. See below.

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var serviceUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");
        var accountKey = "**********************"; // 
        var tcode = new Microsoft.TranslatorContainer(serviceUri);
    
        tcode.Credentials = new NetworkCredential(accountKey, accountKey);
        tcode.UseDefaultCredentials = false;
        var query = tcode.GetLanguagesForTranslation();
        query.BeginExecute(OnQueryComplete, query);
    }
    
    public void OnQueryComplete(IAsyncResult result)
    {
        var query = (DataServiceQuery<Microsoft.Language>)result.AsyncState;
        var enumerableLanguages = query.EndExecute(result);
        string langstring = "";
        foreach (Microsoft.Language lang in enumerableLanguages)
        {
            langstring += lang.Code + "\n";
        }
        MessageBox.Show(langstring);
    }
    

This way you can use BeginExecute() and BeginEnd() to get Async results.

I had exact same problem and I was suggested that the issue may be related with the how the Async results are return internally when calling GetLanguagesForTranslation, however I did not dig further and just used Execute() to get the list of Language as below:

var serviceUri = new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/");
var accountKey = "***********************"; // 
var tcode = new TranslatorContainer(serviceUri);
tcode.Credentials = new NetworkCredential(accountKey, accountKey);
var languages = tcode.GetLanguagesForTranslation().Execute().ToArray(); 
foreach (var i in languages)
{
    Console.WriteLine(i.Code);
}

Not sure if that is what you are looking for but it worked in my case well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!