Quickstart: Use the .NET SDK and C# to call the Text Analytics service

This quickstart helps you begin using the Azure SDK for .NET and C# to analyze language. Although the Text Analytics REST API is compatible with most programming languages, the SDK provides an easy way to integrate the service into your applications.

Note

The source code for this sample is available on GitHub.

For technical details, refer to the SDK for .NET Text Analytics reference.

Prerequisites

  • Any edition of [visual studio 2017 or later]
  • The Text Analytics SDK for .NET

You must have a Cognitive Services API subscription with access to the Text Analytics API. If you don't have a subscription, you can create an account for free. Before continuing, you will need the Text Analytics subscription key provided after activating your account.

You also need the endpoint and access key that was generated for you during sign-up.

Create the Visual Studio solution and install the SDK

  1. Create a new console app (.NET Core) project. Access Visual Studio.
  2. Right-click the solution and select Manage NuGet Packages for Solution.
  3. Select the Browse tab. Search for Microsoft.Azure.CognitiveServices.Language.TextAnalytics.

Authenticate your credentials

  1. Add the following using statements to the main class file (which is Program.cs by default).

    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    
    using Microsoft.Azure.CognitiveServices.Language.TextAnalytics;
    using Microsoft.Azure.CognitiveServices.Language.TextAnalytics.Models;
    using Microsoft.Rest;
    
  2. Create a new ApiKeyServiceClientCredentials class to store the credentials and add them for each request.

    /// <summary>
    /// Allows authentication to the API by using a basic apiKey mechanism
    /// </summary>
    class ApiKeyServiceClientCredentials : ServiceClientCredentials
    {
        private readonly string subscriptionKey;
    
        /// <summary>
        /// Creates a new instance of the ApiKeyServiceClientCredentails class
        /// </summary>
        /// <param name="subscriptionKey">The subscription key to authenticate and authorize as</param>
        public ApiKeyServiceClientCredentials(string subscriptionKey)
        {
            this.subscriptionKey = subscriptionKey;
        }
    
        /// <summary>
        /// Add the Basic Authentication Header to each outgoing request
        /// </summary>
        /// <param name="request">The outgoing request</param>
        /// <param name="cancellationToken">A token to cancel the operation</param>
        public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
    
            request.Headers.Add("Ocp-Apim-Subscription-Key", this.subscriptionKey);
            return base.ProcessHttpRequestAsync(request, cancellationToken);
        }
    }
    
  3. Update the Program class. Add a constant member for your Text Analytics subscription key, and another for the service endpoint. Remember to use the correct Azure region for your Text Analytics subscription.

    private const string SubscriptionKey = "enter-your-key-here";
    
    private const string Endpoint = "enter-your-service-endpoint-here"; // For example: "https://westus.api.cognitive.microsoft.com";
    

Tip

To boost the security of secrets in production systems, we recommend that you use Azure Key Vault.

Create a Text Analytics client

In the Main function of your project, call the sample method that you want to invoke. Pass the Endpoint and SubscriptionKey parameters that you defined.

    public static void Main(string[] args)
    {
        var credentials = new ApiKeyServiceClientCredentials(SubscriptionKey);
        var client = new TextAnalyticsClient(credentials)
        {
            Endpoint = Endpoint
        };

        // Change the console encoding to display non-ASCII characters.
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        SentimentAnalysisExample(client).Wait();
        // DetectLanguageExample(client).Wait();
        // RecognizeEntitiesExample(client).Wait();
        // KeyPhraseExtractionExample(client).Wait();
        Console.ReadLine();
    }

The following sections describe how to call each service feature.

Perform sentiment analysis

  1. Create a new function SentimentAnalysisExample() that takes the client that you created earlier.

  2. Generate a list of MultiLanguageInput objects that contains the documents that you want to analyze.

    public static async Task SentimentAnalysisExample(TextAnalyticsClient client)
    {
        // The documents to be analyzed. Add the language of the document. The ID can be any value.
        var inputDocuments = new MultiLanguageBatchInput(
            new List<MultiLanguageInput>
            {
                new MultiLanguageInput("en", "1", "I had the best day of my life."),
                new MultiLanguageInput("en", "2", "This was a waste of my time. The speaker put me to sleep."),
                new MultiLanguageInput("es", "3", "No tengo dinero ni nada que dar..."),
                new MultiLanguageInput("it", "4", "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),
            });
        //...
    }
    
  3. In the same function, call client.SentimentAsync() and get the result. Then iterate through the results. Print each document's ID and sentiment score. A score that's close to 0 indicates a negative sentiment, while a score that's closer to 1 indicates a positive sentiment.

    var result = await client.SentimentAsync(false, inputDocuments);
    
    // Printing sentiment results
    foreach (var document in result.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} , Sentiment Score: {document.Score:0.00}");
    }
    

Output

Document ID: 1 , Sentiment Score: 0.87
Document ID: 2 , Sentiment Score: 0.11
Document ID: 3 , Sentiment Score: 0.44
Document ID: 4 , Sentiment Score: 1.00

