Saturday 11 November 2023

CQRS pattern

 CQRS, which stands for Command Query Responsibility Segregation, is a software architectural pattern that separates the concerns of handling command input (write operations) from the concerns of handling query output (read operations). In CQRS, a system is divided into two parts: the Command side and the Query side.

Command Side: Responsible for handling commands and updating the state of the system.

Query Side: Responsible for handling queries and providing read access to the system's state.

Here's a simple example of implementing the CQRS pattern in C#:

 // Command
public class CreateProductCommand
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Command Handler
public class CreateProductCommandHandler
{
    public void Handle(CreateProductCommand command)
    {
        // Logic to create a new product and update the state
        // This might involve validation, persistence, and other business logic

        Console.WriteLine($"Product '{command.Name}' created successfully with price {command.Price}");
    }
}

// Query
public class GetProductQuery
{
    public int ProductId { get; set; }
}

// Query Handler
public class GetProductQueryHandler
{
    public Product Handle(GetProductQuery query)
    {
        // Logic to retrieve product information from the state
        // This might involve querying a database, caching, or other mechanisms

        return new Product
        {
            ProductId = query.ProductId,
            Name = "Sample Product",
            Price = 29.99m
        };
    }
}

// Model
public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// Example Usage
class Program
{
    static void Main()
    {
        // Command side usage
        var createProductCommand = new CreateProductCommand
        {
            Name = "Example Product",
            Price = 49.99m
        };

        var createProductHandler = new CreateProductCommandHandler();
        createProductHandler.Handle(createProductCommand);

        // Query side usage
        var getProductQuery = new GetProductQuery
        {
            ProductId = 1
        };

        var getProductHandler = new GetProductQueryHandler();
        var product = getProductHandler.Handle(getProductQuery);

        Console.WriteLine($"Product Name: {product.Name}, Price: {product.Price}");
    }
}

In this example, the CreateProductCommand represents a command for creating a new product, and the CreateProductCommandHandler handles this command, updating the system state accordingly. On the query side, the GetProductQuery represents a query to retrieve product information, and the GetProductQueryHandler handles this query, providing the necessary data from the system state. The Product class is a simple model representing a product.

Reference: https://www.c-sharpcorner.com


Continue Reading →

MicroService Interview Q/A

 1. What is a Microservice?

  • Answer: A microservice is a small, independent, and modular service that performs a specific business function. Microservices architecture involves breaking down a large application into a collection of loosely coupled services that can be developed, deployed, and scaled independently.

2. What are the key characteristics of Microservices?

  • Answer:
    • Independence: Microservices operate independently of each other.
    • Scalability: Each service can be scaled independently.
    • Resilience: Failure in one service does not affect others.
    • Decentralized Data Management: Each service manages its own database.

3. How do Microservices communicate with each other?

  • Answer: Microservices commonly communicate through lightweight protocols such as HTTP/REST, or message queues like RabbitMQ or Apache Kafka.

4. What is the difference between Microservices and Monolithic architecture?

  • Answer: In a monolithic architecture, the entire application is a single, tightly integrated unit, whereas in microservices, the application is broken down into smaller, loosely coupled services.

5. Explain the concept of Service Discovery in Microservices.

  • Answer: Service discovery is a mechanism that allows microservices to find and communicate with each other without hard-coding service locations. It helps manage dynamic environments where services may be added or removed.

6. What is API Gateway in the context of Microservices?

  • Answer: An API Gateway is a server that acts as an API front-end, receiving API requests, enforcing throttling and security policies, and distributing requests to the appropriate microservices.

7. How does Microservices architecture contribute to DevOps practices?

  • Answer: Microservices promote continuous delivery and deployment as each service can be developed, tested, and deployed independently. This aligns with the principles of DevOps, encouraging collaboration and automation.

