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:



Friday, December 5, 2025

All bisect functions in Python

 Here’s a clean, practical tour of all bisect functions in Python – with code and scenario-based examples.

We’ll cover:

  • bisect_left

  • bisect_right (same as bisect)

  • insort_left

  • insort_right (same as insort)

All of these work on sorted lists. If the list is not sorted, results are wrong.


1. Basic idea: using bisect_left and bisect_right

from bisect import bisect_left, bisect_right

scores = [10, 20, 20, 20, 30, 40]  # sorted list

x = 20

pos_left = bisect_left(scores, x)
pos_right = bisect_right(scores, x)

print("scores:", scores)
print("bisect_left(20)  ->", pos_left)   # first position where 20 can go (leftmost)
print("bisect_right(20) ->", pos_right)  # position after the last 20 (rightmost+1)

Output (conceptually):

  • bisect_left(20)1

  • bisect_right(20)4

When to use which?

  • bisect_left(a, x)

    • Think: “insert before existing equals”

    • Good for lower bound, “first ≥ x”

  • bisect_right(a, x) / bisect(a, x)

    • Think: “insert after existing equals”

    • Good for upper bound, “first > x”


2. Scenario 1 – Grade boundaries (using bisect_right)

You have percentage marks, and you want to map them to grades based on boundary cutoffs.

from bisect import bisect_right

# boundaries: marks at which grade changes
boundaries = [40, 60, 75, 90]  # must be sorted
grades = ["F", "C", "B", "A", "A+"]  # one more than boundaries

def get_grade(score):
    idx = bisect_right(boundaries, score)
    return grades[idx]

for s in [35, 40, 59, 60, 74, 75, 89, 90, 99]:
    print(f"{s} -> {get_grade(s)}")

Logic:

  • bisect_right(boundaries, score) returns how many boundaries the score crosses.

  • We use that number as the index in grades.


3. Scenario 2 – Find position to insert (using bisect_left)

You want to place a new value in a sorted list but without actually inserting – just find where it would go.

from bisect import bisect_left

data = [3, 5, 8, 12, 15]

def find_insert_position(sorted_list, value):
    pos = bisect_left(sorted_list, value)
    return pos

for v in [1, 5, 7, 20]:
    pos = find_insert_position(data, v)
    print(f"Value {v} should go at index {pos} in {data}")

Use this when you just need the index, e.g., to split a list, or for binary search style lookup.


4. Inserting while keeping the list sorted – insort_left & insort_right

These are like bisect_... + list.insert(...) combined.

from bisect import insort_left, insort_right

nums = [10, 20, 20, 30]

print("Original:", nums)

# Insert with insort_left (before existing equals)
insort_left(nums, 20)
print("After insort_left(20): ", nums)

# Insert with insort_right (after existing equals)
insort_right(nums, 20)
print("After insort_right(20):", nums)

Behavior:

  • insort_left(a, x)
    Insert x at the position returned by bisect_left(a, x) (before equals)

  • insort_right(a, x) / insort(a, x)
    Insert x at the position returned by bisect_right(a, x) (after equals)


5. Scenario 3 – Maintaining a sorted list (online data)

Imagine you get sensor readings one by one, and you want to keep them in sorted order to quickly get median or percentiles.

from bisect import insort

readings = []

def add_reading(value):
    # insort == insort_right
    insort(readings, value)

def get_median():
    n = len(readings)
    if n == 0:
        return None
    mid = n // 2
    if n % 2 == 1:
        return readings[mid]
    else:
        return (readings[mid - 1] + readings[mid]) / 2

for r in [10, 5, 8, 15, 3, 12]:
    add_reading(r)
    print("After adding", r, "=> readings:", readings, "median:", get_median())

Here:

  • New values are inserted in O(n) time but still using binary search internally for the position.

  • Lookup for median is O(1) once sorted.


6. Scenario 4 – Counting elements in a range

Given a sorted list, how many values fall between low and high?

from bisect import bisect_left, bisect_right

data = [2, 4, 4, 4, 7, 9, 10, 10, 15]  # sorted

def count_in_range(sorted_list, low, high):
    # first index with value >= low
    left = bisect_left(sorted_list, low)
    # first index with value > high
    right = bisect_right(sorted_list, high)
    return right - left

print(count_in_range(data, 4, 10))   # how many values between 4 and 10 inclusive?
print(count_in_range(data, 5, 9))    # values between 5 and 9
print(count_in_range(data, 0, 100))  # all values

