Wednesday, 31 December 2025

Azure Function - In-process model vs Isolated worker model

 In-process model

  • Your function code runs inside the same process as the Azure Functions runtime
  • Uses the WebJobs SDK.

[FunctionName("TimetriggerFunction")]

What this means

  • Used in:

    • Azure Functions v1–v4 (in-process)

  • Namespace: Microsoft.Azure.WebJobs

  • Runs inside the same process as the Azure Functions runtime

  • Uses:

    • ILogger for logging

    • TimerInfo from Microsoft.Azure.WebJobs

Characteristics

  • Tight coupling to the Functions runtime

  • Faster startup (historically)

  • More magic / implicit behavior

  • Not recommended for new apps going forward


2. Isolated worker model

  • Your function runs in a separate .NET process from the Azure Functions runtime.
  • Communicates with the runtime over gRPC.

[Function("TimetriggerFunction")]

What this means

  • Used in:

    • Azure Functions v4+ isolated worker

  • Namespace: Microsoft.Azure.Functions.Worker

  • Runs in a separate .NET process from the runtime

  • Uses:

    • FunctionContext instead of ILogger

    • Logging via context.GetLogger(...)


Characteristics

  • Decoupled from the Functions runtime

  • Better:

    • Dependency injection

    • Versioning control

    • Middleware support

  • Required for:

    • .NET 8

    • Future Azure Functions development

Key Differences at a Glance

Feature

[FunctionName]

[Function]

Hosting model

In-process

Isolated worker

Runtime coupling

Tight

Loose

Logging

ILogger

FunctionContext

Namespace

WebJobs

Functions.Worker

.NET 8 support

No

Yes

Recommended for new apps

No

Yes


Summary

In-process = older, tightly coupled, simpler
Isolated worker = modern, decoupled, flexible, future-proof

Wednesday, 2 July 2025

How to get PowerBI Embed Token

 Here's a step-by-step guide to help you through the process.

Step 1: Register Your App in Azure

  • 1. Go to Azure Portal → App registrations
  • 2. Register a new app.
  • 3. Provide necessary API permissions
  • 4. Go to Certificates & secrets → Generate a Client Secret






 




Step 2: Assign the App to the Power BI Workspace

1. Go to Power BI Service
2. Click Workspace access
3. Add the App's Service Principal(App Registration ClientId) as an Admin or Member














Step 3: Get Access Token 

Request:

 Method: POST
 URL: https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token

 

Headers:
Content-Type: application/x-www-form-urlencoded 

Body: (x-www-form-urlencoded):

grant_type=client_credentials
client_id={your-client-id}
client_secret={your-client-secret}
scope=https://analysis.windows.net/powerbi/api/.default
















Endpoint will provide you with an Access Token












Step 4: Generate the Embed Token


URL: Post Endpoint 

https://api.powerbi.com/v1.0/myorg/groups/{groupId}/reports/{reportId}/GenerateToken


Headers

Authorization: Bearer <access_token>
Content-Type: application/json

Body

{
  "accessLevel": "View"
}









 

Sample Code to embed the PowerBI Report in an HTML Page



<script src="https://cdn.jsdelivr.net/npm/powerbi-client@2.21.1/dist/powerbi.min.js"></script>

<style>
    #reportContainer {
      width: 100%;
      height: 800px;
      border: 1px solid #ccc;
    }
  </style>

<div id="reportContainer"></div>

<script>
  
    const embedToken = "Call the APIs and pass the token here";
    
    const embedUrl = "https://app.powerbi.com/reportEmbed?reportId=report id here&groupId=group id here";

    const reportId = "your report Id here";

    // Embed configuration
    const config = {
        type: 'report',
        id: reportId,
        embedUrl: embedUrl,
        accessToken: embedToken,
        tokenType: window['powerbi-client'].models.TokenType.Embed,
        settings: {
            filterPaneEnabled: false,
            navContentPaneEnabled: true
        }
    };

    const reportContainer = document.getElementById('reportContainer');

    // Embed the report
    const powerbi = new window['powerbi-client'].service.Service(
        window['powerbi-client'].factories.hpmFactory,
        window['powerbi-client'].factories.wpmpFactory,
        window['powerbi-client'].factories.routerFactory
    );

    powerbi.embed(reportContainer, config);
