Monday, October 7, 2013

SOAP Interface

http://msdn.microsoft.com/en-us/library/ff512390.aspx

Using the SOAP Interface

The SOAP interface supports client application scenarios and a rich .NET service client programming model. Developers can use their development technology of choice with this interface.
To start using the SOAP interface for the Microsoft Translator service you need SOAP web service reference
To add reference to SOAP web service, right-click on the Visual Studio 2010 project and click on Add Service Reference... Then provide address as http://api.microsofttranslator.com/V2/Soap.svc and click Go. Once service information is downloaded, provide Namespace as "TranslatorService" and click Ok.

Add Service Reference
This will generate the proxy code in a LanguageServiceClient class in the project. In order to call the SOAP web service in the C# code, an instance of the LanguageServiceClient class is required. This instance is created using a static constructor
                                
TranslatorService.LanguageServiceClient client = new TranslatorService.LanguageServiceClient();
                            

Authorization Header

To make request to any method of Microsoft translator you will need access token. Process of obtaining access token is explained in detailed at Obtain Access Token. Use the value of access token in the Authorization header of the subsequent calls to the Microsoft Translator API. This Token is valid for 10 minutes.
Authorization header value should be in following format. (Note: One BLANK space between Bearer and Access Token Value)
"Bearer" + " " + Access Token Value
To send this authorization header as a part of SOAP request, define a variable of type HttpRequestMessageProperty.
                                
HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                            
Now to call Translate method, we have to provide all required parameters. appId is required parameter but as we are using Authorization header leave appId parameter blank.
Code block below ensures that Authorization header added to the SOAP request.
                                
// Creates a block within which an OperationContext object is in scope.
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
    string sourceText = "Use pixels to express measurements for padding and margins.";
    string translationResult;
    //Keep appId parameter blank as we are sending access token in authorization header.
    translationResult = client.Translate("", sourceText, "en", "de", "text/plain", "");
    Console.WriteLine("Translation for source {0} from {1} to {2} is", sourceText,"en","de");
    Console.WriteLine(translationResult);
}

No comments :

Post a Comment