30 April 2024

Await example in C#

Await example in C# 

using System;
using System.Threading.Tasks;

class Program {
 private static string result="test123";
 
 static void Main() {
   SaySomething();
   Console.WriteLine(result);
 }
 
 static async Task<string> SaySomething() {
   await Task.Delay(5);
   Console.WriteLine("test");
   result = "Hello world!";
    Console.WriteLine(result);
   return “Something”;
 }
}

Output

test123
test
Hello world!

Middleware vs Filters

 Middleware vs Filters

Use Middleware When
      You need to handle every request or response in a consistent manner accross the application 

Use Filters When
      Suppose if you want to implement certain logic to particular API/Controller

C# Web API Flow

 C# Web API Flow

  1. Receive Request
  2. Middleware Pipeline(Authentication, authorization, Logging, Error handling, Routing)
  3. Routing
  4. Controller Activation
  5. Model Binding
  6. Action Filters
  7. Execute Actions
  8. Result Execution
  9. Response Sent
  10. Logging and Cleanup

OAuth and C# Integration

 OAuth and C# Integration

Authenticate users with Microsoft Accounts
      
Steps
  1. Register your application - Microsoft Identity Platform(Azure Active Directory)
  2. Install required Nuget packages.
    1. Microsoft.Identity.Client
  3. Configure OAuth Settings - including the ClientID, tenantId, Client Secret
  4. Implementing Authentication
  5. Handling Token acquistion - method AcquireTokenByAuthorization Code
  6. Refresh Token

Solid Principles - Project example

 Solid Principles - Project example


Single Responsibility Principle

your code should have only one job - Mail and SMS
Open/Closed Principle
We can override the class functionality, but not change the existing class. Abstract -> Overide. Example - Version Maintain

Liskov/Substitution Principle

Derived class must be substitutable for its base class.
Abstract Class -> Interface -> No Override method

Use Abstract class in interface and give more explanation

Interface Segregation Principle
clients should not be forced to implement interfaces they don't use. Instead of one fat interface, many small interfaces are preferred.
     

Dependency Inversion Principle

high-level modules/classes should not depend on low-level modules/classes. should depend upon abstractions.

Use dependency injection for injecting the dependency

25 October 2023

Consistency level in Azure cosmos db

 Consistency level in Azure cosmos db

Azure Cosmos DB offers five well-defined consistency levels to provide developers with the flexibility to choose the desired trade-off between consistency, availability, and latency for their applications. Here are the available consistency levels in Azure Cosmos DB:

 1. Strong Consistency:

   - Description: Guarantees linearizability, meaning that reads are guaranteed to return the most recent committed version of the data across all replicas. It ensures the highest consistency but might have higher latency and lower availability compared to other levels.

   - Use Case: Critical applications where strong consistency is required, such as financial or legal applications.

 2. Bounded staleness:

   - Description: Allows you to specify a maximum lag between reads and writes. You can set the maximum staleness in terms of time or number of versions (operations). This level provides a balance between consistency, availability, and latency.

   - Use Case: Scenarios where you can tolerate a slight delay in consistency, such as social media feeds or news applications.

 3. Session Consistency:

   - Description: Guarantees monotonic reads and writes within a single client session. Once a client reads a particular version of the data, it will never see a version of the data that's older than that in subsequent reads. This level provides consistency within a user session.

   - Use Case: User-specific data scenarios where consistency within a user session is important, like in online shopping carts.

 4. Consistent Prefix:

   - Description: Guarantees that reads never see out-of-order writes. Within a single partition key, reads are guaranteed to see writes in the order they were committed. This level provides consistency per partition key.

   - Use Case: Applications that require ordered operations within a partition key, such as time-series data or event logging.

 5. Eventual Consistency:

   - Description: Provides the weakest consistency level. Guarantees that, given enough time and lack of further updates, all replicas will converge to the same data. There is no strict guarantee about the order in which updates are applied to different replicas.

   - Use Case: Scenarios where eventual consistency is acceptable, such as content management systems or applications dealing with non-critical data.

6. Custom Consistency:

   - Description: Allows developers to define custom consistency levels based on specific requirements. This flexibility enables fine-tuning consistency for unique application needs.

   - Use Case: Applications with highly specific or unique consistency requirements not met by the predefined consistency levels.

When selecting a consistency level, it's essential to understand the requirements of your application, as well as the implications on latency, availability, and throughput. Each consistency level offers a different balance between these factors, allowing you to tailor the database behavior to match your application's needs.

Reprocess data in deadletter queue - Service Bus

Reprocess data in deadletter queue - Service Bus

Reprocessing data from the Dead Letter Queue in Azure Service Bus involves inspecting the failed messages, addressing the issues that caused the failures, and then resubmitting the corrected messages for processing. Here's how you can reprocess data from the Dead Letter Queue:

 1. Inspect Messages:

   - First, you need to identify and understand the reason why messages ended up in the Dead Letter Queue. Inspect the messages to determine the cause of the failure. You can do this by reading the messages' content, properties, and error details.

 2. Correct the Issues:

   - Once you've identified the issues, correct the problems with the messages. This might involve fixing data inconsistencies, updating message formats, or addressing any other issues that caused the messages to fail.

3. Manually Resubmit Messages:

   - After correcting the problematic messages, you can manually resubmit them to the main queue or topic for reprocessing. To do this, you need to create a new message with the corrected content and send it to the appropriate queue or topic.

   Example (using Azure SDK for .NET):

   ```csharp

   // Read the message from the Dead Letter Queue

   var deadLetterMessage = await deadLetterReceiver.ReceiveAsync();

      // Correct the issues with the message

   // ...

   // Create a new message with the corrected content

   var correctedMessage = new Message(Encoding.UTF8.GetBytes("Corrected Message Content"))

   {

       // Set message properties, if necessary

       MessageId = "NewMessageId"

   };

   // Send the corrected message back to the main queue or topic

   await queueClient.SendAsync(correctedMessage);

4. Automated Retry Mechanism:

   - Depending on the nature of the issues, you might implement an automated retry mechanism. For transient errors, you can configure Service Bus to automatically retry processing failed messages after a certain delay. You can set policies for automatic retries and define the maximum number of delivery attempts before a message is moved to the Dead Letter Queue.

   Example (using Azure SDK for .NET):

   ```csharp

   queueClient.ServiceBusConnection.OperationTimeout = TimeSpan.FromSeconds(30);

   queueClient.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(5), 10);

5. Monitoring and Alerting:

   - Implement monitoring and alerting to be notified when messages are moved to the Dead Letter Queue. This ensures that you're aware of processing failures promptly and can take appropriate actions to resolve them.

By following these steps, you can reprocess data from the Dead Letter Queue, ensuring that failed messages are corrected, resubmitted, and successfully processed in your Azure Service Bus application.

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...