Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, September 19, 2025

Web - AI Based Regex Generator

Problem Statement: 

I want to dynamically generate RegEx based on human provided input with simple .Net, C# web application. 

Implementation:

- Create web application using .Net C#, Web API

- As prerequisite need to get the Open AI Service details. If it's not already exists follow this

  • Go to Portal.Azure.Com
  • Search for Azure OpenAI 


  • Create new Open AI and click to go to Azure AI Foundry
  • In Azure AI Foundry, Left side click Home. This is your Open AI API Key to use in code below
  • In Azure AI Foundry, Left side click PlayGrounds/Chat, you should be able to setup new Chatbot with new deployment model (For ex: GPT3.5Turbo, GPT5 etc,.). This is your Deployment Model Name to use in code below.
  • Click the View Code on Chat, to get the Endpoint details. This is your Chat Completion Endpoint to use in code below.



- In index.cshtml, simply add textbox and post call
  

<h2>Balaji - AI-Powered Regex Validator - POC</h2>

<form method="post">

    <label for="rule">Enter validation rule (human text):</label><br />

    <input type="text" id="rule" name="Rule" value="@Model.Rule" size="50" /><br /><br />

     <button type="submit">Generate Regex</button><br /><br />

     @if (!string.IsNullOrEmpty(Model.GeneratedRegex))

    {

        <div><strong>Generated Regex:</strong> @Model.GeneratedRegex</div>

         <br />

        <label for="inputText">Enter text to validate:</label>

        <br />

        <input type="text" id="inputText" name="InputText" value="@Model.InputText" size="50" />

         <br />

         <br />

        <div id="result">@Model.ValidationResult</div>

    }

</form>



 - In Index.cshtml.cs, add below logic to generate the validation from AI code. 


using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using System.Net.Http;

using System.Text;

using System.Text.Json;

using System.Threading.Tasks;

 

namespace POCRegexBuilderAI.Pages

{

    public class IndexModel : PageModel

    {

        [BindProperty]

        public string Rule { get; set; }

        [BindProperty]

        public string InputText { get; set; }

        public string GeneratedRegex { get; set; }

        public string ValidationResult { get; set; }

 

        public async Task<IActionResult> OnPostAsync()

        {

            if (!string.IsNullOrEmpty(Rule))

            {

                // Call OpenAI API to generate regex

                var regex = await GenerateRegexFromRule(Rule);

                GeneratedRegex = regex;

 

                if (!string.IsNullOrEmpty(InputText) && !string.IsNullOrEmpty(regex))

                {

                    try

                    {

                        var isValid = System.Text.RegularExpressions.Regex.IsMatch(InputText, regex);

                        ValidationResult = isValid ? " Valid input" : " Invalid input";

                    }

                    catch

                    {

                        ValidationResult = "⚠️ Invalid regex pattern.";

                    }

                }

            }

             return Page();

        }

        private async Task<string> GenerateRegexFromRule(string rule)

        {

            var apiKey = "1.ReplaceYourOpenAIKey";

            var prompt = $"Convert this rule to regex: {rule}";

            var requestBody = new

            {

                model = "gpt-35-turbo", //2.Replace with your deployment model

                messages = new[]

                {

                new { role = "user", content = prompt }

            }

            };

             using var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

             var chatCompletionUrl = "https://api.openai.com/v1/chat/completions";//3.Replace with your chatmodel endpoint

             var content = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");

            var response = await client.PostAsync(chatCompletionUrl, content);

            var responseString = await response.Content.ReadAsStringAsync();

 

            using var doc = JsonDocument.Parse(responseString);

            var regex = doc.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();

             return regex.Trim();

        }

     }

}

 

- Now simply try with human text ("Zipcode with alphabet numeric with Min 3 and Max 5 character") to convert into Regex to apply in any textbox UI as output. It will show the validation simply as below







Friday, July 21, 2023

How to get previous page details in page change event on embedded PowerBI report

In Power Bi, there is challenge to get page details when changing the pages. In Angular/JavaScript, powerBI client provides event handling to manage this. For this page changes, we have "pageChanged" event. Below sample code will help us to get events on page changes, so that you can capture bookmark if needed on previous page names etc.,


Sample Code: 

import { service, factories } from "powerbi-client";
const powerBI= new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory);

....

let currentSelectedPage = any = null;
let pbiElement = document.getElementById(“yourdivid”);
let pbiconfig = : any = {
    type: 'report',
    hostName: "https://app.powerbi.com/",
    accessToken: "",
    embedUrl: "",
    id: "",
    settings: {
      filterPaneEnabled: false,
      navContentPaneEnabled: false
    }
  }

this.report =  powerBI.embed(pbiElement, pbiconfig);

this.report.on('pageChanged', (event) => {
      
     console.log('Page changed Old:', event.detail.oldPage);
    
    //If event.detail.oldPage is not working then go with custom logic 
    //if (this.currentSelectedPage)
    //console.log('Page changed Old:', this.currentSelectedPage.displayName);  
    //set changed page into existing variables
    //this.currentSelectedPage = event.detail.newPage;

      console.log('Page changed New:', this.currentSelectedPage.displayName);
});

Friday, January 13, 2023

How to cancel any running task by wait for sometime in C#

 Problem Statement: In some real time scenario, you may need to cancel some long running tasks in certain time interval and then proceed. 

Here in below example, i am calling some infinite time method and am not sure when it will be completed. So i am making 30 seconds maximum to wait and cancelling it. 

RunSomeTestJob();

 

string RunSomeTestJob()

{

    string result = "";

 

    //loop your logic

 

    try

    {

        Console.WriteLine("Running Job Started " + DateTime.Now.ToString());

        // Create CancellationTokenSource.

        var source = new CancellationTokenSource();

        // ... Get Token from source.

        var token = source.Token;

 

        var someTask = Task.Run(() =>

        {

            result = infinteJobWork(token);

 

        }, token);

 

        someTask.Wait(30 * 1000);

       //someTask.Dispose();

        source.Cancel();

 

    }

    catch (Exception ex)

    {

        //suppress error and proceed

        //log somewhere

    }

    Console.Write("Running Job Completed " + result + DateTime.Now.ToString());

 

    Console.Read();

 

    //proceed with next steps

 

    return result;

 

}

 

string infinteJobWork(CancellationToken token)

{

    //Short running Job - Fixed timing

    //for (int i = 0; i < 3; i++)

    {

        //Long running Job - Indefinite time

        while (true)

        {

            //TODO: make some api call or some work to external api

            Console.WriteLine("Running Job : " + DateTime.Now.ToString());

            Thread.Sleep(5 * 1000);

 

            // See if we are canceled from our CancellationTokenSource.

            if (token.IsCancellationRequested)

            {

                Console.WriteLine("Job cancelled");

                return "Job cancelled";

            }

        }

    }

    //return "Job done";

}