</script>


Power BI - PowerBIEntityNotFound Error in Embed Report

Typically, PowerBIEntityNotFound indicates that the requested resource (report, dataset, or workspace) could not be found under the access token's permissions. 



{
    "error": {
        "code": "PowerBIEntityNotFound",
        "pbi.error": {
            "code": "PowerBIEntityNotFound",
            "parameters": {},
            "details": [],
            "exceptionCulprit": 1
        }
    }
}


You need to check a couple of things.

1. Ensure the workspace GUID is accurate. 


You can find it in the URL when viewing a report:
https://app.powerbi.com/groups/{workspace-id}/reports/{report-id}

2. Is the Report ID correct?

    same steps as above.

3. Does the service principal have access?

Your Azure AD app (service principal) must be added to the workspace as a member or admin:

Go to Power BI Service → Workspace → Access
















Add the service principal (client ID) as a Member or Admin

























4. Ensure service principal access is enabled in tenant settings


In Power BI Admin Portal: Go to Tenant settings

Enable:
"Allow service principals to use Power BI APIs"
"Allow service principals to create embed tokens."

5. Ensure you are using the correct scope and authority in the token request.

SCOPE = "https://analysis.windows.net/powerbi/api/.default"

Check all the above steps, and it will resolve the issue.

Wednesday, 25 June 2025

Create an Azure AD B2C (ADB2C) user using Postman

 Here's a step-by-step guide to help you through the process.

Registered App in Azure AD B2C with:

  • Delegated Microsoft Graph API permissions:
    • User.ReadWrite.All
    • Directory.ReadWrite.All
  • Client secret
  • Admin Consent granted for permissions







 



Step 1: Get Access Token 

Request:

 Method: POST
 URL: https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token

 

Headers:
Content-Type: application/x-www-form-urlencoded 

Body: (x-www-form-urlencoded):

grant_type=client_credentials

client_id={your-client-id}

client_secret={your-client-secret}

scope=https://graph.microsoft.com/.default


















Endpoint will provide you with an Access Token












Step 2: Create a User

Request:

Method: POST
URL: https://graph.microsoft.com/v1.0/users

 

Headers:

Authorization: Bearer {access_token}

Content-Type: application/json

 

Body (raw JSON):

{  
  "displayName": "sunny setia",
  "givenName": "sunny27",
  "surname": "setia",
  "identities": [  
    {  
      "signInType": "emailAddress",  
      "issuer": "tssorg.onmicrosoft.com",  
      "issuerAssignedId": "setia27@mailinator.com"  
    }
  ],  
  "passwordProfile":{  
    "password": "P@ssword1",  
    "forceChangePasswordNextSignIn": false  
  },  
  "passwordPolicies": "DisablePasswordExpiration"  
}  















Important:

  • The Issuer must follow your B2C tenant domain.
  • Use a strong password that meets AAD complexity requirements.

 

 

Monday, 31 March 2025

Enum with Flag Attribute in .NET


In .NET, you can use the Flags attribute with an enum. You can combine multiple values into one to represent a set of bit fields. It is useful when you want to combine options or states using bitwise operations.

Here is an example of how to define and use an enum with the Flags attribute:

[Flags]
public enum BankruptcyStatus
{
    None = 0,              // No status
    Filing = 1,            // Bankruptcy is filed
    Reorganization = 2,    // Bankruptcy is under reorganization (Chapter 11, for example)
    Discharge = 4,         // Debts have been discharged (Chapter 7, for example)
    Closed = 8,            // Bankruptcy case is closed
    All = Filing | Reorganization | Discharge | Closed  // All possible statuses
}


