locked
Accessing the Microsoft Translator API from VB.NET RRS feed

  • General discussion

  • Some folks have been asking about how to access the translator using VB.NET. Here's a simple, synchronous example that gets the token from Windows Azure, and uses it to get a translation from translator, using VB.NET.

    Namespace LMVBTrans
        Public Class _Default
            Inherits System.Web.UI.Page

            Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            End Sub

            Protected Sub DoClick(sender As Object, e As EventArgs) Handles Button1.Click
                Dim clientID As String = "Your Client ID"
                Dim clientSecret As String = "Your Secret"
                Dim strTranslatorAccessURI As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
                Dim strRequestDetails As String = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret))


                Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(strTranslatorAccessURI)
                webRequest.ContentType = "application/x-www-form-urlencoded"
                webRequest.Method = "POST"
                Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(strRequestDetails)
                webRequest.ContentLength = bytes.Length


                Using outputStream As System.IO.Stream = webRequest.GetRequestStream()
                    outputStream.Write(bytes, 0, bytes.Length)
                End Using
                Dim webResponse As System.Net.WebResponse = webRequest.GetResponse()
                ' Make sure you add a reference to System.Runtime.Serialization here
                Dim AdmToken As New AdmAccessToken
                Dim serializer As System.Runtime.Serialization.Json.DataContractJsonSerializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(AdmToken.GetType())
                Dim token As AdmAccessToken = serializer.ReadObject(webResponse.GetResponseStream())
                Dim txtToTranslate As String = TextBox1.Text
                Dim headerValue As String = "Bearer " + token.access_token
                Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"

                Dim translationWebRequest As System.Net.WebRequest = System.Net.WebRequest.Create(uri)
                translationWebRequest.Headers.Add("Authorization", headerValue)
                Dim response As System.Net.WebResponse = Nothing
                response = translationWebRequest.GetResponse()
                Dim stream As System.IO.Stream = response.GetResponseStream()
                Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding("utf-8")
                Dim translatedStream As System.IO.StreamReader = New System.IO.StreamReader(stream, encode)
                ' Be sure to add references to System.Xml and System.Xml.Linq
                Dim xTranslation As System.Xml.XmlDocument = New System.Xml.XmlDocument()
                xTranslation.LoadXml(translatedStream.ReadToEnd())

                lbl1.Text = "Your Translation is: " + xTranslation.InnerText
            End Sub
        End Class
        Public Class AdmAccessToken

            Property access_token As String = ""
            Property token_type As String = ""
            Property expires_in As String = ""
            Property scope As String = ""

        End Class
    End Namespace

    And here is the ASPX markup if you need it:

    [NOTE THE USE OF THE NAMESPACE IN THE INHERITS ATTRIBUTE!]

    <%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
        CodeBehind="Default.aspx.vb" Inherits="VBTrans.LMVBTrans._Default" %>

    <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    </asp:Content>
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        <h2>My Spanish Translator</h2>
        <p>
            Enter your text in English:&nbsp; </p>
        <p>
            <asp:TextBox ID="TextBox1" runat="server" 
                Width="198px"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button"/>
        </p>
        <p>
            &nbsp;</p>
        <p>
            Here is your translation:</p>
        <p>
            <asp:Literal ID="lbl1" runat="server"></asp:Literal>
        </p>
    </asp:Content>


    //Laurence Moroney: www.netnavi.tv // Author of 'Introducing Silverlight' series and much more // @lmoroney


    Wednesday, April 25, 2012 1:40 AM