Key idea:

  • left = position of first value ≥ low

  • right = position of first value > high

  • count = right - left


7. Scenario 5 – Implementing your own binary search using bisect_left

You can use bisect_left as a helper to implement “does this value exist?” in a sorted list.

from bisect import bisect_left

def contains(sorted_list, value):
    i = bisect_left(sorted_list, value)
    # i is index where value *should* be inserted to stay sorted
    if i != len(sorted_list) and sorted_list[i] == value:
        return True
    return False

arr = [1, 3, 4, 7, 9, 11]

for v in [3, 5, 11, 12]:
    print(f"{v} exists? -> {contains(arr, v)}")

8. Quick summary of all bisect functions

from bisect import (
    bisect_left,
    bisect_right,  # same as bisect
    bisect,        # alias of bisect_right
    insort_left,
    insort_right,  # same as insort
    insort,        # alias of insort_right
)
  • Search / index only

    • bisect_left(a, x) → index of first element ≥ x

    • bisect_right(a, x) / bisect(a, x) → index of first element > x

  • Insert while keeping list sorted

    • insort_left(a, x) → insert at position bisect_left(a, x)

    • insort_right(a, x) / insort(a, x) → insert at position bisect_right(a, x)

All of them assume a is already sorted.



Tuesday, November 4, 2025

How to Upload User Profile Photos to Azure AD (Microsoft Entra ID) Using C# and Microsoft Graph API

How to Upload User Profile Photos to Azure AD (Microsoft Entra ID) Using C# and Microsoft Graph API

// To DO:
// Go to Azure Portal → Microsoft Entra ID → App registrations
// Find your app:
// Go to API permissions
// Check if you have: Microsoft Graph → User.ReadWrite.All (Application permission)
// If missing, click Add a permission → Microsoft Graph → Application permissions → Search and add User.ReadWrite.All
// Click "Grant admin consent" - This is crucial!

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;

