Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8190847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T03:46:13+00:00 2026-06-07T03:46:13+00:00

I’m attempting to translate some English text to Chinese using Bing Translate’s API. My

  • 0

I’m attempting to translate some English text to Chinese using Bing Translate’s API.

My code is essentially what was provided on MSDN, albeit with a few modifications.

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace AutoTranslate2
{
    public class Translator
    {
        private string authToken;

        public Translator(string clientId, string clientSecret)
        {
            AdmAccessToken admToken;

            AdmAuthentication admAuth = new AdmAuthentication("clientId", "client secret");

            admToken = admAuth.GetAccessToken();
            DateTime tokenReceived = DateTime.Now;
            this.authToken = "Bearer " + admToken.access_token;
        }

        public string TranslateMethod(
            string text,
            string inputLang = "en",
            string outputLang = "zh-CHS", // Chinese, simplified ('zh-CHT' is traditional Chinese)
            string inputType = "text/html",
            string outputType = "general")
        {
            // Add TranslatorService as a service reference, Address:http://api.microsofttranslator.com/V2/Soap.svc
            TranslatorService.LanguageServiceClient client = new TranslatorService.LanguageServiceClient();
            //Set Authorization header before sending the request
            HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
            httpRequestProperty.Method = "POST";
            httpRequestProperty.Headers.Add("Authorization", this.authToken);

            // Creates a block within which an OperationContext object is in scope.
            string translationResult;
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
                //Keep appId parameter blank as we are sending access token in authorization header.
                translationResult = client.Translate("", "<p>" + text + "</p>", inputLang, outputLang, inputType, outputType);
            }
            return translationResult;
        }
    }

    [DataContract]
    public class AdmAccessToken
    {
        [DataMember]
        public string access_token { get; set; }
        [DataMember]
        public string token_type { get; set; }
        [DataMember]
        public string expires_in { get; set; }
        [DataMember]
        public string scope { get; set; }
    }

    public class AdmAuthentication
    {
        public static readonly string DatamarketAccessUri = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
        private string clientId;
        private string clientSecret;
        private string request;

        public AdmAuthentication(string clientId, string clientSecret)
        {
            this.clientId = clientId;
            this.clientSecret = clientSecret;
            //If clientid or client secret has special characters, encode before sending request
            this.request = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));
        }

        public AdmAccessToken GetAccessToken()
        {
            return HttpPost(DatamarketAccessUri, this.request);
        }

        private AdmAccessToken HttpPost(string DatamarketAccessUri, string requestDetails)
        {
            //Prepare OAuth request 
            WebRequest webRequest = WebRequest.Create(DatamarketAccessUri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
            webRequest.ContentLength = bytes.Length;
            using (Stream outputStream = webRequest.GetRequestStream())
            {
                outputStream.Write(bytes, 0, bytes.Length);
            }
            WebResponse webResponse = webRequest.GetResponse();
            using (webResponse)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AdmAccessToken));
                //Get deserialized object from JSON stream
                AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
                return token;
            }
        }
    }
}

…and somewhere else in my code, I do…

Translator t = new Translator(client_id, secret);
string output = t.TranslateMethod(text);

However, the code always returns an exception:

Unhandled Exception: System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at System.Net.HttpWebRequest.GetResponse()
   at AutoTranslate2.AdmAuthentication.HttpPost(String DatamarketAccessUri, String requestDetails) in C:\Users\Deflect\AutoTranslate2\AutoTranslate2\Translate.cs:line 102
   at AutoTranslate2.AdmAuthentication.GetAccessToken() in C:\Users\Deflect\AutoTranslate2\AutoTranslate2\Translate.cs:line 87
   at AutoTranslate2.Translator..ctor(String clientId, String clientSecret) in C:\Users\Deflect\AutoTranslate2\AutoTranslate2\Translate.cs:line 26
   at AutoTranslate2.Chinese.Parse(String rawText) in C:\Users\Deflect\AutoTranslate2\AutoTranslate2\Parse.cs:line 68
   at AutoTranslate2.Program.Main(String[] args) in C:\Users\Deflect\AutoTranslate2\AutoTranslate2\Program.cs:line 19

I’ll be the first to admit I really don’t know what my code is doing, since I mostly copied and pasted from MSDN — does anybody know why my code is returning an exception, and how I can get it to work?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T03:46:14+00:00Added an answer on June 7, 2026 at 3:46 am

    It was this line:

    AdmAuthentication admAuth = new AdmAuthentication("clientId", "client secret"); 
    

    I forgot to swap the strings in the examples with the actual variables.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am using the SimpleRSS gem to parse a WordPress RSS feed. The only
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.