class Program
{
    static void Main()
    {
        // Assigning multiple flags to a variable
        BankruptcyStatus currentStatus = BankruptcyStatus.Filing | BankruptcyStatus.Reorganization;

        Console.WriteLine($"Current Bankruptcy Status: {currentStatus}");

        // Checking if a specific status is active
        bool isFiling = (currentStatus & BankruptcyStatus.Filing) == BankruptcyStatus.Filing;
        Console.WriteLine($"Is filing in progress? {isFiling}");

        bool isReorganizing = (currentStatus & BankruptcyStatus.Reorganization) == BankruptcyStatus.Reorganization;
        Console.WriteLine($"Is bankruptcy under reorganization? {isReorganizing}");

        // Adding a new status (Discharge)
        currentStatus |= BankruptcyStatus.Discharge;
        Console.WriteLine($"Updated Bankruptcy Status: {currentStatus}");

        // Checking if discharge has occurred
        bool isDischarged = (currentStatus & BankruptcyStatus.Discharge) == BankruptcyStatus.Discharge;
        Console.WriteLine($"Has the bankruptcy been discharged? {isDischarged}");

        // Remove the 'Filing' status (assuming bankruptcy filing is no longer active)
        currentStatus &= ~BankruptcyStatus.Filing;
        Console.WriteLine($"Updated Bankruptcy Status after removing Filing: {currentStatus}");
    }
}

[Flags] Attribute: The Flags attribute indicates that the enum values are bit fields, and you can combine them using bitwise operations.

Enum Values:

  • Filing = 1: Represents the status of the bankruptcy being filed.

  • Reorganization = 2: Represents the status of a reorganization process, like Chapter 11.

  • Discharge = 4: Represents the status where debts are discharged, like in a Chapter 7 bankruptcy.

  • Closed = 8: Represents the bankruptcy case being closed.

Thursday, 5 September 2024

Implement Authorization in Swagger with Static Value in Header .Net 8

If you want an anonymous user should not run the APIs.
To run your API Endpoints From Swagger / Postman / Code the user should pass the header key. Follow the below steps.

We need to set up, AddSecurityDefinition and AddSecurityRequirement


Step 1: Open Program.cs, Copy and Paste code below


builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    // Add the security requirement
    c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
    {
        Name = "X-api-key",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Description = "API Key needed to access the endpoints."
    });
    // Apply the security requirement globally
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
     {
         {
             new OpenApiSecurityScheme
             {
                 Reference = new OpenApiReference
                 {
                     Type = ReferenceType.SecurityScheme,
                     Id = "ApiKey"
                 }
             },
             new string[] {}
         }
     });
});


Step 2: Create a new Middleware Class and call in the Program.cs


 public class ApiKeyMiddleware
 {
     private const string ApiKeyHeaderName = "X-api-key";
     private readonly RequestDelegate _next;
     private readonly string _apiKey;
     public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
     {
         _next = next;
         _apiKey = configuration["ApiKey"]; // Assuming you store the API key in your app settings
     }
     public async Task InvokeAsync(HttpContext context)
     {
         if (context.Request.Headers.TryGetValue(ApiKeyHeaderName, out var providedApiKey))
         {
             if (providedApiKey == _apiKey)
             {
                 await _next(context);
                 return;
             }
         }
         context.Response.StatusCode = StatusCodes.Status401Unauthorized;
         await context.Response.WriteAsync("Unauthorized");
     }
 }


Step 3: Copy these lines and paste the below lines into the Program.cs


app.UseMiddleware<ApiKeyMiddleware>();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();
app.Run();


Step 4: Add  ApiKey in appsettings.json

"ApiKey": "setia",


Step 5: Run the application and you will Notice you can see the Authorize button in the top right position on Swagger.










Step 6: On the Click of a button, it will ask you to enter the key here. It will match the key mentioned in the app settings.json
























Step 7: It will match the key mentioned in the app settings.json. If the passed key is incorrect or you run the endpoint without a key it will throw an 401 Error.





















You will get the response if the key is correct.




Thursday, 1 August 2024

Use ChatGPT API in a C# application to Read the Image

To use the ChatGPT API in a C# application, you'll follow below steps:

1. Set Up Your OpenAI Account

  1. Sign UpIf you haven't already done so, create an account on the Open AI Website.

  1. Get API KeyAfter logging in, go to the API section and generate an API key.


Once you have the ChatGPT API Key, copy the method below into your application and run. You need to pass 2 parameters.

1) API Key
2) Image Path

 I am using Model "gpt-4o" in the below code.