namespace AzureADPhotoUploader;

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            Console.WriteLine("Azure AD Photo Uploader");
            Console.WriteLine("=======================\n");

            // Load configuration
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            var tenantId = configuration["AzureAd:TenantId"];
            var clientId = configuration["AzureAd:ClientId"];
            var clientSecret = configuration["AzureAd:ClientSecret"];

            if (string.IsNullOrEmpty(tenantId) || string.IsNullOrEmpty(clientId))
            {
                Console.WriteLine("Error: Azure AD configuration is missing. Please check appsettings.json");
                return;
            }

            // Initialize Graph Client with appropriate authentication
            Console.WriteLine("Initializing Microsoft Graph client...");
            GraphServiceClient graphClient = CreateGraphClient(tenantId, clientId, clientSecret);
            Console.WriteLine("✓ Graph client initialized\n");

            // Get user ID or UPN to upload photo
            Console.Write("Enter user ID or User Principal Name (UPN): ");
            var userId = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(userId))
            {
                Console.WriteLine("Error: User ID or UPN is required.");
                return;
            }

            // Get photo file path
            Console.Write("Enter the full path to the photo file (JPG/PNG): ");
            var photoPath = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(photoPath) || !File.Exists(photoPath))
            {
                Console.WriteLine("Error: Photo file not found.");
                return;
            }

            // Upload the photo
            await UploadUserPhoto(graphClient, userId, photoPath);

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\nUnexpected error: {ex.Message}");
            Console.WriteLine($"Stack trace: {ex.StackTrace}");
        }
    }

    /// <summary>
    /// Creates a GraphServiceClient with appropriate authentication method
    /// Uses ClientSecretCredential for service principal authentication
    /// For production, consider using Managed Identity when hosted in Azure
    /// </summary>
    static GraphServiceClient CreateGraphClient(string tenantId, string clientId, string? clientSecret)
    {
        // Use ClientSecretCredential for daemon/service applications
        // For interactive user applications, use InteractiveBrowserCredential
        // For Azure-hosted apps, use DefaultAzureCredential (Managed Identity)
       
        if (!string.IsNullOrEmpty(clientSecret))
        {
            // Service Principal authentication (daemon apps)
            var clientSecretCredential = new ClientSecretCredential(
                tenantId,
                clientId,
                clientSecret
            );
           
            return new GraphServiceClient(clientSecretCredential);
        }
        else
        {
            // Interactive Browser authentication (user apps)
            Console.WriteLine("Using interactive browser authentication...");
            var interactiveBrowserCredential = new InteractiveBrowserCredential(
                new InteractiveBrowserCredentialOptions
                {
                    TenantId = tenantId,
                    ClientId = clientId,
                    RedirectUri = new Uri("http://localhost")
                }
            );
           
            return new GraphServiceClient(interactiveBrowserCredential);
        }
    }

    /// <summary>
    /// Uploads a photo to a user's Azure AD profile
    /// </summary>
    /// <param name="graphClient">The authenticated Graph Service Client</param>
    /// <param name="userId">User ID or User Principal Name (UPN)</param>
    /// <param name="photoPath">Full path to the photo file</param>
    static async Task UploadUserPhoto(GraphServiceClient graphClient, string userId, string photoPath)
    {
        try
        {
            Console.WriteLine($"\nUploading photo for user: {userId}");
            Console.WriteLine($"Photo file: {photoPath}");

            // Validate file size (Azure AD supports photos up to 4MB for user profiles)
            var fileInfo = new FileInfo(photoPath);
            Console.WriteLine($"File size: {fileInfo.Length / 1024.0:F2} KB");
           
            if (fileInfo.Length > 4 * 1024 * 1024)
            {
                Console.WriteLine("Error: Photo file size exceeds 4MB limit.");
                return;
            }

            // Validate file type
            var extension = Path.GetExtension(photoPath).ToLowerInvariant();
            Console.WriteLine($"File extension: {extension}");
           
            if (extension != ".jpg" && extension != ".jpeg" && extension != ".png")
            {
                Console.WriteLine("Error: Only JPG and PNG formats are supported.");
                return;
            }

            // First, try to verify the user exists
            try
            {
                Console.WriteLine("\nVerifying user exists...");
                var user = await graphClient.Users[userId].GetAsync();
                Console.WriteLine($"✓ User found: {user?.DisplayName} ({user?.UserPrincipalName})");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Could not verify user: {ex.Message}");
                Console.WriteLine("Continuing with photo upload anyway...");
            }

            // Read the photo file
            Console.WriteLine("\nReading photo file...");
            using var photoStream = File.OpenRead(photoPath);
            Console.WriteLine($"Photo stream length: {photoStream.Length} bytes");
           
            // Upload the photo
            // The Graph API expects the photo content in the request body
            Console.WriteLine("Uploading to Microsoft Graph API...");
            await graphClient.Users[userId].Photo.Content
                .PutAsync(photoStream);

            Console.WriteLine("✓ Photo uploaded successfully!");

            // Optional: Verify the upload by retrieving photo metadata
            var photoMetadata = await graphClient.Users[userId].Photo.GetAsync();
            if (photoMetadata != null)
            {
                Console.WriteLine($"\nPhoto Details:");
                Console.WriteLine($"  Height: {photoMetadata.Height}px");
                Console.WriteLine($"  Width: {photoMetadata.Width}px");
            }
        }
        catch (Microsoft.Graph.Models.ODataErrors.ODataError odataError)
        {
            Console.WriteLine($"\nGraph API Error: {odataError.Error?.Message}");
            Console.WriteLine($"Code: {odataError.Error?.Code}");
           
            // Display additional error details
            if (odataError.Error?.InnerError != null)
            {
                Console.WriteLine($"Inner Error: {odataError.Error.InnerError.AdditionalData}");
            }
           
            if (odataError.ResponseStatusCode > 0)
            {
                Console.WriteLine($"HTTP Status Code: {odataError.ResponseStatusCode}");
            }
           
            // Provide specific guidance based on error code
            if (odataError.Error?.Code == "Authorization_RequestDenied")
            {
                Console.WriteLine("\nTip: Ensure your app registration has 'User.ReadWrite.All' permission");
                Console.WriteLine("and that admin consent has been granted.");
            }
            else if (odataError.Error?.Code == "UnknownError")
            {
                Console.WriteLine("\nPossible causes:");
                Console.WriteLine("1. The photo size might be incompatible (try resizing to 648x648 pixels)");
                Console.WriteLine("2. Missing API permissions - ensure 'User.ReadWrite.All' is granted");
                Console.WriteLine("3. The user might not exist or the UPN is incorrect");
                Console.WriteLine("4. The app might not have admin consent");
                Console.WriteLine("5. The photo stream might be corrupted or in an unsupported format");
            }
           
            // Display full exception for debugging
            Console.WriteLine($"\nFull error details: {odataError}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\nError uploading photo: {ex.Message}");
            Console.WriteLine($"Exception type: {ex.GetType().Name}");
            Console.WriteLine($"Stack trace: {ex.StackTrace}");
        }
    }
}