8. What is the purpose of a Container in Microservices?

  • Answer: Containers provide a lightweight and consistent environment for running microservices. They encapsulate the application, its dependencies, and runtime, ensuring consistency across different environments.

9. Explain Circuit Breaker pattern in Microservices.

  • Answer: The Circuit Breaker pattern is a design pattern used to detect and prevent failures in microservices by temporarily stopping requests to a failing service and redirecting those requests to a fallback mechanism.

10. How can you ensure data consistency in a Microservices architecture?

Answer:  Ensuring data consistency in a microservices architecture can be challenging. One approach is to use the Saga pattern, where a sequence of local transactions is coordinated to achieve global consistency.




Continue Reading →

What is Microservice ?

 A microservice is a software architectural style that structures an application as a collection of small, independent services, each of which is designed to perform a specific business function. These services are loosely coupled and communicate with each other through well-defined APIs (Application Programming Interfaces). The goal of microservices architecture is to break down a monolithic application into smaller, independently deployable services that can be developed, deployed, and scaled independently.

Here are some key characteristics and principles of microservices:

Decentralization:

Microservices architecture emphasizes decentralization. Each microservice is an independent entity that can be developed, deployed, and scaled independently. This allows for greater flexibility and agility in development and maintenance.

Independence:

Each microservice is responsible for a specific business capability and operates independently of other services. This independence allows for separate development, deployment, and scaling of each service.

Scalability:

Microservices can be individually scaled based on the specific needs of each service. This enables more efficient resource utilization and the ability to scale only the parts of the system that require additional capacity.

Resilience:

Since microservices operate independently, a failure in one service does not necessarily affect the entire system. This makes it easier to build resilient and fault-tolerant systems.

Technology Diversity:

Microservices allow for the use of different technologies and programming languages for different services. This enables teams to choose the best tools for the specific requirements of each microservice.

APIs and Communication:

Microservices communicate with each other through well-defined APIs. This communication is often achieved through lightweight protocols like HTTP/REST or messaging systems. This enables interoperability between services.

Autonomy and Ownership:

Development teams can be organized around microservices, giving each team end-to-end responsibility for a specific service. This autonomy allows teams to make decisions independently and move quickly.

Continuous Delivery:

Microservices architecture is well-suited for continuous integration and continuous delivery (CI/CD) practices. Since each service can be deployed independently, updates and new features can be released more frequently.

Data Management:

Microservices may have their own databases, and data consistency between services is typically maintained through asynchronous communication and eventual consistency.

Containerization:

Microservices are often deployed in containers (e.g., Docker containers) to ensure consistency across different environments and simplify deployment.

While microservices offer several benefits, such as scalability, flexibility, and resilience, they also introduce challenges, including increased complexity in managing distributed systems, potential communication overhead, and the need for effective service discovery and orchestration mechanisms. Successful adoption of microservices requires careful consideration of these challenges and the application of best practices in areas like monitoring, testing, and deployment automation.

Continue Reading →

Tuesday 31 October 2023

C# String data type : Exercises

 C# String data type : Exercises, Practice, Solution

Write a C# Sharp program to find the length of a string without using a library function.

  using System;  
  public class Exercise2
  {  
      public static void Main()
  {
      string str; /* Declares a string of size 100 */
      int l= 0;
   
        Console.Write("Input the string : ");
        str = Console.ReadLine();
 
           foreach(char chr in str)
          {
              l += 1;
          }
     Console.Write("Length of the string is : {0}\n\n", l);
    }
  }

Write a program in C# Sharp to count the total number of words in a string.

  using System;  
  public class Exercise5
  {  
      public static void Main()
      {
          string str;
          int i, wrd,l;
   
            Console.Write("Input the string : ");
            str = Console.ReadLine();
   
             l = 0;
             wrd = 1;
 
      /* loop till end of string */
      while (l <= str.Length - 1)
      {
          /* check whether the current character is white space or new line or tab character*/
          if(str[l]==' ' || str[l]=='\n' || str[l]=='\t')
          {
              wrd++;
          }
 
          l++;
      }
 
     Console.Write("Total number of words in the string is : {0}\n", wrd);
    }
  }

