Monday, December 8, 2025

Develop Azure AI services applications securely by using Azure Key Vault and Run Text Analytics (C#)


//Develop Azure AI services applications securely by using Azure Key Vault
and Run Text Analytics (C#)
//Create an Azure AI services account
//Create an Azure Key Vault

using Azure;
using Azure.AI.TextAnalytics;
using Azure.Core;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Threading.Tasks;

namespace WhizConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var keyVaultName = "mykeyvalut85"; //"your-key-vault-name";

            const string keySecretName = "CognitiveServicesKey"; //"Your-Key-Secret-Name";
            const string endpointSecretName = "CognitiveServicesEndpoint"; //"Your-Endpoint-Secret-Name";

            var kvUri = $"https://{keyVaultName}.vault.azure.net/";

            // Try DefaultAzureCredential first and fall back to
                InteractiveBrowserCredential if authentication is unavailable.
            TokenCredential credential = new DefaultAzureCredential();
            SecretClient keyVaultClient = new SecretClient(new Uri(kvUri), credential);

            Console.WriteLine($"Retrieving your secrets from {keyVaultName}.");

            KeyVaultSecret keySecret = null;
            KeyVaultSecret endpointSecret = null;

            try
            {
                var keyResponse = await keyVaultClient.GetSecretAsync(keySecretName);
                keySecret = keyResponse.Value;
                var endpointResponse = await keyVaultClient.GetSecretAsync(endpointSecretName);
                endpointSecret = endpointResponse.Value;
            }
            catch (Azure.Identity.CredentialUnavailableException)
            {
                Console.WriteLine("DefaultAzureCredential could not authenticate
                    with any of the configured credential sources.");
                Console.WriteLine("Falling back to InteractiveBrowserCredential.
                    A browser window will open for authentication.");

                credential = new InteractiveBrowserCredential();
                keyVaultClient = new SecretClient(new Uri(kvUri), credential);

                try
                {
                    var keyResponse =
                        await keyVaultClient.GetSecretAsync(keySecretName);
                    keySecret = keyResponse.Value;
                    var endpointResponse =
                        await keyVaultClient.GetSecretAsync(endpointSecretName);
                    endpointSecret = endpointResponse.Value;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to retrieve secrets after falling
                        back: {ex.Message}");
                    Console.WriteLine("Recommendations: run 'az login', or set
                        AZURE_CLIENT_ID / AZURE_TENANT_ID / AZURE_CLIENT_SECRET
                        environment variables for a service principal.");
                    Console.ReadLine();
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to retrieve secrets: {ex.Message}");
                Console.ReadLine();
                return;
            }

            Console.WriteLine($"Your key secret value is: {keySecret.Value}");
            Console.WriteLine($"Your endpoint secret value is: {endpointSecret.Value}");
            Console.WriteLine("Secrets retrieved successfully");

            EntityRecognitionExample(keySecret.Value, endpointSecret.Value);

            Console.ReadLine();
        }

        private static void EntityRecognitionExample(
            string keySecret, string endpointSecret
        )
        {
            var exampleString = "I had a wonderful trip to Seattle last week.";

            AzureKeyCredential azureKeyCredential = new AzureKeyCredential(keySecret);
            Uri endpoint = new Uri(endpointSecret);
            var languageServiceClient =
                new TextAnalyticsClient(endpoint, azureKeyCredential);

            Console.WriteLine("Sending a Named Entity Recognition (NER) request");
            var response = languageServiceClient.RecognizeEntities(exampleString);

            Console.WriteLine("Named Entities:");
            foreach (var entity in response.Value)
            {
                Console.WriteLine($"\tText: {entity.Text},\tCategory:
                    {entity.Category},\tSub-Category: {entity.SubCategory}");
                Console.WriteLine($"\t\tScore: {entity.ConfidenceScore:F2},\tLength:
                    {entity.Length},\tOffset: {entity.Offset}\n");
            }
        }

    }
}


OutPut:



3 comments:

  1. Absolutely love how comprehensive this Outback Steakhouse menu guide is! Everything from appetizers to desserts is listed with accurate prices and calories. Makes ordering ahead so convenient, especially when feeding a large family group.

    ReplyDelete
  2. Super impressed by how thorough this Red Lobster menu with prices breakdown is! The search function works perfectly, and I love that nutritional information is readily accessible. This transparency helps me make healthier dining choices without compromising on flavor.

    ReplyDelete
  3. Highly recommend this site for browsing Raising Cane's menu with prices and planning meals! The combo comparisons make choosing easier, and tailgate pricing is clearly displayed. Saves time and eliminates confusion about what's available at my local restaurant location.

    ReplyDelete

Featured Post

Study guide for Exam AZ-204: Developing Solutions for Microsoft Azure

  Azure: Implement Containerized Solutions (Points Only) 1) ✅ Create and Manage Container Images for Solutions ✅ What a container image is A...

Popular posts