Friday, October 24, 2025

Important links

Important Links

Node Download: https://nodejs.org/en/download 
Nvm-Windows: https://github.com/coreybutler/nvm-windows?tab=readme-ov-file 
n8n Webpage: https://n8n.io/ 
n8n on Github: https://github.com/n8n-io/n8n 
Self Hostung on Render: https://render.com/ 
Deepseek: https://www.deepseek.com/ 
Groq: https://groq.com/ 
OpenAI Playground: https://platform.openai.com/playground 
Anthripic (Claude) Models: https://docs.anthropic.com/en/docs/about-claude/models 
Anthropic (Claude) API: https://console.anthropic.com/dashboard 
Google AI Studio (Gemini API): https://aistudio.google.com/prompts/new_chat 
FB Developers: https://developers.facebook.com/ 
Google Claude Console: https://console.cloud.google.com/ 
Pinecone (Vectorstore): https://www.pinecone.io/ 
Ollama: https://ollama.com/ 
Bot Father (Telegram API Key): https://telegram.me/BotFather 
Firecrawl: https://www.firecrawl.dev/ 
Julia: https://discourse.julialang.org/t/including-raw-html-in-julia-markdown/26165 
PDF to Markdown (online): https://pdf2md.morethan.io/ 
Llamaindex with LlamaParse (online): https://cloud.llamaindex.ai/ 
PDFs for RAG on Github: https://github.com/run-llama/llama_parse 
Colab Notebook (Llama_parse): https://colab.research.google.com/drive/1PXpCEt4QaLN7PQk-d1irliWBsVYMQl5?usp=sharing 
N8n License: https://docs.n8n.io/sustainable-use-license/#what-is-and-isnt-allowedunder-the-license-in-the-context-of-n8ns-product 
GDPR: https://dsgvo-gesetz.de/ 
OpenAI API for GDPR: https://openai.com/index/introducing-data-residency-ineurope/ 
AI-Act: https://artificialintelligenceact.eu/de/ 
LLM Leaderboard: https://lmarena.ai/

Software to create Automation and Agents: 
https://zapier.com/ 
https://www.make.com/en 
https://n8n.io/ 
https://www.langchain.com/ 
https://www.langchain.com/langgraph 
https://www.langflow.org/ 
https://flowiseai.com/ 
https://microsoft.github.io/autogen/stable/ 
https://vectorshift.ai/ 
https://www.voiceflow.com/ 
https://www.crewai.com/ 
https://github.com/openai/swarm 
https://botpress.com/

Thursday, October 23, 2025

Azure Cache for Redis CRUD (Create, Read, Update, Delete) operations

Azure Cache for Redis CRUD (Create, Read, Update, Delete) operations:

Azure Cache for Redis facilitates standard CRUD (Create, Read, Update, Delete) operations on data stored in memory. These operations are performed using Redis commands, which can be executed through various client libraries or directly via the Redis Console in the Azure portal.

1. Create (Set):
To create or add data to the cache, the SET command is typically used. This command associates a key with a value.
Code: 
    SET mykey "myvalue"

2. Read (Get):
To retrieve data from the cache, the GET command is used, specifying the key of the desired value.
Code:
    GET mykey

3. Update (Set/Incr/HSet):
Updating data can involve overwriting an existing value with SET, incrementing a numerical value with INCR (for integers), or modifying specific fields within a hash with HSET.
Code: 
    SET mykey "newvalue"  // Overwrite
    INCR counterkey      // Increment a numerical value
    HSET user:1 name "Alice" age 30 // Update fields in a hash

4. Delete (Del):
To remove data from the cache, the DEL command is used, specifying one or more keys to be deleted.
Code: 
    DEL mykey
    DEL key1 key2 key3

Data Types:
Redis supports various data types beyond simple strings, including hashes, lists, sets, and sorted sets, each with specific commands for performing CRUD-like operations on their respective structures. For example, LPUSH and RPUSH for lists, SADD for sets, and ZADD for sorted sets are used to add elements, while LPOP, RPOP, SREM, and ZREM are used to remove elements.