public static async Task<string> ReadImagefromChatGPTAsync()
  {
      var client = new HttpClient();
      string apiKey = "Your Key Here";
      string imgPath = "D:\\aaa.png"; // Image Path here
      string prompt = "Extract A1C Value and Date from Image";
      try
      {
          // Convert image to base64
          byte[] imageBytes = File.ReadAllBytes(imgPath);
          string base64Image = Convert.ToBase64String(imageBytes);
          string imageBase64Url = $"data:image/png;base64,{base64Image}";

          var requestContent = new
          {
              model = "gpt-4o",
              messages = new[]
              {
              new {
                  role = "user",
                  content = new object[]
                  {
                      new { type = "text", text = prompt },
                      new { type = "image_url", image_url = new { url = imageBase64Url } }
                  }
              }
          },
              max_tokens = 500
          };


          string jsonString = Newtonsoft.Json.Linq.JObject.FromObject(requestContent).ToString();
          var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
          client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
        
          var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
          var responseString = await response.Content.ReadAsStringAsync();
          ChatGPTResponseModel chatGPTResponse = null;
          chatGPTResponse = JsonConvert.DeserializeObject<ChatGPTResponseModel>(responseString);

          if (chatGPTResponse != null)
          {
              var message = chatGPTResponse.Choices?[0].Text;
              return await Task.Run<string>(() => { return string.Empty; });
          }
          return await Task.Run<string>(() => { return string.Empty; });
      }
      catch (Exception ex)
      {
          Console.WriteLine($"An error occurred: {ex.Message}");
          return await Task.Run<string>(() => { return string.Empty; });
      }
  }


Below are the models for Deserialize the response


 public class ChatGPTResponseModel
 {
     [JsonPropertyName("id")]
     public string Id { get; set; }

     [JsonPropertyName("object")]
     [SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "This is the name of the property returned by the API.")]
     public string @Object { get; set; }

     [JsonPropertyName("created")]
     public int Created { get; set; }

     [JsonPropertyName("model")]
     public string Model { get; set; }

     [JsonPropertyName("choices")]
     public List<ChatGPTChoice> Choices { get; set; }
 }


 [DebuggerDisplay("Text = {Text}")]
 public class ChatGPTChoice
 {
     [JsonPropertyName("text")]
     public string Text { get; set; }
    [JsonPropertyName("message")]
    public Message Message { get; set; }
 }

public class Message
{
    [JsonPropertyName("role")]
    public string Role { get; set; }

    [JsonPropertyName("conent")]
    public string Content { get; set; }
}

You can call your method like the one below in your main file.

 var output = await ReadImagefromChatGPTAsync();


This is all about this article. I hope you like it.

Use ChatGPT API in a C# application

 To use the ChatGPT API in a C# application, you'll follow below steps:

1. Set Up Your OpenAI Account

  1. Sign Up: If you haven't already done so, create an account on the Open AI Website.

  1. Get API Key: After logging in, go to the API section and generate an API key.


Once you have the ChatGPT API Key, copy the method below into your application and run. You need to pass 2 parameters.

1) API Key
2) Prompt


I am using Model "gpt-3.5-turbo-instruct", you can choose your model based on your requirements.



  private static async Task<string> GetResutlsFromChatGPT()
  {
      var apiKey = "Your Key here";
      var prompt = "Your prompt here";

      var chatGPTRequest = new
      {
          model = "gpt-3.5-turbo-instruct",
          temperature = 0.5f,
          max_tokens = 1000,
          top_p = 0.5f,
          frequency_penalty = 1.0f,
          presence_penalty = 0.0f,
          prompt = prompt
      };

      ChatGPTResponseModel chatGPTResponse = null;
      using (HttpClient httpClient = new HttpClient())
      {
          using (var httpReq = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/completions"))
          {
              httpReq.Headers.Add("Authorization", $"Bearer {apiKey}");
              string requestString = JsonConvert.SerializeObject(chatGPTRequest);
              httpReq.Content = new StringContent(requestString, Encoding.UTF8, "application/json");

              using (HttpResponseMessage httpResponse = await httpClient.SendAsync(httpReq))
              {
                  if (httpResponse.IsSuccessStatusCode)
                  {
                      string responseString = await httpResponse.Content.ReadAsStringAsync();
                      chatGPTResponse = JsonConvert.DeserializeObject<ChatGPTResponseModel>(responseString);
                      if (chatGPTResponse != null)
                      {
                          string completionText = chatGPTResponse.Choices?[0]?.Text;
                          return await Task.Run<string>(() => { return completionText ?? string.Empty; });
                      }
                  }
              }
          }
      }

      return await Task.Run(() => { return string.Empty; });
  }


Below are the models for Deserialize the response


 public class ChatGPTResponseModel
 {
     [JsonPropertyName("id")]
     public string Id { get; set; }

     [JsonPropertyName("object")]
     [SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "This is the name of the property returned by the API.")]
     public string @Object { get; set; }

     [JsonPropertyName("created")]
     public int Created { get; set; }

     [JsonPropertyName("model")]
     public string Model { get; set; }

     [JsonPropertyName("choices")]
     public List<ChatGPTChoice> Choices { get; set; }
 }


 [DebuggerDisplay("Text = {Text}")]
 public class ChatGPTChoice
 {
     [JsonPropertyName("text")]
     public string Text { get; set; }

 }