All replies

  • To access the service using SOAP, the code is almost identical.

    First, create a service reference to: http://api.microsofttranslator.com/V2/Soap.svc and make sure you call it 'TranslatorService'. Then, your code will look like this:

                Dim clientID As String = "Your ClientID"
                Dim clientSecret As String = "Your Secret"
                Dim strTranslatorAccessURI As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
                Dim strRequestDetails As String = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret))


                Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(strTranslatorAccessURI)
                webRequest.ContentType = "application/x-www-form-urlencoded"
                webRequest.Method = "POST"
                Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(strRequestDetails)
                webRequest.ContentLength = bytes.Length

                Using outputStream As System.IO.Stream = webRequest.GetRequestStream()
                    outputStream.Write(bytes, 0, bytes.Length)
                End Using
                Dim webResponse As System.Net.WebResponse = webRequest.GetResponse()
                ' Make sure you add a reference to System.Runtime.Serialization here
                Dim AdmToken As New AdmAccessToken
                Dim serializer As System.Runtime.Serialization.Json.DataContractJsonSerializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(AdmToken.GetType())
                Dim token As AdmAccessToken = serializer.ReadObject(webResponse.GetResponseStream())
                Dim txtToTranslate As String = TextBox1.Text
                Dim headerValue As String = "Bearer " + token.access_token

                ' Call the SOAP Service

                Dim soapClient As New TranslatorService.LanguageServiceClient()
                Dim translatedText As String = soapClient.Translate(headerValue, txtToTranslate, "en", "es", "text/plain", "")
                lbl1.Text = translatedText

    Laurence


    //Laurence Moroney: www.netnavi.tv // Author of 'Introducing Silverlight' series and much more // @lmoroney

    Wednesday, April 25, 2012 2:22 PM
  • This code does not work in VS 2005 mainly because I do not know how to name the com.microsoft.api to TranslatorService.

    I ran the following code:

            ' Call the SOAP Service
            Dim soapClient As New com.microsofttranslator.api.SoapService
            'Dim soapClient As New TranslatorService.LanguageServiceClient()
            Dim translatedText As String = soapClient.Translate(headerValue, txtToTranslate, "en", "es", "text/plain", "")
            txtRisk2.Text = "Your Translation is: " + translatedText

    I get "No bearer information found in the token: ID=3743.V2_Soap.Translate.242FACD0

    Any Suggestions?

    Saturday, July 14, 2012 4:23 AM
  • That error indicates that the code to get the access token from ADM isn't working for you. The JSON deserializer stuff isn't supported in 2005 AFAIK, so check the code for what you did there?
    Thursday, July 19, 2012 5:19 PM
  • Hi,

    This might sound a little out of context. But i'm new to C# and new to Visual Studio. I have to develop an app for Windows Surface RT. I am able to start off with the VS2012 and create a Tiled App. I want to use the Microsoft Translator in my app. So when I click a tile or a button, It should speak whatever that button corresponds to or whatever I type in a text box.

    Could you please guide me to the right place where I can find some help to start off from scratch. I have tried multiple threads like the following :

    microsoft Speech-Synthesis

    translatorservice at codeplex

    But i'm getting stuck at one place or another. If you could let me know a getting started guide which could run me through the basics, I'd be grateful.

    OR if you want me to let you know the exact issue i'm facing. I'd be glad to provide my code and the issue both.

    Thanks

    Thursday, February 28, 2013 9:50 AM
  • None to offer some guidance???
    Sunday, March 10, 2013 12:02 AM
  • Hi All

    I checked all my settings but I still keep getting the error:

    "there was no endpoint listening at http://api.microsofttranslator.com/V2/soap.svc.............................

    My app.config file looks like

    <system.serviceModel>
        <bindings>
          <basicHttpBinding>
            <binding name="BasicHttpBinding_LanguageService" />
          </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://api.microsofttranslator.com/V2/soap.svc"
            binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_LanguageService"
            contract="TranslatorService.LanguageService" name="BasicHttpBinding_LanguageService" />
        </client>
      </system.serviceModel>

    the configurantion.svcinfo file looks like

    <?xml version="1.0" encoding="utf-8"?>
    <configurationSnapshot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:schemas-microsoft-com:xml-wcfconfigurationsnapshot">
      <behaviors />
      <bindings>
        <binding digest="System.ServiceModel.Configuration.BasicHttpBindingElement, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089:&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;&lt;Data name=&quot;BasicHttpBinding_LanguageService&quot; /&gt;" bindingType="basicHttpBinding" name="BasicHttpBinding_LanguageService" />
      </bindings>
      <endpoints>
        <endpoint normalizedDigest="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;&lt;Data address=&quot;http://api.microsofttranslator.com/V2/soap.svc&quot; binding=&quot;basicHttpBinding&quot; bindingConfiguration=&quot;BasicHttpBinding_LanguageService&quot; contract=&quot;TranslatorService.LanguageService&quot; name=&quot;BasicHttpBinding_LanguageService&quot; /&gt;" digest="&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-16&quot;?&gt;&lt;Data address=&quot;http://api.microsofttranslator.com/V2/soap.svc&quot; binding=&quot;basicHttpBinding&quot; bindingConfiguration=&quot;BasicHttpBinding_LanguageService&quot; contract=&quot;TranslatorService.LanguageService&quot; name=&quot;BasicHttpBinding_LanguageService&quot; /&gt;" contractName="TranslatorService.LanguageService" name="BasicHttpBinding_LanguageService" />
      </endpoints>
    </configurationSnapshot>

    and I call the translator service with

    Try
                    Dim strTranslatedText As String = _
                                client.Translate(translatorkey, _
                                                 "This is a test", _
                                                 "en", lblLanguageShort.Text, "text/plain", "general")

                    MessageBox.Show("English Text:" & vbCrLf & vbCrLf _
                                    & "'This is a test'" & vbCrLf & vbCrLf _
                                    & "Successfully translated to:" & vbCrLf & vbCrLf _
                                    & boxLanguage.Text & vbCrLf & vbCrLf _
                                    & strTranslatedText, "Successful Translation", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Catch ex As Exception

                    MessageBox.Show("English Text:" & vbCrLf & vbCrLf _
                                    & "'This is a test'" & vbCrLf & vbCrLf _
                                    & "Unsuccessfully translated!" & vbCrLf & vbCrLf _
                                    & "Error:" & vbCrLf & vbCrLf _
                                    & ex.ToString, "Unsuccessful Translation", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try

    All this results in "Unsuccessful Translation" with the returned error text

    Could somebody please help, I don't know anymore

    Ton


    Friday, August 15, 2014 1:39 PM