Python:
"""
pip install redis
py azure_redis_cache.py
Azure Redis Cache - Get and Set Methods
Simple example demonstrating connection and basic operations with Azure Redis Cache
"""

import redis
import json
from typing import Optional, Any

# Redis connection string
REDIS_CONNECTION_STRING = "myazurerediscache.redis.cache.windows.net:6380,password=password=,ssl=True,abortConnect=False"


class AzureRedisCache:
    """Azure Redis Cache client wrapper"""
   
    def __init__(self, connection_string: str):
        """
        Initialize Redis connection
       
        Args:
            connection_string: Redis connection string
        """
        # Parse connection string
        params = {}
        for param in connection_string.split(','):
            if '=' in param:
                key, value = param.split('=', 1)
                params[key.strip()] = value.strip()
            else:
                # First part is host:port
                host_port = param.split(':')
                params['host'] = host_port[0]
                params['port'] = int(host_port[1])
       
        # Create Redis client
        self.client = redis.StrictRedis(
            host=params.get('host'),
            port=params.get('port', 6380),
            password=params.get('password'),
            ssl=params.get('ssl', 'True').lower() == 'true',
            decode_responses=True
        )
       
        print(f"✓ Connected to Redis: {params.get('host')}")
   
    def set_value(self, key: str, value: Any, expiration: Optional[int] = None) -> bool:
        """
        Set a value in Redis cache
       
        Args:
            key: Cache key
            value: Value to store (will be JSON serialized if not a string)
            expiration: Optional expiration time in seconds
           
        Returns:
            True if successful, False otherwise
        """
        try:
            # Convert value to string if it's not already
            if not isinstance(value, str):
                value = json.dumps(value)
           
            if expiration:
                result = self.client.setex(key, expiration, value)
            else:
                result = self.client.set(key, value)
           
            print(f"✓ Set key '{key}' = '{value}'" + (f" (expires in {expiration}s)" if expiration else ""))
            return bool(result)
        except Exception as e:
            print(f"✗ Error setting key '{key}': {str(e)}")
            return False
   
    def get_value(self, key: str) -> Optional[Any]:
        """
        Get a value from Redis cache
       
        Args:
            key: Cache key
           
        Returns:
            Value if found, None otherwise
        """
        try:
            value = self.client.get(key)
            if value is None:
                print(f"✗ Key '{key}' not found")
                return None
           
            # Try to parse as JSON, otherwise return as string
            try:
                value = json.loads(value)
            except (json.JSONDecodeError, TypeError):
                pass
           
            print(f"✓ Get key '{key}' = '{value}'")
            return value
        except Exception as e:
            print(f"✗ Error getting key '{key}': {str(e)}")
            return None
   
    def delete_key(self, key: str) -> bool:
        """
        Delete a key from Redis cache
       
        Args:
            key: Cache key to delete
           
        Returns:
            True if key was deleted, False otherwise
        """
        try:
            result = self.client.delete(key)
            if result:
                print(f"✓ Deleted key '{key}'")
            else:
                print(f"✗ Key '{key}' not found")
            return bool(result)
        except Exception as e:
            print(f"✗ Error deleting key '{key}': {str(e)}")
            return False
   
    def key_exists(self, key: str) -> bool:
        """
        Check if a key exists in Redis cache
       
        Args:
            key: Cache key
           
        Returns:
            True if key exists, False otherwise
        """
        try:
            exists = self.client.exists(key)
            print(f"✓ Key '{key}' exists: {bool(exists)}")
            return bool(exists)
        except Exception as e:
            print(f"✗ Error checking key '{key}': {str(e)}")
            return False
   
    def ping(self) -> bool:
        """
        Test connection to Redis
       
        Returns:
            True if connection is successful, False otherwise
        """
        try:
            result = self.client.ping()
            print(f"✓ Ping successful: {result}")
            return result
        except Exception as e:
            print(f"✗ Ping failed: {str(e)}")
            return False