You can call your method like below in your main file.

 var output = await GetResutlsFromChatGPT();

This is all about this article. I hope you like it.



Thursday, 25 July 2024

AWS Elastic Beanstalk by Amazon Web Services

AWS Elastic Beanstalk is a Platform as a Service (PaaS) offered by Amazon Web Services. 

It simplifies deploying, managing, and scaling web applications and services. Here's a detailed overview: 


AWS Elastic Beanstalk supports web applications written in many popular languages and frameworks. It requires no or minimal code changes to go from the development machine to the cloud. Development options for deploying your web applications include Java, .NET, Node.js, PHP, Ruby, Python, Go, and Docker.

Let's deploy the .Net Application to EC2 via Elastic Beanstalk.

Step 1: Open the Visual Studio --> Go to Extensions --> Click on Manage Extensions
Step 2: Search for AWS Toolkit with Amazon Q Extension.
Step 3: Install the extension and restart the PC

Step 4: When you right-click on the Solution, you can see published with AWS options.















Step 5: Click on the Publish to AWS option. It will validate your AWS connection. If it is not connected, you need to enter AWS User credentials.

Step 6: You can choose the OS based on your app.














You can go to View Menu in Visual Studio and Click AWS Explorer to ensure you are connected with AWS. If you are not connected with AWS then get the access key from AWS Portal, Under users sections













Step 7: Click on the Publish button












It will create a new EC2 and deploy the website automatically in IIS. 


Pricing:

There is no additional charge for Elastic Beanstalk. You pay only for the underlying AWS resources that your application consumes.

Thursday, 27 June 2024

Get Microsoft Entra ID (formerly Azure Active Directory) Client Token From Postman

Let's learn step by step How to get the AD Client Token.

Step 1: Go to Azure Portal

Step 2: Search Microsoft Entra ID and click it.

Step 3: Go to App Registrations











Step 4: Click on the application and copy TenantId, Client Id and Client Secret







Step  5: Below are the parameters we required for the postman request

Parameter        Description
Tenant Id               The (tenant) ID for the related application is registered in Microsoft Entra ID.
client_id                 The (client) ID for the related application registered in Microsoft Entra ID.
client_secret           Client secret value for the related application registered in Microsoft Entra ID.
grant_type              client_credentials
scope                      https://graph.microsoft.com/.default 


Step 6: Add a new Post request in the Postman with the below URL and above parameters, you will get token as shown in the snapshot below.

https://login.microsoftonline.com/{{tenantId}}/oauth2/v2.0/token


























Here you can see the token.

C# Create Dynamic JSON With Dynamic Keys

 In this article, we will create a dynamic JSON.

When you have a requirement where you are not sure how many nodes/keys you need to create in the JSON then follow the below approach.


Step 1: Declare a dictionary

            var fileData = new Dictionary<string, object>();


Step 2: Add dynamic data, in my example, I have an array of nodes and values. So, I am adding values to each.

 foreach (DocumentKeyValuePair kvp in result.KeyValuePairs)

 {

             fileData[kvp.Key.Content] = kvp.Value.Content;     

 }


Step 3: Searlize Object using Newtonsoft.Json;


 string json = JsonConvert.SerializeObject(fileData, Formatting.Indented);

 System.IO.File.WriteAllText(@"D:\file.json", json);



I am also saving the JSON in D drive, you can specify your path.

Your file will be saved in the specific directory and you can see I have dynamic keys and values.




Azure Function - In-process model vs Isolated worker model

 In-process model Your function code runs inside the same process as the Azure Functions runtime Uses the WebJobs SDK . [FunctionName(...