Showing posts with label .NetCore. Show all posts
Showing posts with label .NetCore. Show all posts

Wednesday, 25 December 2024

Azure Durable Functions

What is a Durable Function?

A Durable Function is an extension of Azure Functions that allows you to write stateful workflows in a serverless environment. Durable Functions are part of the Durable Task Framework, which enables you to chain function calls, handle retries, and execute long-running processes without worrying about the limitations of the traditional stateless Azure Functions.

With Durable Functions, you can manage complex workflows that require coordination and long-running tasks like waiting for external events or managing retries.


Key Concepts of Durable Functions:

  1. Orchestrator Functions:

    • Purpose: Orchestrator functions define the workflow logic. They are responsible for calling other functions (called activity functions) in a defined order.
    • Behavior: Orchestrator functions are durable, meaning they can pause and resume without losing state. They are executed once and can call other functions in sequence, parallel, or even handle retries.
    • Example: You could have an orchestrator function that retrieves data from an Azure SQL Database, processes it, and then sends results to a downstream service.
  2. Activity Functions:

    • Purpose: Activity functions are the actual units of work within the durable workflow. They execute the tasks like querying a database, calling an API, processing data, etc.
    • Behavior: Activity functions are stateless and run as normal Azure Functions.
    • Example: An activity function could perform an SQL query, send an email, or process a file.
  3. Client Functions:

    • Purpose: These are regular Azure Functions that start the orchestration by calling the orchestrator function. They are typically HTTP-triggered and initiate the durable workflow.
    • Behavior: Client functions handle the initiation and monitor the progress or completion of the orchestration.
    • Example: An HTTP trigger might accept a request to start an orchestration that processes a file upload or runs a time-consuming SQL query.

Key Features of Durable Functions:

  1. Long-Running and State Preservation:

    • Durable Functions can run for extended periods (even days) and maintain state across retries and failures.
    • They can be paused and resumed by the Azure Durable Task framework, allowing them to handle long-running processes like waiting for external events or delays.
  2. Resiliency and Retry Mechanism:

    • Durable Functions can automatically retry operations in case of failure or timeouts, ensuring that long-running operations are resilient.
  3. Fan-Out and Fan-In Patterns:

    • Fan-Out: You can trigger multiple activities in parallel and wait for all of them to complete (useful for processing large datasets concurrently).
    • Fan-In: After the parallel operations, you can consolidate the results into a single output.
  4. Human Intervention:

    • They support waiting for external events or human intervention before proceeding with the next step. For example, you could wait for a user to approve or review something before continuing the workflow.

Example Workflow in Durable Functions:

Imagine a scenario where you need to query an Azure SQL Database and process the data over several steps, including retries for failures:

  1. Client Function (HTTP Trigger): Accepts a request to start the process (e.g., querying a database).
  2. Orchestrator Function:
    • Calls an Activity Function to query the database.
    • If the query takes a long time or is complex, it can be handled gracefully using Durable Functions.
    • Calls other activity functions to process the data (e.g., transformation, validation).
  3. Activity Function:
    • Executes the query and processes the data.
    • Handles retries if an error occurs (e.g., network failure, SQL timeout).
  4. Wait for External Event: If the process requires user confirmation or waiting for a response, the orchestrator can pause until the event is triggered.

Example Code Snippet for Durable Functions:

Here’s a simplified example of how you might set up a Durable Function workflow with a SQL query and processing.

  1. Orchestrator Function (DurableOrchestrator.cs):
[FunctionName("DurableOrchestrator")]
public static async Task RunOrchestrator(
    [OrchestrationTrigger] IDurableOrchestrationContext context)
{
    // Call the Activity Function to query the database
    var queryResult = await context.CallActivityAsync<string>("QueryDatabase", null);

    // Call another activity to process the data
    var processedData = await context.CallActivityAsync<string>("ProcessData", queryResult);

    return processedData;
}
  1. Activity Function to Query Database (QueryDatabase.cs):
[FunctionName("QueryDatabase")]
public static string QueryDatabase([ActivityTrigger] string name, ILogger log)
{
    // Execute SQL query and return result
    return "Query result from DB";
}
  1. Activity Function to Process Data (ProcessData.cs):
[FunctionName("ProcessData")]
public static string ProcessData([ActivityTrigger] string queryResult, ILogger log)
{
    // Process the data (e.g., transform, validate)
    return "Processed data: " + queryResult;
}
  1. Client Function (HTTP Trigger):
