1

I am testing out the Azure Computer Vision API to try extract handwritten text from a local .jpg file. I am following the following example: https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts-sdk/csharp-sdk

Unfortunately when I run my code, I get an exception thrown: System.AggregateException: "this.Endpoint" cannot be null

Text

My test code currently:

class Program
    {
        static string subscriptionKey = Environment.GetEnvironmentVariable("{SUBSCRIPTION-KEY}");
        static string endpoint = Environment.GetEnvironmentVariable("https://{MY-ENDPOINT}.cognitiveservices.azure.com/");

        private const string EXTRACT_TEXT_LOCAL_IMAGE = "vision3.jpg";

        public static ComputerVisionClient Authenticate(string endpoint, string key)
        {
            ComputerVisionClient client =
                new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
                { Endpoint = endpoint };
            return client;
        }


        static void Main()
        {
            Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
            Console.WriteLine();

            ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);

            //ExtractTextUrl(client, EXTRACT_TEXT_URL_IMAGE).Wait();
            ExtractTextLocal(client, EXTRACT_TEXT_LOCAL_IMAGE).Wait();


        }
        public static async Task ExtractTextLocal(ComputerVisionClient client, string localImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("EXTRACT TEXT - LOCAL IMAGE");
            Console.WriteLine();

            // Helps calucalte starting index to retrieve operation ID
            const int numberOfCharsInOperationId = 36;

            Console.WriteLine($"Extracting text from local image {Path.GetFileName(localImage)}...");
            Console.WriteLine();
            using (Stream imageStream = File.OpenRead(localImage))
            {
                // Read the text from the local image
                BatchReadFileInStreamHeaders localFileTextHeaders = await client.BatchReadFileInStreamAsync(imageStream);
                // Get the operation location (operation ID)
                string operationLocation = localFileTextHeaders.OperationLocation;

                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

                // Extract text, wait for it to complete.
                int i = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = await client.GetReadOperationResultAsync(operationId);
                    Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                    await Task.Delay(1000);
                    if (maxRetries == 9)
                    {
                        Console.WriteLine("Server timed out.");
                    }
                }
                while ((results.Status == TextOperationStatusCodes.Running ||
                        results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

                // Display the found text.
                Console.WriteLine();
                var textRecognitionLocalFileResults = results.RecognitionResults;
                foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
                {
                    foreach (Line line in recResult.Lines)
                    {
                        Console.WriteLine(line.Text);
                    }
                }
                Console.WriteLine();
            }
        }
    }

edit:

From trying to debug, it looks like both subscriptionKey and endpoint variables are null from the beginning, even though I initialized them instantly. Why is this?

Text

edit2:

When I hardcode the subscriptionKey and endpoint in Main():

ComputerVisionClient client = Authenticate("https://{END-POINT}.cognitiveservices.azure.com/", "{SUBSCRIPTION-KEY}");

It works fine. Can anybody tell me why my 2 static string variables do not work? As I do not want to hardcode these variables

darego101
  • 319
  • 2
  • 15

3 Answers3

1

Not sure what you want these two lines to accomplish -

static string subscriptionKey = Environment.GetEnvironmentVariable("{SUBSCRIPTION-KEY}");
static string endpoint = Environment.GetEnvironmentVariable("https://{MY-ENDPOINT}.cognitiveservices.azure.com/");

You either pick up environment variables or assign string literals, you're trying to... do a combination of the two?

Maybe read those secrets from appsettings.json instead.

evilSnobu
  • 24,582
  • 8
  • 41
  • 71
1

This is for future people who are following the tutorials and stuck at the environment variables like me, to add new variables from visual studio go to your project properties >> Debug

then add new key and value as provided to you check here to see image explanation

vega_gf
  • 170
  • 1
  • 10
0

Please try adding the below code before sending the request to API or at the starting of code execution.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
Mihail Duchev
  • 4,691
  • 10
  • 25
  • 32