def main():
    """Main function demonstrating Redis operations"""
   
    print("=" * 60)
    print("Azure Redis Cache - Get and Set Demo")
    print("=" * 60)
    print()
   
    # Initialize Redis client
    cache = AzureRedisCache(REDIS_CONNECTION_STRING)
   
    # Test connection
    print("\n--- Testing Connection ---")
    cache.ping()
   
    # Example 1: Set and get a simple string
    print("\n--- Example 1: Simple String ---")
    cache.set_value("greeting", "Hello, Azure Redis!")
    cache.get_value("greeting")
   
    # Example 2: Set and get a JSON object
    print("\n--- Example 2: JSON Object ---")
    user_data = {
        "name": "John Doe",
        "email": "john.doe@example.com",
        "age": 30
    }
    cache.set_value("user:1001", user_data)
    retrieved_user = cache.get_value("user:1001")
   
    # Example 3: Set with expiration (10 seconds)
    print("\n--- Example 3: Value with Expiration ---")
    cache.set_value("temp_token", "abc123xyz", expiration=10)
    cache.get_value("temp_token")
   
    # Example 4: Check if key exists
    print("\n--- Example 4: Check Key Existence ---")
    cache.key_exists("greeting")
    cache.key_exists("nonexistent_key")
   
    # Example 5: Delete a key
    print("\n--- Example 5: Delete Key ---")
    cache.delete_key("greeting")
    cache.get_value("greeting")  # Should return None
   
    print("\n" + "=" * 60)
    print("Demo completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()


Output:































C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Redis;
using Newtonsoft.Json;

namespace AzureRedisCacheDemo
{
    /// <summary>
    /// Azure Redis Cache client wrapper
    /// </summary>
    public class AzureRedisCache : IDisposable
    {
        private readonly ConnectionMultiplexer _connection;
        private readonly IDatabase _db;
        private readonly string _host;

        /// <summary>
        /// Initialize Redis connection
        /// </summary>
        /// <param name="connectionString">Redis connection string</param>
        public AzureRedisCache(string connectionString)
        {
            // Parse connection string
            var parameters = ParseConnectionString(connectionString);
            _host = parameters["host"];

            // Create configuration options
            var configOptions = new ConfigurationOptions
            {
                EndPoints = { $"{parameters["host"]}:{parameters["port"]}" },
                Password = parameters["password"],
                Ssl = parameters.GetValueOrDefault("ssl", "true").Equals("true", StringComparison.OrdinalIgnoreCase),
                AbortOnConnectFail = parameters.GetValueOrDefault("abortConnect", "false").Equals("true", StringComparison.OrdinalIgnoreCase)
            };

            // Create Redis connection
            _connection = ConnectionMultiplexer.Connect(configOptions);
            _db = _connection.GetDatabase();

            Console.WriteLine($"✓ Connected to Redis: {_host}");
        }

        /// <summary>
        /// Parse connection string into parameters
        /// </summary>
        private Dictionary<string, string> ParseConnectionString(string connectionString)
        {
            var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            var parts = connectionString.Split(',');

            foreach (var part in parts)
            {
                var trimmedPart = part.Trim();
                if (trimmedPart.Contains('='))
                {
                    var keyValue = trimmedPart.Split(new[] { '=' }, 2);
                    parameters[keyValue[0].Trim()] = keyValue[1].Trim();
                }
                else
                {
                    // First part is host:port
                    var hostPort = trimmedPart.Split(':');
                    parameters["host"] = hostPort[0];
                    parameters["port"] = hostPort.Length > 1 ? hostPort[1] : "6380";
                }
            }

            return parameters;
        }

        /// <summary>
        /// Set a value in Redis cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <param name="value">Value to store</param>
        /// <param name="expiration">Optional expiration time in seconds</param>
        /// <returns>True if successful, false otherwise</returns>
        public bool SetValue(string key, object value, int? expiration = null)
        {
            try
            {
                // Convert value to string
                string stringValue = value is string str ? str : JsonConvert.SerializeObject(value);

                // Set with or without expiration
                bool result;
                if (expiration.HasValue)
                {
                    result = _db.StringSet(key, stringValue, TimeSpan.FromSeconds(expiration.Value));
                    Console.WriteLine($"✓ Set key '{key}' = '{stringValue}' (expires in {expiration}s)");
                }
                else
                {
                    result = _db.StringSet(key, stringValue);
                    Console.WriteLine($"✓ Set key '{key}' = '{stringValue}'");
                }

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error setting key '{key}': {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Get a value from Redis cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <returns>Value if found, null otherwise</returns>
        public string GetValue(string key)
        {
            try
            {
                var value = _db.StringGet(key);
                if (value.IsNullOrEmpty)
                {
                    Console.WriteLine($"✗ Key '{key}' not found");
                    return null;
                }

                string stringValue = value.ToString();
                Console.WriteLine($"✓ Get key '{key}' = '{stringValue}'");
                return stringValue;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error getting key '{key}': {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// Get a value and deserialize to type T
        /// </summary>
        public T GetValue<T>(string key)
        {
            try
            {
                var value = GetValue(key);
                if (value == null) return default(T);

                // Try to deserialize as JSON
                try
                {
                    return JsonConvert.DeserializeObject<T>(value);
                }
                catch
                {
                    // If deserialization fails, try to cast directly
                    return (T)Convert.ChangeType(value, typeof(T));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error deserializing key '{key}': {ex.Message}");
                return default(T);
            }
        }

        /// <summary>
        /// Delete a key from Redis cache
        /// </summary>
        /// <param name="key">Cache key to delete</param>
        /// <returns>True if key was deleted, false otherwise</returns>
        public bool DeleteKey(string key)
        {
            try
            {
                bool result = _db.KeyDelete(key);
                if (result)
                {
                    Console.WriteLine($"✓ Deleted key '{key}'");
                }
                else
                {
                    Console.WriteLine($"✗ Key '{key}' not found");
                }
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error deleting key '{key}': {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Check if a key exists in Redis cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <returns>True if key exists, false otherwise</returns>
        public bool KeyExists(string key)
        {
            try
            {
                bool exists = _db.KeyExists(key);
                Console.WriteLine($"✓ Key '{key}' exists: {exists}");
                return exists;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error checking key '{key}': {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Test connection to Redis
        /// </summary>
        /// <returns>True if connection is successful, false otherwise</returns>
        public bool Ping()
        {
            try
            {
                var endPoint = _connection.GetEndPoints().First();
                var server = _connection.GetServer(endPoint);
                var latency = server.Ping();
                Console.WriteLine($"✓ Ping successful: {latency.TotalMilliseconds}ms");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Ping failed: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Dispose connection
        /// </summary>
        public void Dispose()
        {
            _connection?.Dispose();
        }
    }

    /// <summary>
    /// User data model for demonstration
    /// </summary>
    public class UserData
    {
        public string Name { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public int Age { get; set; }
    }

    class Program
    {
        // Redis connection string
        const string REDIS_CONNECTION_STRING = "myazurerediscache.redis.cache.windows.net:6380,password=password=,ssl=True,abortConnect=False";

        static void Main(string[] args)
        {
            Console.WriteLine("============================================================");
            Console.WriteLine("Azure Redis Cache - Get and Set Demo (C#)");
            Console.WriteLine("============================================================");
            Console.WriteLine();

            using (var cache = new AzureRedisCache(REDIS_CONNECTION_STRING))
            {
                // Test connection
                Console.WriteLine("\n--- Testing Connection ---");
                cache.Ping();

                // Example 1: Set and get a simple string
                Console.WriteLine("\n--- Example 1: Simple String ---");
                cache.SetValue("greeting", "Hello, Azure Redis!");
                cache.GetValue("greeting");

                // Example 2: Set and get a JSON object
                Console.WriteLine("\n--- Example 2: JSON Object ---");
                var userData = new UserData
                {
                    Name = "John Doe",
                    Email = "john.doe@example.com",
                    Age = 30
                };
                cache.SetValue("user:1001", userData);
                var retrievedUser = cache.GetValue<UserData>("user:1001");
                if (retrievedUser != null)
                {
                    Console.WriteLine($"  Retrieved: {retrievedUser.Name}, {retrievedUser.Email}, Age: {retrievedUser.Age}");
                }

                // Example 3: Set with expiration (10 seconds)
                Console.WriteLine("\n--- Example 3: Value with Expiration ---");
                cache.SetValue("temp_token", "abc123xyz", expiration: 10);
                cache.GetValue("temp_token");

                // Example 4: Check if key exists
                Console.WriteLine("\n--- Example 4: Check Key Existence ---");
                cache.KeyExists("greeting");
                cache.KeyExists("nonexistent_key");

                // Example 5: Delete a key
                Console.WriteLine("\n--- Example 5: Delete Key ---");
                cache.DeleteKey("greeting");
                cache.GetValue("greeting"); // Should return null

                Console.WriteLine("\n============================================================");
                Console.WriteLine("Demo completed!");
                Console.WriteLine("============================================================");
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}


Output:





































Featured Post

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...

Popular posts