[FunctionName("StartWorkflow")]
public static async Task<HttpResponseMessage> StartWorkflow(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestMessage req,
    [DurableClient] IDurableOrchestrationClient starter,
    ILogger log)
{
    // Start the Durable Orchestration
    string instanceId = await starter.StartNewAsync("DurableOrchestrator", null);

    return starter.CreateCheckStatusResponse(req, instanceId);
}

Key Considerations:

  • Costs: While Durable Functions are great for long-running workflows, keep an eye on the execution time, as longer executions may increase costs, especially if using the Consumption plan.
  • State Management: Durable Functions maintain state, so you don’t need to manage it manually (e.g., in a database or external system).
  • Timeouts: Azure Durable Functions can run indefinitely, but they are subject to overall system limits, such as maximum execution duration.

Conclusion:

Durable Functions are ideal for complex, long-running workflows that require state management, resiliency, and asynchronous execution. They can handle tasks that take hours or days, while still being highly scalable and cost-efficient.

Monday, 24 May 2021

C# Concepts to learn

1. Class

Everything in C# is associated with classes and objects, along with its attributes and methods.

2.Encapsulation

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member.

Public-Any public member can be accessed from outside the class.

Private- Access only within a class or scope

Protected- allows a child class to access the member variables and member functions of its base class.

Internal- allows a class to expose its member variables and member functions to other functions and objects in the current assembly.

Protected internal -allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application.

3.Polymorphism

polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.

static polymorphism

  • Function overloading ex: void print(int x){}; void print (string x){};
  • Operator overloading

Dynamic Polymorphism

C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.

Dynamic polymorphism is implemented by abstract classes and virtual functions.

Here are the rules about abstract classes −

  • You cannot create an instance of an abstract class

  • You cannot declare an abstract method outside an abstract class

  • When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.

4.Inheritance 

it's an concept of base class and derived class. derived class can access base class member and member functions.

