Very few people know that anyone can write code using our translation Api, and even fewer know about the interface available in the Bing Api. I’ll use the later for this next sample: an ASPX page that invokes the translation services, show the result and then invokes the Speech feature from the client (using Javascript).
Let’s start with the basics: the Bing Api offers tons of services, and anyone can use it - all you need to to is apply for an AppId. Follow the instructions at http://www.bing.com/developers/appids.aspx and you’ll get one immediately. Once you have your shiny new code, you can then start playing with the many (many) samples available at http://msdn.microsoft.com/en-us/library/dd251056.aspx. It’s a quite powerful Api, and it works really well.
For the sake of this project we’ll only use the Translate methods. There are three “flavors” of protocols available: JSON, XML and SOAP. the XML protocol is really simple: it’s basically a REST implementation that returns a Xml as response. As any REST interface, you can even invoke it from the browser. For example:
http://api.bing.net/xml.aspx?AppId=FD087E7F3CDFEC530B63A2AC2FEEC5846127DA39&Query=mais+um+exemplo+usando+a+interface+do+Bing&Sources=Translation&Version=2.2&Translation.SourceLanguage=pt&Translation.TargetLanguage=en
,returns
(This AppId is registered to H2KTech, so please get your own)
As you can see, the result is a very simple Xml that can be loaded and parsed very easily. MSDN has a pretty good example that I copied and modified for this sample application: http://msdn.microsoft.com/en-us/library/dd877832.aspx.
This application is also very simple, and I even kept the Javascript Speech interface code (I think it’s pretty neat that it runs totally asynchronously from the rest of the page). The code is available here: http://www.h2ktech.net/h2ktechsamples/TranslateUsingBingSpeechSample.txt, and the application here: http://www.h2ktech.net/h2ktechsamples/TranslateUsingBingSpeechSample.aspx
Looking at the code you’ll notice that querying the translation services is really simple: just format the url string correctly and open an Http request:
protected void Button1_Click(object sender, EventArgs e)
{
// retrieve the basic parameters
string sourceText = TextBox1.Text;
string targetLang = DropDownList1.SelectedValue;
// Sample code from the Bing API documentation, with minor modifications
// see http://msdn.microsoft.com/en-us/library/dd877832.aspx
HttpWebRequest request = BuildRequest(sourceText, targetLang);
try
{
// Send the request; display the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
TextBox2.Text = DisplayResponse(response);
}
catch (WebException ex)
{
// An exception occurred while accessing the network.
TextBox2.Text = ex.Message;
}
}
static HttpWebRequest BuildRequest(string sourceText, string targetLang)
{
string requestString = "http://api.bing.net/xml.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=" + HttpUtility.UrlEncode(sourceText)
+ "&Sources=Translation"
// Common request fields (optional)
+ "&Version=2.2"
// SourceType-specific request fields (required)
+ "&Translation.SourceLanguage=en"
+ "&Translation.TargetLanguage=" + targetLang;
// Create and initialize the request.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
requestString);
return request;
}
The response comes in the form of a Xml formatted string, so it’s ready to be loaded into a XmlDocument object. After that, just add the namespace and you’re ready to parse it:
static string DisplayResponse(HttpWebResponse response)
{
// Load the response into an XmlDocument.
XmlDocument document = new XmlDocument();
document.Load(response.GetResponseStream());
// Add the default namespace to the namespace manager.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(
document.NameTable);
nsmgr.AddNamespace(
"api",
XmlNodeList errors = document.DocumentElement.SelectNodes(
"./api:Errors/api:Error",
nsmgr);
if (errors.Count > 0)
{
// There are errors in the response. Display error details.
return DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Translation results.
return DisplayResults(document.DocumentElement, nsmgr);
}
}
static string DisplayResults(XmlNode root, XmlNamespaceManager nsmgr)
{
string results = String.Empty;
string version = root.SelectSingleNode("./@Version", nsmgr).InnerText;
string searchTerms = root.SelectSingleNode(
"./api:Query/api:SearchTerms",
nsmgr).InnerText;
// Add the Translation SourceType namespace to the namespace manager.
nsmgr.AddNamespace(
"tra",
XmlNodeList nodes = root.SelectNodes(
"./tra:Translation/tra:Results/tra:TranslationResult",
nsmgr);
// Display the Translation results.
foreach (XmlNode result in nodes)
{
results = String.Concat(results, result.SelectSingleNode("./tra:TranslatedTerm",
nsmgr).InnerText);
}
return results;
}
Note that I’ve hooked the call to the Search Api to the OnClick handler, so the response will be blocked until we get a result back – and this is bad. However, for the sake of this exercise it doesn’t hurt much. Once we have the translation results, we populate the text box and return. The client Javascript code will then detect that the text box is not empty and invokes the Speech service using the Active X inside the IFrame, just like in the previous sample.
I didn’t add any checks for exceptions, so if the results text box is populated with an error message funny things will certainly happen :-).
Cheers,
Helvecio
English - Portuguese
Muito poucas pessoas sabem que qualquer um pode escrever código usando nossa API detradução, e ainda menos sabem sobre a interface disponível na API de Bing. Usarei esta para meu próximo exemplo: uma página ASPX que invoca os serviços de tradução, mostra o resultado e, em seguida, chama o recurso de voz a partir do cliente (usando JavaScript).
Vamos começar com os princípios básicos: a API de Bing oferece toneladas de serviços e qualquer pessoa pode usá-los - tudo o que você precisa é obter um AppId. Siga as instruções em http://www.bing.com/Developers/APPIDs.aspx e você obterá um imediatamente. Depois de ter seu novo código, você pode então começar a brincar com os varios (muitos) exemplos disponíveis em http://MSDN.Microsoft.com/en-US/Library/dd251056.aspx. É uma API bastante poderosa e funciona muito bem.
Para este projeto só vamos usar os métodos de traduzir. Existem três "flavors" de protocolos disponíveis: JSON, XML e SOAP. O protocolo XML é realmente simples: é basicamente uma implementação de REST que retorna um XML como resposta. Como qualquer interface REST, você pode até mesmo invocá-lo do navegador. Por exemplo:
http://API.bing.NET/XML.aspx?AppId=FD087E7F3CDFEC530B63A2AC2FEEC5846127DA39
, retorna
(Este AppId está registrado para H2KTech, então, por favor obtenha seu próprio)
Como você pode ver, o resultado é um XML muito simples que pode ser carregado e analisado muito facilmente. MSDN tem um exemplo muito bom que eu copei e modifiquei para este aplicativo: http://MSDN.Microsoft.com/en-US/Library/dd877832.aspx.
Esse aplicativo também é muito simples e eu até manti o código da interface de Speech em JavaScript (achoque é bastante elegante que ele seja executado totalmente assincronamente do resto da página). O código está disponível aqui: http://www.h2ktech.NET/h2ktechsamples/TranslateUsingBingSpeechSample.txt e a aplicação aqui: http://www.h2ktech.NET/h2ktechsamples/TranslateUsingBingSpeechSample.aspx
Olhando o código, você notará que ao consultar os serviços de tradução é realmente facil: basta formatar a cadeia de caracteres de url corretamente e abrir uma solicitação de http.
A resposta vem na forma de uma string formatada como XML, portanto está pronto para ser carregado em um objeto XmlDocument. Após isso, basta adicionar o namespace e você está pronto para analisá-lo.
Observe que eu já implementei a chamada para a API no handler de OnClick, portanto, a resposta será bloqueada até obtermos a um resultado de volta – e isso é ruim. No entanto, por razões deste exercício não importa tanto. Assim que tivermos os resultados de tradução, nós preenchemos a caixa de texto e retornamos. O código JavaScript que roda no cliente irá detectar que a caixa de texto não está vazia e invoca o serviço de voz usando o Active X dentro do IFrame, tal como no exemplo anterior.
Não adicionei testes para exceções, portanto, se a caixa de texto de resultados for preenchida com uma mensagem de erro coisas engraçadas certamente irão acontecer:-).
[]s,
Helvecio