Write a program in C# Sharp to compare two strings without using a string library functions.

  using System;  
  public class Exercise6
  {  
      public static void Main()
  {
      string str1, str2;
      int flg=0;
      int i = 0, l1, l2, yn = 0;
     
        Console.Write("Input the 1st string : ");
        str1 = Console.ReadLine();    
       
        Console.Write("Input the 2nd string : ");
        str2 = Console.ReadLine();    
 
      l1=str1.Length;
      l2=str2.Length;
      /*compare checking when they are equal in length*/    
      if(l1==l2)
    {
      for(i=0;i<l1;i++)
        {
            if(str1[i] != str2[i])
            {
              yn= 1;
              i= l1;       
            }
        }
    }
  /*initialize the flag where they are equal, smaller and greater in length*/  
      if(l1 == l2)
          flg=0;
      else if(l1 > l2)
          flg=1;
      else if(l1 < l2)
          flg=-1;
  /*display the message where the strings are same or smaller or greater*/  
      if(flg == 0)
      {
         if(yn==0)
         Console.Write("\nThe length of both strings are equal and \nalso, both strings are same.\n\n");
         else
              Console.Write("\nThe length of both strings are equal \nbut they are not same.\n\n");
      }
      else if(flg == -1)
      {
         Console.Write("\nThe length of the first string is smaller than second.\n\n");
      }
      else
      {
         Console.Write("\nThe length of the first string is greater than second.\n\n");
      }
    }
  }

Write a program in C# Sharp to count the number of alphabets, digits and special characters in a string.

using System;  
  public class Exercise7  
  {  
   public static void Main()
  {
      string str;
      int alp, digit, splch, i,l;
      alp = digit = splch = i = 0;
 
        Console.Write("Input the string : ");
        str = Console.ReadLine();
        l=str.Length;
 
       /* Checks each character of string*/
 
      while(i<l)
      {
          if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              alp++;
          }
          else if(str[i]>='0' && str[i]<='9')
          {
              digit++;
          }
          else
          {
              splch++;
          }
 
          i++;
      }
 
     Console.Write("Number of Alphabets in the string is : {0}\n", alp);
     Console.Write("Number of Digits in the string is : {0}\n", digit);
     Console.Write("Number of Special characters in the string is : {0}\n\n", splch);
    }
  }

Write a program in C# Sharp to copy one string to another string.

using System;  
public class Exercise8  
{  
    public static void Main()
{
    string str1;
    int  i,l;

      Console.Write("\n\nCopy one string into another string :\n");
      Console.Write("-----------------------------------------\n");  
      Console.Write("Input the string : ");
      str1 = Console.ReadLine();
     
      l=str1.Length;
      string[] str2=new string[l];

    /* Copies string1 to string2 character by character */
    i=0;
    while(i<l)
    {
        string tmp=str1[i].ToString();
        str2[i] = tmp;
        i++;
    }
   Console.Write("\nThe First string is : {0}\n", str1);
   Console.Write("The Second string is : {0}\n", string.Join("",str2));
   Console.Write("Number of characters copied : {0}\n\n", i);
  }
}

Write a C# Sharp program to count the number of vowels or consonants in a string.

  public class Exercise9  
  {  
  public static void Main()
  {
      string str;
      int i, len, vowel, cons;
     
      Console.Write("Input the string : ");
      str = Console.ReadLine();  
 
      vowel = 0;
      cons = 0;
      len = str.Length;
 
      for(i=0; i<len; i++)
      {
 
          if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
          {
              vowel++;
          }
          else if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              cons++;
          }
      }
     Console.Write("\nThe total number of vowel in the string is : {0}\n", vowel);
     Console.Write("The total number of consonant in the string is : {0}\n\n", cons);
    }
  }