-Single inheritance( class A{}; sealed class B:A{}; 

-Multilevel inheritance ( class A{}; class B:A{}; class C:B) 

-Multiple not possible but can achieve through interface.

5.Interface

it contains function declaration only with default public access specifies, implemented/derived class should provide definition declared functions in interface.

 Public interface ICalculator

{

int sum(int x,int y);

}

public class Calc : ICalculator

{

public int sum(int x,int y){ return x+y;}

}

6.Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

An abstract class can have both abstract and regular methods:

// Abstract class
abstract class Animal
{
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

// Derived class (inherit from Animal)
class Pig : Animal
{
  public override void animalSound()
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();  // Call the abstract method
    myPig.sleep();  // Call the regular method
  }
}

7.Dependancy Injection:

Dependency Injection (or inversion) is basically providing the objects that an object needs, instead of having it construct the objects themselves. It is a useful technique that makes testing easier, as it allows you to mock the dependencies.

8.Scafolding - Auto generated code for Controller CRUD operation using Entity Framework. 

9.Filters

10. Diff bw Authorize and Authentication

Authentication : need to pass login credentials, it's valid then it will return authorize response.

Authorize: after Authentication steps based on response it will validate user access to the particular action.

11.MVC architecture

12. ViewBag and ViewData and TempData

ViewData, ViewBag and TeampData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and it helps us to transfer the data from controller to view whereas TempData also works during the current and subsequent requests.

ViewData
ViewBag
TempData
It is Key-Value Dictionary collectionIt is a type objectIt is Key-Value Dictionary collection
ViewData is a dictionary object and it is property of ControllerBase classViewBag is Dynamic property of ControllerBase class.TempData is a dictionary object and it is property of controllerBase class.
ViewData is Faster than ViewBagViewBag is slower than ViewDataNA
ViewData is introduced in MVC 1.0 and available in MVC 1.0 and aboveViewBag is introduced in MVC 3.0 and available in MVC 3.0 and aboveTempData is also introduced in MVC1.0 and available in MVC 1.0 and above.
ViewData also works with .net framework 3.5 and aboveViewBag only works with .net framework 4.0 and aboveTempData also works with .net framework 3.5 and above
Type Conversion code is required while enumeratingIn depth, ViewBag is used dynamic, so there is no need to type conversion while enumerating.Type Conversion code is required while enumerating
Its value becomes null if redirection has occurred.Same as ViewDataTempData is used to pass data between two consecutive requests.
It lies only during the current request.Same as ViewDataTempData only works during the current and subsequent request

13.Seesion, Temp Data and Cookies

Session: stored in server side we can access all actions until get expired

Temp Data: stored in server side we can access all actions once read the value it will get expired.

Cookies: Stored in client side Each request & response it will pass. not secured one so not add sensitive info

14.Action Verbs

Action Verbs supported by MVC framework are HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions & HttpPatch, NonAction 

15.Areas in MVC

16.Partial View

17.Partial Class

18.Inner class

19.Linq

- Sum 

-Count

-Group by

- Min & Max

-Join

20. Quarriable & Enumerable

21. Render Action methods

22.Routing

23.Startup config

24.Constructors & types

25.Method Overload & Override

When two or more methods in the same class have the same name but different parameters, it's called Overloading. When the method signature (name and parameters) are the same in the superclass and the child class, it's called Overriding.

26.Singleton class and object

Singleton :In this pattern, a class has only one instance in the program that provides a global point of access to it. In other words, a singleton is a class that allows only a single instance of itself to be created and usually gives simple access to that instance.

The advantages of a Singleton Pattern are,

  1. Singleton pattern can implement interfaces.
  2. Can be lazy-loaded and has Static Initialization.
  3. It helps to hide dependencies.
  4. It provides a single point of access to a particular instance, so it is easy to maintain.
There are several ways to implement a Singleton Pattern in C#.
  1. No Thread Safe Singleton.
  2. Thread-Safety Singleton.
  3. Thread-Safety Singleton using Double-Check Locking.
  4. Thread-safe without a lock.
  5. Using .NET 4's Lazy<T> type.
No Thread Safety:
public sealed class SingletonA
{  
    private SingletonA() {}  
    private static SingletonA instance = null;  
    public static SingletonA Instance {  
        get {  
            if (instance == null) {  
                instance = new SingletonA();  
            }  
            return instance;  
        }  
    }  
}  
 
Thread Safety:
public sealed class SingletonA
{  
    private static readonly object lock = new object();  
    private SingletonA() {}  
    private static SingletonA instance = null;  
    public static SingletonA Instance {  
        get {
            lock(lock) {  
            if (instance == null) {  
                instance = new SingletonA();  
            }  
            return instance;  
            }
        }  
    }  
}  
 

27.Sealed class- no more inheritance

28.Dictionary & Hash table

29.Deligate and Callback

delegates detail link

C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

30.Global.asax : file allows you to write code that runs in response to application-level events, such as Application_BeginRequest, application_start, application_error, session_start, session_end, etc.

31.Ioc- Inversion Of Control : It is an design principle to support Test Driven Development and Dependency Injection.

https://www.tutorialsteacher.com/ioc/introduction

IoC is a design principle which recommends the inversion of different kinds of controls in object-oriented design to achieve loose coupling between application classes. In this case, control refers to any additional responsibilities a class has, other than its main responsibility, such as control over the flow of an application, or control over the dependent object creation and binding (Remember SRP - Single Responsibility Principle). If you want to do TDD (Test Driven Development), then you must use the IoC principle, without which TDD is not possible. Learn about IoC in detail in the next chapter.

Dependency Inversion Principle

The DIP principle also helps in achieving loose coupling between classes. It is highly recommended to use DIP and IoC together in order to achieve loose coupling.DIP suggests that high-level modules should not depend on low level modules. Both should depend on abstraction.

32.Discards - C#
 C# supports discards, which are placeholder variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they don't have a value.
public static void Main() { var p = new Person("John", "Quincy", "Adams", "Boston", "MA"); // Deconstruct the person object. var (fName, _, city, _) = p; Console.WriteLine($"Hello {fName} of {city}!"); // The example displays the following output: // Hello John of Boston! }

33.Diff between Ref & Out in C#
ref keywordout keyword
It is necessary the parameters should initialize before it pass to ref.It is not necessary to initialize parameters before it pass to out.
It is not necessary to initialize the value of a parameter before returning to the calling method.It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter.The declaring of parameter through out parameter is useful when a method return multiple values.
When ref keyword is used the data may pass in bi-directional.When out keyword is used the data only passed in unidirectional.