This walk through gives step by step instructions on how to create a class library to access Google Translation service.
In this walk through you will complete the following tasks:
We are now done with the basics.
Lets now start with the real translation work.
Currently, Google is publishing its translation API using a translation web service.
Here is the URL for the web service.
https://www.googleapis.com/language/translate/v2
More information can be found at this URL:
https://cloud.google.com/translate/docs/translating-text
In order for this URL to work, a few query string parameters need to be supplied:
key : In order to access the REST service the user needs to register with Google API cloud service. Once the registration is done, the user needs to enable the translation API. After enabling the translation API Google provides the user with an API key. The API key obtained needs to be sent as a query string parameter.
source: The source language of the text (Example: en, fr, de and so on)
target: The target language - language in which the source text needs to be translated
q: The text that needs to be translated. The query string value with parameter name 'q' will be translated and the translated value will be sent as part of the response.
Example URL with query string:
https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY&source=en&target=de&q=Hello%20world
YOUR_API_KEY in the above URL refers to API key obtained by the user after registering to the cloud service and enabling the translation API.
Lets start using this service Url in our code:
Now lets start the real coding part.
The response is sent in the following JSON format:
Lets add a reference to NewtonSoft Json library
Newtonsoft Json library can be added to the solution using Nuget package manager.
In Visual Studio, under Tools -> Library package manager select "Manage NuGet packages for solution".
In the package manager window, search for newtonsoft json.
Install the Json.NET library from search results.
Once a reference to NewtonSoft library is added, use "JsonTextReader" object from the library and read the property with key "translatedText".
"JsonTextReader" takes StreamReader as a parameter. So lets create a StreamReader out of the response object.
Return the string value once the property is found.
In Solution explorer window, right click on the "GoogleTranslationLibrary" projetc and select "Build" option. The build option compiles the application and generates a dll file.
Testing the library:
In this walk through you will complete the following tasks:
- Creation of Class Library project
- Add code to access Google Translation service
- Build the project and create a dll
- Test the dll created
- Open Visual Studio
- Create a new project
- In the "New Project" window select "Class Library" template
- For this project name the library as "GoogleTranslationLibrary"
- Under location field, key in a location where you would like to save the project.
- Checking the box "Create directory for solution" creates a folder for the solution within the selected location.
- By default Visual Studio assumes the same name as Project name for solution. Lets leave as it is for this project.
New project window |
- Once the settings are done, you should see something like this in Solution Explorer window of Visual Studio:
Solution explorer |
- Visual Studio creates a solution with one project "GoogleTranslationLibrary" within it.
- Within the project a new class "Class1" is created. Rename the class "Class1.cs" to "Translator.cs". You should now see something similar in the "Translator.cs" code file.
Editor should look similar to this image |
Lets now start with the real translation work.
Currently, Google is publishing its translation API using a translation web service.
Here is the URL for the web service.
https://www.googleapis.com/language/translate/v2
More information can be found at this URL:
https://cloud.google.com/translate/docs/translating-text
In order for this URL to work, a few query string parameters need to be supplied:
key : In order to access the REST service the user needs to register with Google API cloud service. Once the registration is done, the user needs to enable the translation API. After enabling the translation API Google provides the user with an API key. The API key obtained needs to be sent as a query string parameter.
source: The source language of the text (Example: en, fr, de and so on)
target: The target language - language in which the source text needs to be translated
q: The text that needs to be translated. The query string value with parameter name 'q' will be translated and the translated value will be sent as part of the response.
Example URL with query string:
https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY&source=en&target=de&q=Hello%20world
YOUR_API_KEY in the above URL refers to API key obtained by the user after registering to the cloud service and enabling the translation API.
Lets start using this service Url in our code:
- Add a new method that does the translation.
public void Translate()
{
}
- Add necessary values as parameters to the method so that the values can be passed to the library from calling application.
public void Translate(string key, string sourceText, string sourceLanguage, string targetLanguage)
{
}
- Since the calling application needs translated value as a response add string as a return type.
public string Translate(string key, string sourceText, string sourceLanguage, string targetLanguage)
{
}
This completes the method signature.Now lets start the real coding part.
- Create a string variable and add the Url as a base url.
string baseUrl = "https://www.googleapis.com/language/translate/v2?";
- Create a HttpWebRequest to the Url.
HttpWebRequest request = WebRequest.Create(baseUrl+ string.Format("key={0}& q={1}&source={2}&target={3}",
new object[] { key, sourceText, sourceLanguage, targetLanguage })) as HttpWebRequest;
- HttpWebRequest is present inside System.Net namespace. So add System.Net to the list of namespaces.
Editor should look similar to this image |
- Set the request method to "GET"
request.Method = "GET";
Now its time to get the response.- Call GetResponse method on the request object and assign it to a new HttpResponse object.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
- The response object will have a status code associated with it. The status code specifies the status of response. It denotes if the request to the translation service succeeded or resulted in a failure.
if (response.StatusCode == HttpStatusCode.OK)
{
}
If the status code is OK, we proceed and read the response.The response is sent in the following JSON format:
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt"
}
]
}
}
Since the response contains JSON string we need a way to read JSON. For this example, I used Newtonsoft Json library. Newtonsoft Json library is a free and a very popular library for processing Json.Lets add a reference to NewtonSoft Json library
Newtonsoft Json library can be added to the solution using Nuget package manager.
In Visual Studio, under Tools -> Library package manager select "Manage NuGet packages for solution".
Open NuGet package manager |
Install the Json.NET library from search results.
Search for newtonsoft json library in package manager window |
"JsonTextReader" takes StreamReader as a parameter. So lets create a StreamReader out of the response object.
JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream()));
Just to make sure that the reader object is disposed off correctly lets wrap the above statement in a using construct. using (JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream())))
{
}
Now lets loop through the reader object recursively and find the property with key "translatedText".Return the string value once the property is found.
while (reader.Read())
{
if ((reader.TokenType == JsonToken.PropertyName) && (reader.Value.ToString() == "translatedText"))
{
return reader.ReadAsString();
}
}
Here is the final code:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace GoogleTranslationLibrary
{
public class Translator
{
public string Translate(string key, string sourceText, string sourceLanguage, string targetLanguage)
{
string baseUrl = "https://www.googleapis.com/language/translate/v2?";
string responseText = string.Empty;
try
{
//Call format for the translation API
//https://www.googleapis.com/language/translate/v2?key={INSERT-YOUR-KEY}&q=hello%20world&source=en&target=de
HttpWebRequest request = WebRequest.Create(baseUrl + string.Format("key={0}&q={1}&source={2}&target={3}", new object[] { key, sourceText, sourceLanguage, targetLanguage })) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
using (JsonTextReader reader = new JsonTextReader(new StreamReader(response.GetResponseStream())))
{
while (reader.Read())
{
if ((reader.TokenType == JsonToken.PropertyName) && (reader.Value.ToString() == "translatedText"))
{
return reader.ReadAsString();
}
}
}
return sourceText;
}
return ("Failed with " + response.StatusCode);
}
catch (Exception ex)
{
}
return responseText;
}
}
}
Build the project:In Solution explorer window, right click on the "GoogleTranslationLibrary" projetc and select "Build" option. The build option compiles the application and generates a dll file.
Build project from Solution explorer window |
Lets now create a console application in order to test the GoogleTranslationLibrary.
Right click on the Solution Explorer window and select Add->New Project.
In the "Add new project" window select Console Application.
Add new project window |
Now lets add a reference to the dll created in "GoogleTranslationLibrary" project.
Right click on the References node of the project explorer window and select the option "Add Reference".
In the Add reference window under Solution tab, select Projects. You should see the library GoogleTranslationLibrary listed.
Select "GoogleTranslationLibrary" and press "OK".
A reference to the "GoogleTranslationLibrary" dll is added to the project "GoogleTranslationLibraryTestProject".
Lets add the following few lines of code inside the "Main" method:
For the above code to work, you need to register for Google Translation API and obtain a key. The procedure to obtain the API key is explained in another post.
Right click on the References node of the project explorer window and select the option "Add Reference".
Add reference to dll |
In the Add reference window under Solution tab, select Projects. You should see the library GoogleTranslationLibrary listed.
Add solution reference |
Select "GoogleTranslationLibrary" and press "OK".
A reference to the "GoogleTranslationLibrary" dll is added to the project "GoogleTranslationLibraryTestProject".
A reference to GoogleTranslationLibrary dll is added |
Lets add the following few lines of code inside the "Main" method:
Translator translator = new Translator();
string translatedString = string.Empty;
translatedString = translator.Translate("YOUR-API-KEY", "Hello world", "en", "fr");
Console.WriteLine(translatedString);
Console.Read();
Running the project should give the following output:
Translation output |
For the above code to work, you need to register for Google Translation API and obtain a key. The procedure to obtain the API key is explained in another post.
Excellent beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog website? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept
ReplyDeleteInteresting and impressive information, definitely will be helpful for those who are looking for Legal Translation Dubai and related services.
ReplyDelete