Perform language detection

  1. Create a new function DetectLanguageExample() that takes the client that you created earlier.

  2. Generate a list of LanguageInput objects that contains your documents.

    public static async Task DetectLanguageExample(TextAnalyticsClient client)
    {
    
        // The documents to be submitted for language detection. The ID can be any value.
        var inputDocuments = new LanguageBatchInput(
                new List<LanguageInput>
                    {
                        new LanguageInput(id: "1", text: "This is a document written in English."),
                        new LanguageInput(id: "2", text: "Este es un document escrito en Español."),
                        new LanguageInput(id: "3", text: "这是一个用中文写的文件")
                    });
        //...
    }
    
  3. In the same function, call client.DetectLanguageAsync() and get the result. Then iterate through the results. Print each document's ID and the first returned language.

    var langResults = await client.DetectLanguageAsync(false, inputDocuments);
    
    // Printing detected languages
    foreach (var document in langResults.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} , Language: {document.DetectedLanguages[0].Name}");
    }
    

Output

===== LANGUAGE EXTRACTION ======
Document ID: 1 , Language: English
Document ID: 2 , Language: Spanish
Document ID: 3 , Language: Chinese_Simplified

Perform entity recognition

  1. Create a new function RecognizeEntitiesExample() that takes the client that you created earlier.

  2. Generate a list of MultiLanguageBatchInput objects that contains your documents.

    public static async Task RecognizeEntitiesExample(TextAnalyticsClient client)
    {
    
        // The documents to be submitted for entity recognition. The ID can be any value.
        var inputDocuments = new MultiLanguageBatchInput(
            new List<MultiLanguageInput>
            {
                new MultiLanguageInput("en", "1", "Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and sell BASIC interpreters for the Altair 8800."),
                new MultiLanguageInput("es", "2", "La sede principal de Microsoft se encuentra en la ciudad de Redmond, a 21 kilómetros de Seattle.")
            });
        //...
    }
    
  3. In the same function, call client.EntitiesAsync() and get the result. Then iterate through the results. Print each document's ID. For each detected entity, print its Wikipedia name and the type and subtypes (if they exist) as well as the locations in the original text.

    var entitiesResult = await client.EntitiesAsync(false, inputDocuments);
    
    // Printing recognized entities
    foreach (var document in entitiesResult.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} ");
    
        Console.WriteLine("\t Entities:");
        foreach (var entity in document.Entities)
        {
            Console.WriteLine($"\t\tName: {entity.Name},\tType: {entity.Type ?? "N/A"},\tSub-Type: {entity.SubType ?? "N/A"}");
            foreach (var match in entity.Matches)
            {
                Console.WriteLine($"\t\t\tOffset: {match.Offset},\tLength: {match.Length},\tScore: {match.EntityTypeScore:F3}");
            }
        }
    }
    

Output

Document ID: 1
         Entities:
                Name: Microsoft,        Type: Organization,     Sub-Type: N/A
                        Offset: 0,      Length: 9,      Score: 1.000
                Name: Bill Gates,       Type: Person,   Sub-Type: N/A
                        Offset: 25,     Length: 10,     Score: 1.000
                Name: Paul Allen,       Type: Person,   Sub-Type: N/A
                        Offset: 40,     Length: 10,     Score: 0.999
                Name: April 4,  Type: Other,    Sub-Type: N/A
                        Offset: 54,     Length: 7,      Score: 0.800
                Name: April 4, 1975,    Type: DateTime, Sub-Type: Date
                        Offset: 54,     Length: 13,     Score: 0.800
                Name: BASIC,    Type: Other,    Sub-Type: N/A
                        Offset: 89,     Length: 5,      Score: 0.800
                Name: Altair 8800,      Type: Other,    Sub-Type: N/A
                        Offset: 116,    Length: 11,     Score: 0.800
Document ID: 2
         Entities:
                Name: Microsoft,        Type: Organization,     Sub-Type: N/A
                        Offset: 21,     Length: 9,      Score: 1.000
                Name: Redmond (Washington),     Type: Location, Sub-Type: N/A
                        Offset: 60,     Length: 7,      Score: 0.991
                Name: 21 kilómetros,    Type: Quantity, Sub-Type: Dimension
                        Offset: 71,     Length: 13,     Score: 0.800
                Name: Seattle,  Type: Location, Sub-Type: N/A
                        Offset: 88,     Length: 7,      Score: 1.000

Perform key phrase extraction

  1. Create a new function KeyPhraseExtractionExample() that takes the client that you created earlier.

  2. Generate a list of MultiLanguageBatchInput objects that contains your documents.

    public static async Task KeyPhraseExtractionExample(TextAnalyticsClient client)
    {
        var inputDocuments = new MultiLanguageBatchInput(
                    new List<MultiLanguageInput>
                    {
                        new MultiLanguageInput("ja", "1", "猫は幸せ"),
                        new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
                        new MultiLanguageInput("en", "3", "My cat might need to see a veterinarian."),
                        new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")
                    });
        //...
    }
    
  3. In the same function, call client.KeyPhrasesAsync() and get the result. Then iterate through the results. Print each document's ID and any detected key phrases.

    var kpResults = await client.KeyPhrasesAsync(false, inputDocuments);
    
    // Printing keyphrases
    foreach (var document in kpResults.Documents)
    {
        Console.WriteLine($"Document ID: {document.Id} ");
    
        Console.WriteLine("\t Key phrases:");
    
        foreach (string keyphrase in document.KeyPhrases)
        {
            Console.WriteLine($"\t\t{keyphrase}");
        }
    }
    

Output

Document ID: 1
         Key phrases:
                幸せ
Document ID: 2
         Key phrases:
                Stuttgart
                Hotel
                Fahrt
                Fu
Document ID: 3
         Key phrases:
                cat
                veterinarian
Document ID: 4
         Key phrases:
                fútbol

Next steps