none
Microsoft Translator API work using console, not working in MVC RRS feed

  • Question

  • I have been able to get the Microsoft Translator API to work with creating a console project.  I could only find examples with using console projects.

    1) Console working

    2) MVC controller executing the console project not working

    3) MVC controller using Microsoft Translator API not working.

    #2

    I created a console project within my solution. The console executable LanguageTranslation.exe is working great.

    Within the same solution I have an MVC project. I am calling the executable LanguageTranslation.exe within a controller.

    The executable is working up-to this method TranslateAsync(productNumber, divisionId, defaultCountryCode).Wait(); when calling the executable within the controller.

    What is causing this method not work within my MVC project?

    Console:

    static void Main(string[] args)
        {
            string productNumber = null;
            int divisionId = 0;
            string defaultCountryCode = null;
    
            if (args.Length > 0)
            {
                productNumber = args[0];
                divisionId = int.Parse(args[1]);
                defaultCountryCode = args[2];
            }
            else
            {
                productNumber = "111";
                divisionId = 19;
                defaultCountryCode = "USA";
            }
    
            File.WriteAllText("C:\\TEST\\Start.txt", productNumber.ToString());
    
            TranslateAsync(productNumber, divisionId, defaultCountryCode).Wait();
    
            File.WriteAllText("C:\\TEST\\End.txt", productNumber.ToString());
        }

    MVC Controller executing 

     private void TranslateLanguage(ProductTest productTest)
        {
            try
            {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = Server.MapPath("~/Executable_File/LanguageTranslation.exe");
    
                process.StartInfo.Arguments = productTest.Product_Number + ' ' + productTest.Division_Id + ' ' + productTest.Default_Country_Code;
                process.Start();
                process.Close();
            }
            catch(Exception ex)
            {
                ViewBag.Result = ex.Message;
            }
        }

    Error message

    #3

    Only using MVC controller

    Here's the logic that I tried to use within MVC to do the translation. The authTokenSource is causing an error message.

    private async Task TranslateAsync(ProductTest productTest, string getUserName)
        {
            var translatorService = new TranslatorService.LanguageServiceClient();
            var authTokenSource = new AzureAuthToken(SubscriptionKey);
            var token = string.Empty;
    
            try
            {
                token = await authTokenSource.GetAccessTokenAsync();
            }
            catch (HttpException)
            {
                string exMessage = null;
                switch (authTokenSource.RequestStatusCode)
                {
                    case HttpStatusCode.Unauthorized:
                        exMessage = "Request to token service is not authorized (401). Check that the Azure subscription key is valid.";
                        break;
                    case HttpStatusCode.Forbidden:
                        exMessage = "Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.";
                        break;
                }
                throw new Exception(exMessage);
            }
    
            var productCountries = from ptest in db.ProductTests
                                   where ptest.ProductDescriptionTests.Any(pt => pt.Product_Number == productTest.Product_Number && pt.Division_Id == productTest.Division_Id && pt.Country_Code == productTest.Default_Country_Code)
                                   select ptest;
    
            string productNumber = productTest.Product_Number;
            int divisionId = productTest.Division_Id;
            string countryCode = productTest.Default_Country_Code;

    string defaultProductDescription = productTest.Product_Description; string defaultLanguageCode = productTest.Country.Language_Code; foreach (Country country in productCountries.FirstOrDefault().Countries) { string languageCode = country.Language_Code; string languageDescription = defaultProductDescription; if (defaultLanguageCode != languageCode) { languageDescription = translatorService.Translate(token, languageDescription, defaultLanguageCode, languageCode, "text/html", "general", string.Empty); } //Add the default Country Product Description ProductDescriptionTest productDescriptionTestDetail = new ProductDescriptionTest(); productDescriptionTestDetail.Product_Number = productNumber; productDescriptionTestDetail.Division_Id = divisionId; productDescriptionTestDetail.Country_Code = productTest.Default_Country_Code; productDescriptionTestDetail.Product_Description = db.ProductDescriptionTests.Add(productDescriptionTestDetail); await db.SaveChangesAsync(); } }

    GetAccessTokenAsync

    public async Task<string> GetAccessTokenAsync()
        {
            if (SubscriptionKey == string.Empty) return string.Empty;
    
            // Re-use the cached token if there is one.
            if ((DateTime.Now - storedTokenTime) < TokenCacheDuration)
            {
                return storedTokenValue;
            }
    
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                request.RequestUri = ServiceUrl;
                request.Content = new StringContent(string.Empty);
                request.Headers.TryAddWithoutValidation(OcpApimSubscriptionKeyHeader, this.SubscriptionKey);
                client.Timeout = TimeSpan.FromSeconds(2);
                var response = await client.SendAsync(request);
                this.RequestStatusCode = response.StatusCode;
                response.EnsureSuccessStatusCode();
                var token = await response.Content.ReadAsStringAsync();
                storedTokenTime = DateTime.Now;
                storedTokenValue = "Bearer " + token;
                return storedTokenValue;
            }
        }

    • Moved by CoolDadTx Thursday, August 17, 2017 2:53 PM ASP.NET related
    Thursday, August 17, 2017 12:35 AM

All replies

  • The screenshot is showing only the stacktrace and not the actual error message. Please send the same question with the proper error details to this asp.net api forum: Web Api as there is the right place for similar questions.

    Fouad Roumieh

    Thursday, August 17, 2017 9:29 AM
  • I realized that I posted in the wrong area.

    Here's my link 

    https://forums.asp.net/t/2127050.aspx?Microsoft+Translator+API+work+using+console+not+working+in+MVC


    Thursday, August 17, 2017 2:11 PM