Write a C# Sharp program to find the maximum number of characters in a string.  Click here













Continue Reading →

Monday 30 October 2023

Arrays in C#

In C#, an array is a collection of elements of the same type that are stored in contiguous memory locations and can be accessed using an index. Arrays provide an efficient way of storing and accessing a fixed number of elements.

 Create an array 

There are multiple ways to create an array in C#. Here are a few examples.

Using the new keyword

  int[] numbers = new int[5];

The above code snippet creates an array called "intArray" to hold five integers. However, the elements of the Array are not yet initialized, and their values are undefined.

Using the new keyword with an array initializer

Arrays can also be initialized when they are declared by providing a list of comma-separated values enclosed in curly braces {}

  int[] intArray = new int[] {1, 2, 3, 4, 5};

  // or Simply
 
  int[] intArray = {1, 2, 3, 4, 5};

This creates an array called "intArray" with five elements and assigns the values 1, 2, 3, 4, and 5 to the elements of the Array.

Using the var keyword

  var myArray = new int[] {1, 2, 3, 4, 5};

This creates an array; the array type is inferred from the initializer, and the Array's name is myArray.

How To Sort Array In C#

The simplest way to sort an array in C# is using Array.Sort method. The Array.Sort method takes a one-dimensional array as an input and sorts the array elements in the ascending order.

The following code snippet creates an array of integers.

  int[] intArray = new int[] { 9, 2, 4, 3, 1, 5 };

The Array.Sort method takes array as an input and sorts the array in ascending order.

  Array.Sort(intArray);

To sort an array in descending order, we can use Sort.Reverse method. This method also takes an array as an input and sorts its elements in descending order. The following code snippet reverses an array.

  Array.Reverse(intArray);

Sort an Array of Int in C#

Here is the complete code that creates an array of integers and sorts in ascending and descending orders using Array.Sort and Array.Reverse methods.

static void Main(string[] args) {
    // Array of integers
    int[] intArray = new int[] {
        9,
        2,
        4,
        3,
        1,
        5
    };
    Console.WriteLine("Original array");
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    // Sort array in ASC order
    Console.WriteLine("Sorted array in ASC order");
    Array.Sort(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    Console.WriteLine("Sorted array in DESC order");
    // Sort Array in DESC order
    Array.Reverse(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();

The output of the above code is below where first it prints the original array, followed by the sorted array in ASC and DESC order respectively.


Sort an Array of Strings in C#

Now let’s sort an array of strings in C#. Sorting an array of strings is like sorting an array of int. The Array.Sort method takes an input value of an array of strings. The following code example shows how to sort an array of strings in ascending and descending orders using C#.

  // Array of strings
string[] strArray = new string[] { "Mahesh", "David", "Allen", "Joe", "Monica" };
Console.WriteLine();
Console.WriteLine("Original array");
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
// Sort array
Array.Sort(strArray);
// Read array items using foreach loop
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
Array.Reverse(strArray);
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();

The output of the above code displays original array, sorted array in the ascending order, and sorted array in the descending order.


Sort a Range of Elements In An Array

The Sort.Array method allows you to sort a range of elements within an array. For example, if an array has 11 elements but what if you want to sort only 1st to next 6 elements in the array? You can use that by passing the first starting index of the element followed by the number of elements to be sorted.

// Array of integers
int[] intArray = new int[] { 9, 2, 4, 3, 1, 5, 6, 9, 5, 7, 1, 0};
// Sort array from 1st element to 6th element. Skip 0th element.
Array.Sort(intArray, 1, 6);
foreach (int i in intArray)
{
    Console.Write(i + " ");
}

The output looks like the following where you can see only 6 elements are sorted after skipping the first element of the array.

9 1 2 3 4 5 6 9 5 7 1 0

Note that this sorting applies to all types of arrays not just integers.


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives