Wednesday, June 18, 2025

Create a generative AI chat app

Create a generative AI chat app

https://microsoftlearning.github.io/mslearn-ai-studio/Instructions/02a-AI-foundry-sdk.html

1. Go to https://ai.azure.com/
2. Create a new Project and deploy 'gpt-4o' model

C# Code:
using System;
using Azure;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Azure.Identity;
using Azure.AI.Projects;
using Azure.AI.Inference;

namespace chat_app
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Clear();
            try
            {
                IConfigurationBuilder builder =
                    new ConfigurationBuilder().AddJsonFile("appsettings.json");
                IConfigurationRoot configuration = builder.Build();
                string project_connection = "https://sree-2937-resource.services.ai.
                    azure.com/api/projects/sree-2937";
                string model_deployment = "my-gpt-4o-2";

                DefaultAzureCredentialOptions options = new()
                {
                    ExcludeEnvironmentCredential = true,
                    ExcludeManagedIdentityCredential = true
                };
                var projectClient = new AIProjectClient(
                     new Uri(project_connection),
                     new DefaultAzureCredential(options));

                ChatCompletionsClient chat = projectClient.GetChatCompletionsClient();

                var prompt = new List<ChatRequestMessage>(){
                 new ChatRequestSystemMessage("You are a helpful AI assistant that
                    answers questions.")
             };

                string input_text = "";
                while (input_text.ToLower() != "quit")
                {
                    Console.WriteLine("Enter the prompt (or type 'quit' to exit):");
                    input_text = Console.ReadLine();
                    if (input_text.ToLower() != "quit")
                    {
                        prompt.Add(new ChatRequestUserMessage(input_text));
                        var requestOptions = new ChatCompletionsOptions()
                        {
                            Model = model_deployment,
                            Messages = prompt
                        };

                        Response<ChatCompletions> response =
                            chat.Complete(requestOptions);
                        var completion = response.Value.Content;
                        Console.WriteLine(completion);
                        prompt.Add(new ChatRequestAssistantMessage(completion));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}



OutPut:
1.  dotnet add package Azure.Identity
     dotnet add package Azure.AI.Projects --version 1.0.0-beta.9
     dotnet add package Azure.AI.Inference --version 1.0.0-beta.5

2. AZ LOGIN
3. dotnet run
4. 


Python Code:
import os
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.inference.models import SystemMessage, UserMessage, AssistantMessage

def main():

    os.system('cls' if os.name=='nt' else 'clear')
       
    try:
   
        load_dotenv()
        project_connection = "https://sree-2937-resource.services.ai.azure.com/api
            /projects/sree-2937"
        model_deployment =  "my-gpt-4o-2"
       
        projectClient = AIProjectClient(            
         credential=DefaultAzureCredential(
             exclude_environment_credential=True,
             exclude_managed_identity_credential=True
         ),
         endpoint=project_connection,
        )
       
        chat = projectClient.inference.get_chat_completions_client()

        prompt=[
         SystemMessage("You are a helpful AI assistant that answers questions.")
        ]

        while True:
            input_text = input("Enter the prompt (or type 'quit' to exit): ")
            if input_text.lower() == "quit":
                break
            if len(input_text) == 0:
                print("Please enter a prompt.")
                continue
           
            prompt.append(UserMessage(input_text))
            response = chat.complete(
                model=model_deployment,
                messages=prompt)
            completion = response.choices[0].message.content
            print(completion)
            prompt.append(AssistantMessage(completion))

    except Exception as ex:
        print(ex)

if __name__ == '__main__':
    main()

OutPut:
1.  python -m venv labenv
    ./labenv/bin/Activate.ps1
    pip install python-dotenv azure-identity azure-ai-projects azure-ai-inference

2. AZ LOGIN
3. python chat-app.py
4. 

Wednesday, March 26, 2025

Hybrid Connections WebSockets in Azure Relay

Hybrid Connections WebSockets in Azure Relay

Source: https://learn.microsoft.com/en-us/azure/azure-relay/relay-hybrid-connections-dotnet-get-started

1. Create a Namespace





Get Managed credentials 

Create Hybrid Connection 


2. Create a server application (listener)

using Microsoft.Azure.Relay;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace myserver
{
    public class Program
    {
        private const string RelayNamespace = "sreerelay.servicebus.windows.net";
        private const string ConnectionName = "sreehybridconn";
        private const string KeyName = "RootManageSharedAccessKey";
        private const string Key = "Wtcg6qDIGI4aFts+qYH+zmHwCL1Q=";

        public static void Main(string[] args)
        {
            RunAsync().GetAwaiter().GetResult();
        }

        private static async Task RunAsync()
        {
            var cts = new CancellationTokenSource();
            var tokenProvider =
            TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener = new HybridConnectionListener(new Uri(string.Format(
            "sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online += (o, e) => { Console.WriteLine("Online"); };
            await listener.OpenAsync(cts.Token);
            Console.WriteLine("Server listening");
            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));
            new Task(() => Console.In.ReadLineAsync().ContinueWith((s) => {
            cts.Cancel(); })).Start();
            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();
                if (relayConnection == null)
                {
                    break;
                }
                ProcessMessagesOnConnection(relayConnection, cts);
            }
            await listener.CloseAsync(cts.Token);
        }

        private static async void ProcessMessagesOnConnection(HybridConnectionStream
        relayConnection, CancellationTokenSource cts)
        {
            Console.WriteLine("New session");
            var reader = new StreamReader(relayConnection);
            var writer = new StreamWriter(relayConnection) { AutoFlush = true };
            while (!cts.IsCancellationRequested)
            {
                try
                {
                    var line = await reader.ReadLineAsync();
                    if (string.IsNullOrEmpty(line))
                    {
                        await relayConnection.ShutdownAsync(cts.Token);
                        break;
                    }
                    Console.WriteLine(line);
                    await writer.WriteLineAsync($"Echo: {line}");
                }
                catch (IOException)
                {
                    Console.WriteLine("Client closed connection");
                    break;
                }
            }
            Console.WriteLine("End session");
            await relayConnection.CloseAsync(cts.Token);
        }
    }
}


3. Create a client application (sender)

using Microsoft.Azure.Relay;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace myclient
{
    class Program
    {
        private const string RelayNamespace = "sreerelay.servicebus.windows.net";
        private const string ConnectionName = "sreehybridconn";
        private const string KeyName = "RootManageSharedAccessKey";
        private const string Key = "Wtcg6qDIGI4aFts+qYH+zmHwCL1Q=";

        static void Main(string[] args)
        {
            RunAsync().GetAwaiter().GetResult();
        }

        private static async Task RunAsync()
        {
            Console.WriteLine("Enter lines of text to send to the server with ENTER");
            var tokenProvider =
            TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var client = new HybridConnectionClient(new Uri(String.Format(
            "sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
            var relayConnection = await client.CreateConnectionAsync();

            var reads = Task.Run(async () =>
            {
                var reader = new StreamReader(relayConnection);
                var writer = Console.Out;
                do
                {
                    string line = await reader.ReadLineAsync();
                    if (String.IsNullOrEmpty(line))
                        break;
                    await writer.WriteLineAsync(line);
                }
                while (true);
            });

            var writes = Task.Run(async () =>
            {
                var reader = Console.In;
                var writer = new StreamWriter(relayConnection) { AutoFlush = true };
                do
                {
                    string line = await reader.ReadLineAsync();
                    await writer.WriteLineAsync(line);
                    if (String.IsNullOrEmpty(line))
                        break;
                }
                while (true);
            });
           
            await Task.WhenAll(reads, writes);
            await relayConnection.CloseAsync(CancellationToken.None);
        }
    }
}


OutPut:


Monday, March 10, 2025

Actionable Email Developer Dashboard

 Actionable Email Developer Dashboard:

Source:
Get started with actionable messages in Office 365: https://learn.microsoft.com/en-us/outlook/actionable-messages/get-started

Register your service with the actionable email developer dashboard: https://learn.microsoft.com/en-us/outlook/actionable-messages/email-dev-dashboard

1. Create Provider in ''Actionable Email Developer Dashboard - https://outlook.office.com/connectors/oam/publish "

2. Save "Provider Id (originator)" in notepad.

3. Approve submitted provider here: https://outlook.office.com/connectors/oam/admin





4. Prepare Json as below: 

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script type="application/adaptivecard+json">{
    "type": "AdaptiveCard",
    "version": "1.0",
    "hideOriginalBody": true,
    "originator": "Provider Id (originator) : GUID from Previous step",
    "body": [
      {
        "type": "TextBlock",
        "text": "Visit the Outlook Dev Portal",
        "size": "large"
      },
      {
        "type": "TextBlock",
        "text": "Click **Learn More** to learn more about Actionable Messages!"
      },
      {
        "type": "Input.Text",
        "id": "feedbackText",
        "placeholder": "Let us know what you think about Actionable Messages"
      }
    ],
    "actions": [
      {
        "type": "Action.Http",
        "title": "Send Feedback",
        "method": "POST",
        "url": "https://...",
        "body": "{{feedbackText.value}}"
      },
      {
        "type": "Action.OpenUrl",
        "title": "Learn More",
        "url": "https://learn.microsoft.com/outlook/actionable-messages"
      }
    ]
  }
  </script>
</head>
<body>
Visit the <a href="https://learn.microsoft.com/outlook/actionable-messages">Outlook Dev Portal</a> to learn more about Actionable Messages.
</body>
</html>

C# Code:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Users.Item.SendMail;

public class Program
{
    public static async Task Main(string[] args)
    {
        var clientId = "6e4110e7-e5b0d411db60";
        var tenantId = "bb55f134-82bf54373c6d";
        var clientSecret = "imx8Q~Q~AHcGN";
        var userFromEmail = "user1@test.onmicrosoft.com";
        var userToEmails = "user2@test.onmicrosoft.com,user3@test.onmicrosoft.com";

        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(credential);

        string adaptiveCardJson = @"<html>
        <head>
          <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
          <script type='application/adaptivecard+json'>{
            'type': 'AdaptiveCard',
            'version': '1.0',
            'hideOriginalBody': true,
            'originator': 'a115aabe-03994fbaf1d',
            'body': [
              {
                'type': 'TextBlock',
                'text': 'Visit the Outlook Dev Portal',
                'size': 'large'
              },
              {
                'type': 'TextBlock',
                'text': 'Click **Learn More** to learn more about Actionable Messages!'
              },
              {
                'type': 'Input.Text',
                'id': 'feedbackText',
                'placeholder': 'Let us know what you think about Actionable Messages'
              }
            ],
            'actions': [
              {
                'type': 'Action.Http',
                'title': 'Send Feedback',
                'method': 'POST',
                'url': 'https://...',
                'body': '{{feedbackText.value}}'
              },
              {
                'type': 'Action.OpenUrl',
                'title': 'Learn More',
                'url': 'https://learn.microsoft.com/outlook/actionable-messages'
              }
            ]
          }
          </script>
        </head>
        <body>
        Visit the <a href='https://learn.microsoft.com/outlook/actionable-messages'>Outlook Dev
        Portal</a> to learn more about Actionable Messages.
        </body>
        </html>";

        List<string> userToEmailList = new List<string>(userToEmails.Split(','));
        var message = new Message
        {
            Subject = "Test Subject",
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = $"{adaptiveCardJson}"
            },
            ToRecipients = userToEmailList.Select(email => new Recipient { EmailAddress =
            new EmailAddress { Address = email } }).ToList(),
        };
        var sendMailRequest = new SendMailPostRequestBody { Message = message };
        await graphClient.Users[userFromEmail].SendMail.PostAsync(sendMailRequest);

        Console.ReadKey();
    }
}



OutPut:






Monday, March 3, 2025

Connect SharePoint using Azure App Application/Delegate Authentication in C#

1. Connect SharePoint using Azure App Application Authentication in C#
Create Azure app and give below Application permissions. 


using Azure.Identity;
using Microsoft.Graph;

public class Program
{
    public static async Task Main(string[] args)
    {
        string tenantId = "";
        string clientId = "";
        string clientSecret = "";
        string siteId = "283f598a-6b0f-4ba5-af06-c72a0cef8f42";
        string listId = "e9609d64-1f36-45a2-8260-743998ea2cd4";
        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(credential);
        var items = await graphClient.Sites[siteId].Lists[listId].Items.GetAsync();
        foreach (var item in items.Value)
        {
            Console.WriteLine($"Item ID: {item.Id}, Created By: {item.CreatedBy?.User?.DisplayName}");
        }
        Console.ReadKey();
    }
}



2. Connect SharePoint using Azure App Delegate Authentication in C#

Wednesday, February 19, 2025

Azure AI services | Language service | Azure Cognitive Search | Sentiment analysis and opinion mining

Azure AI services | Language service | Azure Cognitive Search | Sentiment analysis and opinion mining

1. Create a Language resource in Azure and copy languagekey.

using Azure;
using System;
using Azure.AI.TextAnalytics;
using System.Collections.Generic;

namespace Example
{
    class Program
    {
        // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"

        // Environment.GetEnvironmentVariable("LANGUAGE_KEY");
        static string languageKey = "9BuOuIbUCOGGygz";
       
        //Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT");
        static string languageEndpoint = "https://sreelanguage.cognitiveservices.azure.com/";

        private static readonly AzureKeyCredential credentials = new AzureKeyCredential(languageKey);
        private static readonly Uri endpoint = new Uri(languageEndpoint);

        // Example method for detecting opinions text.
        static void SentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
        {
            var documents = new List<string>
            {
                "The food and service were unacceptable. The concierge was nice, however."
            };

            AnalyzeSentimentResultCollection reviews = client.AnalyzeSentimentBatch(documents,
            options: new AnalyzeSentimentOptions()
            {
                IncludeOpinionMining = true
            });

            foreach (AnalyzeSentimentResult review in reviews)
            {
                Console.WriteLine($"Document sentiment: {review.DocumentSentiment.Sentiment}\n");
                Console.WriteLine($"\tPositive score:
                {review.DocumentSentiment.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score:
                {review.DocumentSentiment.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score:
                {review.DocumentSentiment.ConfidenceScores.Neutral:0.00}\n");

                foreach (SentenceSentiment sentence in review.DocumentSentiment.Sentences)
                {
                    Console.WriteLine($"\tText: \"{sentence.Text}\"");
                    Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                    Console.WriteLine($"\tSentence positive score:
                    {sentence.ConfidenceScores.Positive:0.00}");
                    Console.WriteLine($"\tSentence negative score:
                    {sentence.ConfidenceScores.Negative:0.00}");
                    Console.WriteLine($"\tSentence neutral score:
                    {sentence.ConfidenceScores.Neutral:0.00}\n");

                    foreach (SentenceOpinion sentenceOpinion in sentence.Opinions)
                    {
                        Console.WriteLine($"\tTarget: {sentenceOpinion.Target.Text}, Value:
                        {sentenceOpinion.Target.Sentiment}");
                        Console.WriteLine($"\tTarget positive score:
                        {sentenceOpinion.Target.ConfidenceScores.Positive:0.00}");
                        Console.WriteLine($"\tTarget negative score:
                        {sentenceOpinion.Target.ConfidenceScores.Negative:0.00}");
                        foreach (AssessmentSentiment assessment in sentenceOpinion.Assessments)
                        {
                            Console.WriteLine($"\t\tRelated Assessment: {assessment.Text}, Value:
                            {assessment.Sentiment}");
                            Console.WriteLine($"\t\tRelated Assessment positive score:
                            {assessment.ConfidenceScores.Positive:0.00}");
                            Console.WriteLine($"\t\tRelated Assessment negative score:
                            {assessment.ConfidenceScores.Negative:0.00}");
                        }
                    }
                }
                Console.WriteLine($"\n");
            }
        }

        static void Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            SentimentAnalysisWithOpinionMiningExample(client);
            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }
    }
}


OutPut:


Monday, February 17, 2025

Azure AI services | Document intelligence | Use prebuilt Document Intelligence models

Azure AI services | Document intelligence | Use prebuilt Document Intelligence models

Source: https://github.com/MicrosoftLearning/mslearn-ai-document-intelligence

https://documentintelligence.ai.azure.com/studio

C# Code:

using Azure;
using Azure.AI.FormRecognizer.DocumentAnalysis;

// dotnet add package Azure.AI.FormRecognizer --version 4.1.0

// Store connection information
string endpoint = "https://sreedocumentintelligence.cognitiveservices.azure.com/";
string apiKey = "BxcKE20FOGiN8b";

Uri fileUri = new Uri("https://github.com/MicrosoftLearning/mslearn-ai-document-intelligence/blob
/main/Labfiles/01-prebuild-models/sample-invoice/sample-invoice.pdf?raw=true");

Console.WriteLine("\nConnecting to Forms Recognizer at: {0}", endpoint);
Console.WriteLine("Analyzing invoice at: {0}\n", fileUri.ToString());

// Create the client
var cred = new AzureKeyCredential(apiKey);
var client = new DocumentAnalysisClient(new Uri(endpoint), cred);

// Analyze the invoice
AnalyzeDocumentOperation operation = await client.AnalyzeDocumentFromUriAsync(WaitUntil.Completed,
"prebuilt-invoice", fileUri);


// Display invoice information to the user
AnalyzeResult result = operation.Value;

foreach (AnalyzedDocument invoice in result.Documents)
{
    if (invoice.Fields.TryGetValue("VendorName", out DocumentField? vendorNameField))
    {
        if (vendorNameField.FieldType == DocumentFieldType.String)
        {
            string vendorName = vendorNameField.Value.AsString();
            Console.WriteLine($"Vendor Name: '{vendorName}', with confidence
            {vendorNameField.Confidence}.");
        }
    }

    if (invoice.Fields.TryGetValue("CustomerName", out DocumentField? customerNameField))
    {
        if (customerNameField.FieldType == DocumentFieldType.String)
        {
            string customerName = customerNameField.Value.AsString();
            Console.WriteLine($"Customer Name: '{customerName}', with confidence
            {customerNameField.Confidence}.");
        }
    }

    if (invoice.Fields.TryGetValue("InvoiceTotal", out DocumentField? invoiceTotalField))
    {
        if (invoiceTotalField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue invoiceTotal = invoiceTotalField.Value.AsCurrency();
            Console.WriteLine($"Invoice Total: '{invoiceTotal.Symbol}{invoiceTotal.Amount}',
            with confidence {invoiceTotalField.Confidence}.");
        }
    }
}

Console.WriteLine("\nAnalysis complete.\n");


OutPut:


Python Code:
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer import DocumentAnalysisClient

# pip install azure-ai-formrecognizer==3.3.3

# Store connection information
endpoint = "https://sreedocumentintelligence.cognitiveservices.azure.com/"
key = "BxcKE20FOGiN8b"

fileUri = "https://github.com/MicrosoftLearning/mslearn-ai-document-intelligence/blob/main/Labfiles
/01-prebuild-models/sample-invoice/sample-invoice.pdf?raw=true"
fileLocale = "en-US"
fileModelId = "prebuilt-invoice"

print(f"\nConnecting to Forms Recognizer at: {endpoint}")
print(f"Analyzing invoice at: {fileUri}")

# Create the client
document_analysis_client = DocumentAnalysisClient(
     endpoint=endpoint, credential=AzureKeyCredential(key)
)

# Analyse the invoice
poller = document_analysis_client.begin_analyze_document_from_url(
     fileModelId, fileUri, locale=fileLocale
)

# Display invoice information to the user
receipts = poller.result()
   
for idx, receipt in enumerate(receipts.documents):
    vendor_name = receipt.fields.get("VendorName")
    if vendor_name:
        print(f"\nVendor Name: {vendor_name.value}, with confidence {vendor_name.confidence}.")

    customer_name = receipt.fields.get("CustomerName")
    if customer_name:
        print(f"Customer Name: '{customer_name.value}, with confidence {customer_name.confidence}.")


    invoice_total = receipt.fields.get("InvoiceTotal")
    if invoice_total:
        print(f"Invoice Total: '{invoice_total.value.symbol}{invoice_total.value.amount},
        with confidence {invoice_total.confidence}.")

print("\nAnalysis complete.\n")

OutPut:




Featured Post

Create a generative AI chat app

Create a generative AI chat app https://microsoftlearning.github.io/mslearn-ai-studio/Instructions/02a-AI-foundry-sdk.html 1. Go to https://...

Popular posts