Communication Patterns in Microservices – REST, gRPC, and Event-Driven Messaging

Introduction

In the last article, we discussed how microservices stay decoupled through strong boundaries and data ownership. But independence doesn’t mean isolation, services still need to talk to each other.

And how they talk defines everything: latency, reliability, scalability, and even user experience.

That’s where communication patterns come into play which is the architectural backbone connecting distributed systems.

We’ll explore three key approaches used across modern microservice ecosystems:

  1. REST (HTTP) – Simple, request/response communication
  2. gRPC – Fast, strongly-typed, binary communication
  3. Event-Driven Messaging — Asynchronous, loosely coupled communication

1. REST — The Universal Language of Microservices

REST (Representational State Transfer) uses HTTP as its foundation. It’s simple, human-readable, and widely supported.

Article content

When to Use REST

  • Simplicity and familiarity matter most
  • You need request/response semantics
  • Perfect for user-facing APIs and CRUD operations

Limitations

  • Verbose (JSON over HTTP)
  • Slower under high load
  • Lacks streaming and strong typing
  • Each hop adds the network latency

2. gRPC — High-Performance, Typed Communication

gRPC (Google Remote Procedure Call) is a modern alternative to REST which used the Protocol Buffers instead of JSON and HTTP/2 instead of HTTP/1.

This allows:

  • Smaller payloads (binary serialization)
  • Multiplexed requests over one connection
  • Strongly-typed service contracts
Article content

When to Use gRPC

  • Internal microservice communication within same org or network
  • High throughput and low latency required
  • Need for streaming

Limitations

  • Not browser-friendly. It requires client libraries required
  • Harder for external developers to consume directly
  • Needs schema management of the .proto files

Now lt’s have a quick comparison of both the protocols

Article content
Now let’s move to the event driven messaging

3. Event-Driven Messaging – Asynchronous Collaboration

While REST and gRPC are ,Event-Driven Messaging is asynchronous in which services communicate via events through a message broker (Kafka, RabbitMQ, Azure Service Bus, etc.).

Article content

In this setup:

  • Publishers emits events
  • Subscribers consume them independently
  • No one waits. Everything happens in parallel

Example (MetroX Platform):

When Payment Service publishes PaymentConfirmed event. Upon receivin this event, notification service sends an SMS or email and operations service updates dashboards.


Now let’s look at the different delivery semantics of their reliability.

Different brokers and systems offer different guarantees:

Article content

That’s why idempotency is vital:

Processing the same event multiple times should yield the same result.

Article content

Based on the requirement we have to choose the right communication protocol and they can be used together to achieve different functionalities.

Article content

Each pattern serves its own purpose,yet all cooperate through clear contracts, message schemas, and delivery guarantees.

That’s all today in the communication patterns.


 

Coming Next

Next in the Microservices Essentials series: 👉 The API Gateway Pattern – The Front Door of Microservices How to manage routing, versioning, and security across REST, gRPC, and event-driven systems.

Core Characteristics of a Microservice Architecture

In the previous article, we explored what microservices are — small, independent services built around business capabilities.

Today we are going to check the characteristics which truly defines a microservice-based system.

By simply breaking a monolith into smaller projects doesn’t make it microservices.

What defines a microservice architecture is how those services behave — their independence, boundaries, and resilience.

Let’s explore the core traits that make an architecture genuinely microservice-driven.

1. Independent Deployability

Each service should be developed, tested, and deployed without affecting others.That’s the foundation of speed and agility in microservice-based delivery.

Article content

e.g: Update the Transaction Service independently without redeploying Payment or Operations.


2. Loose Coupling and High Cohesion

Each service owns its logic, data, and domain rules (high cohesion).Services interact with others only through defined interfaces (APIs or events) — not direct DB calls (loose coupling).

Article content

3. Clear Domain Boundaries (Bounded Contexts)

Microservices should align with business domains — not arbitrary technical divisions.This concept, inspired by Domain-Driven Design (DDD), ensures every service speaks its own language and owns its model.

Article content

A bounded context keeps domain logic clear, avoiding shared dependencies or model confusion.


4. Decentralized Data Ownership

Every service manages its own database — even if that means using different storage technologies.This isolation enables autonomy and prevents data coupling.

Article content

This helps to developerd gaining a freedom to evolve schema, optimize queries, and maintain service integrity without external impact.


5. Scalability and Fault Isolation

Microservices scale individually based on workload. A Payment Service may run 5 replicas under heavy traffic, while the Operations Service stays small.

Failures are also contained — one service crashing shouldn’t bring others down.

Article content
Sequence Diagram

6. Observability and Monitoring

In a distributed world, visibility is everything. Each service should expose:

  • Logs (structured, centralized)
  • Metrics (performance, throughput)
  • Traces (end-to-end request paths)

Multiple tools are available which can be used such as Prometheus, Grafana, ELK Stack, Jaeger, OpenTelemetry.


Summary at a Glance

Article content

Real-World Snapshot — From the MetroX Platform

Here is the real world snapshot which is being developed by me for the sole purpose of Microservices demonstration.

Article content

These services operate independently, share no databases, and communicate via events — forming a cohesive yet decoupled ecosystem.


Coming Next

Next in the Microservices Essentials series: 👉 Communication Patterns in Microservices — REST, gRPC, and Event-Driven Messaging.

 

What Are Microservices?

Microservices turn a large, tightly coupled system into a collection of small, focused, and independently deployable services — each built around a specific business capability.

The Evolution — From Monoliths to Microservices

For years, applications were built as monoliths — a single deployable unit handling everything from user authentication to payments and reporting.That approach works well initially… until it doesn’t.

As features grow and teams expand, the monolith becomes harder to manage, deploy, and scale. Enter Microservices Architecture — a way to break that big block into smaller, self-contained services that work together through well-defined APIs.


Here’s a visual snapshot of the Monolithic system

Article content

In this model:

  • All features share the same database and deployment.
  • Any bug can impact unrelated modules.
  • Scalability and team agility are limited.

The Same System Reimagined as Microservices

Article content

Now, each service:

  • Has its own data, logic, and lifecycle
  • Can be deployed or scaled independently
  • Allows teams to work autonomously without conflicts

e.g: If the Payment Service needs an update for UPI integration, it can go live without redeploying the Transaction or Operations modules


The Core Idea

A microservice is a self-contained unit that:

  • Solves one clear business problem (e.g., payments, operations, analytics)
  • Has its own data store and API boundary
  • Communicates with others using lightweight protocols (HTTP, gRPC, events)
  • Is independently deployable and scalable

Think of it as a collection of small, specialized teams — each owning one product within a bigger ecosystem.


Why Microservices Matter

  • Independent Deployments — Release one service without affecting others.
  • Faster Innovation — Small, isolated codebases mean rapid iteration.
  • Targeted Scalability — Scale only what’s under load (e.g., Payments on festive days).
  • Resilience — One service failure doesn’t bring down the entire system.
  • Technology Flexibility — Choose the best stack per domain (C#, Node, Go, etc.).

Monolith vs Microservices — A Quick Comparison

Article content


How Microservices Communicate

Let’s see how a client-facing app (like a mobile user app or ticketing app) interacts with these services:

Article content

Here’s the real-world flow:

  • A user initiates a transaction via the app.
  • The Transaction Service emits an event → TransactionCreated.
  • The Payment Service processes and emits → PaymentConfirmed.
  • The Operations Service updates internal logs or shifts.
  • The Notification Service sends confirmation to the user.

This event-driven flow keeps everything loosely coupled and highly scalable.


When (Not) to Use Microservices

Article content

If you are unclear whether to go with Microservices or not then start with a well-structured monolith and gradually evolve into microservices when boundaries become clear.


Key Takeaways

  • Microservices = independent, domain-driven units working together via APIs or events.
  • They bring agility, scalability, and resilience but at the cost of added operational complexity.

Coming Next

Next in the Microservices Essentials series: Core Characteristics of a Microservice Architecture –> exploring autonomy, data ownership, observability, and domain boundaries.

Inter Process Communication in .net and Framework

Recently I was working on a .net Framework 4.8 application and there was one feature which I wanted to implement. But this feature has support only in the .net core 3.0 onwards.

To resolve this issue I decided to take an approach of inter process communication through TCP Listener and Client

Here is the code snippet for TCPListener written in .net 8

static async Task Main(string[] args)
{
    var listener = new TcpListener(IPAddress.Any, 12346);
    listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    listener.Start();
    Console.WriteLine("Server started and listening on port 12346...");

    while (true)
    {
        var client = await listener.AcceptTcpClientAsync();
        Console.WriteLine("Client connected...");
        _ = HandleClientAsync(client);
    }
}

In the above code, I have initialized the TcpListener object to listen the incoming message on any IP address on the port number 12346.

Then I wanted the listener to entertain all type of the sockets and to reuse the addresses.
Reuse address is used because the Listener and Client are running on the same machine.

Once all these options are set, listener is to be started.
Now we have to invoke the AcceptTcpClientAsync method on the listener so that it can accept the communication request from the TcpClient.

Once the connection is established, we have to handle the TcpClient’s request.
It has been handled in the HandleClientAsync method.

Here goes the code for handler.

private static async Task HandleClientAsync(TcpClient client)
{
    try
    {
        using var networkStream = client.GetStream();
        var buffer = new byte[4096];
        int bytesRead = await networkStream.ReadAsync(buffer, 0, buffer.Length);
        string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine($"Received message: {receivedMessage}");

        var response = string.Empty;
        //Specific logic for handling the receivedMessage goes here
        
        byte[] responseBytes = Encoding.UTF8.GetBytes(response);
        await networkStream.WriteAsync(responseBytes, 0, responseBytes.Length);
        Console.WriteLine("Response sent to client.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
    }
    finally
    {
        client.Close();
        Console.WriteLine("Client disconnected.");
    }
}

Along with TcpClient a NetworkStream is attached on which it writes data and read from it.
So in the above code, one has to get the stream from TcpClient and then has to read the data in a byte array.
Once data is read, it can be processed as required.
To send back the data to client, it is to be written on the same network stream.
TcpClient will read the data from this stream.

Here goes the code for client

static void Main(string[] args)
{
    string message = "ENCRYPT:Your data to encrypt";
    string response = SendMessage("127.0.0.1", 12346, message);
    Console.WriteLine("Response from server: " + response);
}

static string SendMessage(string server, int port, string message)
{
	try
	{
		using (var client = new TcpClient(server, port))
		{
			using (var stream = client.GetStream())
			{
				byte[] data = Encoding.UTF8.GetBytes(message);
				stream.Write(data, 0, data.Length);

				byte[] responseData = new byte[4096];
				int bytes = stream.Read(responseData, 0, responseData.Length);
				return Encoding.UTF8.GetString(responseData, 0, bytes);
			}
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine($"Exception: {ex.Message}");
		return string.Empty;
	}
}

Communication Process

 

  • Server Initialization:The server starts listening on the loopback address and specified port.
  • Client Connection:The client initiates a connection to the server’s loopback address and port.
  • Message Sending:The client sends a message (e.g., “ENCRYPT:Your data to encrypt”. In my case the required encryption was not available in .net framework natively) to the server over the established TCP connection.
  • Server Processing:The server receives the message, processes it (encryption or decryption), and prepares a response.
  • Response Sending:The server sends the processed response back to the client over the same TCP connection.
  • Client Receiving:The client reads the server’s response and displays it.

 

By following this setup, the server will only accept connections from clients running on the same machine, ensuring local-only communication.

That’s all for now. Enjoy the coding.

C# Factory Method Design Pattern

Today I am going to write about a factory method design pattern and how to implement it in C#.

Factory method design pattern is one of the creational design pattern first presented by Gang of Four.

Creational patterns are developed to create the objects for the required classes.

Usage: When we do not know object of which class to be be instantiated then we can use factory method design pattern. Responsibility of the object creation is given to the subclasses.

Before starting to understand the implementation of factory method design pattern, let us try to create the problem which is addressed by factory method design pattern.

To demonstrate this problem, I am taking an example of metro(railway) ticketing requirements.

While traveling through metro trains, one needs to buy a ticket. Ticket can be categorized as SJT(Single Journey Ticket), RJT(Return Journey Ticket), Group Ticket, Period Pass, Trip Pass etc.

Once we choose the ticket to be issued from UI, we have to obtain it’s underlying object so that we can assign that ticket specific values and pass it further.

To achieve this I have created a common interface which shall be inherited by all the ticket types in our system.

public interface IProduct
{
    eProductType ProductType { get; set; }
    decimal Price { get; set; }
    int SourceStationId { get; set; }
    int DestinationStationId { get; set; }
    int Quantity { get; set; }
}

This interface is implemented by 3 classes which are Ticket, PeriodPass and TripPass

public class Ticket : IProduct
{
    public eProductType ProductType { get; set; }
    public decimal Price { get; set; }
    public int SourceStationId { get; set; }
    public int DestinationStationId { get; set; }

    public string TicketId { get; set; }
    public DateTime SaleTime { get; set; }
    public DateTime ValidityTime { get; set; }    
}

public class PeriodPass : IProduct
{
    public eProductType ProductType { get; set; }
    public decimal Price { get; set; }
    public int SourceStationId { get; set; }
    public int DestinationStationId { get; set; }

    public DateTime ValidFrom { get; set; }
    public DateTime ValidTill { get; set; }   
}

public class TripPass : IProduct
{
    public eProductType ProductType { get; set; }
    public decimal Price { get; set; }
    public int SourceStationId { get; set; }
    public int DestinationStationId { get; set; }

    public DateTime ValidFrom { get; set; }
    public DateTime ValidTill { get; set; }
    public int NoOfTrips { get; set; }
}

Now based on the product type(ticket type), we can create an instance of the corresponding class by writing a simple method which will accept enum value of eProductType and will return a type of IProduct.

public IProduct GetProduct(eProductType productType)
{
	switch(eProductType)
	{
		case eProductType.SJT:
			return new Ticket();
		case eProductType.RJT:
			return new Ticket();
		case eProductType.PeriodPass:
			return new PeriodPass();
		case eProductType.TripPass:
			return new TripPass();
	}
}

I have demonstrated the simple factory based on switch condition. But the above approach has some disadvantages. One needs to call the GetProduct() method and needs to pass the product type enum value. When new product gets introduced one needs to modify the switch case. This violates the Single Responsibility principle.

At this juncture, factory method pattern comes to rescue.

For each product which we need to create, we need to have a concrete product factory class. This class will be inherited from an abstract ProductFactory class.

public abstract class ProductFactory
{
    public abstract IProduct GetProduct(eProductType productType);
}

public class TicketFactory : ProductFactory
{
    public override IProduct GetProduct(eProductType productType)
    {
        return new Ticket(productType);
    }
}

public class PeriodPassFactory : ProductFactory
{
    public override IProduct GetProduct(eProductType productType)
    {
        return new PeriodPass(productType);
    }
}

So we have successfully utilized our existing IProduct interace and eProductType enum and created the abstract and concrete factory classes.

Now we need to introduce the creator class which will take the responsibility of identifying the correct product to be created and will return the relevant instance of the IProduct.

public class ProductCreator
{
	private readonly Dictionary<eProductType, ProductFactory> factories;

	private ProductCreator()
	{
		factories = new Dictionary<eProductType, ProductFactory>
		{
			{ eProductType.PeriodPass, new PeriodPassFactory() },
			{ eProductType.TripPass, new TripPassFactory() },			
			{ eProductType.SJT, new TicketFactory() },
			{ eProductType.RJT, new TicketFactory() }			
		};
	}

	public static ProductCreator InitializeProductCreator() => new ProductCreator();

	public IProduct CreateProduct(eProductType productType)
	{
		IProduct product = factories[productType].GetProduct(productType);
		return product;
	}
}

Here I have used dictionary to store the eProductType enum and their associated ProductFactory implementations. Using of dictionary is inspired from this blog post.

Now we are all set to utilize our factory implementation. We just need to have an instance of the ProductCreator class and an enum value of type eProductType.

By calling CreateProduct method on instance of the ProductCreator class will return us an instance of the class which implements the IProduct interface.

What have we achieved by this implementation?
When we want to introduce a new product we need not modify the existing concrete factories. We just need to implement the IProduct interface and need to introduce a new concrete factory class which will return an instance of the new product. Also we should not forget to add the eProductType association with new implementation of the ProductFactory class in the ProductCreator dictionary.

This way we have decoupled the logic of creating object from the creator and delegated this responsibility to the subclasses which are the concrete factory classes.

Filtering a collection in WPF using CollectionView

Today I will show you how to use CollectionView for filtering a collection.

As per microsoft docs, CollectionView is defined as

Represents a view for grouping, sorting, filtering, and navigating a data collection.

Among various usages mentioned above let us have a look at how filtering can be used.

Requirement:

We have a list of stations and we want to filter the list based on user input received through a textbox.

Solution:

I will use ListView to populate the list of the stations and will filter this list using the text entered in the search text box.

Here is the raw code which contains a text box and a list view.

       <StackPanel Width="300" HorizontalAlignment="Center">
            <TextBox x:Name="txtSearch" Text="{Binding SearchCriteria, UpdateSourceTrigger=PropertyChanged}" TabIndex="0">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="TextChanged">
                        <i:InvokeCommandAction Command="{Binding SearchTextChangedCommand}"/>
                    </i:EventTrigger>
                    <i:EventTrigger EventName="LostFocus">
                        <i:InvokeCommandAction Command="{Binding SearchLostFocusCommand}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </TextBox>

            <ListView x:Name="listViewStation"
                ItemsSource="{Binding StationList}"
                      DisplayMemberPath="StationName"
                      SelectedValue="{Binding SelectedStation}" TabIndex="1">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="LostFocus">
                        <i:InvokeCommandAction Command="{Binding ListViewLostFocusCommand}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </ListView>
        </StackPanel>

I have used Prism framework for auto wiring view model and to define the commands.

Here is the underlying view model’s code for the above mentioned view.

     public class MainWindowViewModel : BindableBase
    {
        private string searchCriteria;

        public string SearchCriteria
        {
            get { return searchCriteria; }
            set { SetProperty(ref searchCriteria, value); }
        }

        private Station selectedStaion;
        public Station SelectedStation
        {
            get { return selectedStaion; }
            set { SetProperty(ref selectedStaion, value); }
        }

        public DelegateCommand WindowLoadedCommand { get; set; }
        public DelegateCommand SearchTextChangedCommand { get; set; }
        public DelegateCommand ListViewLostFocusCommand { get; set; }
        public ObservableCollection<Station> StationList { get;  set;} = new ObservableCollection<Station>();

        public List<Station> stations = new List<Station>();

        public MainWindowViewModel()
        {
            WindowLoadedCommand = new DelegateCommand(WindowLoaded);
            SearchTextChangedCommand = new DelegateCommand(SearchTextChanged);
            ListViewLostFocusCommand = new DelegateCommand(ListViewLostFocus);
        }

        private void ListViewLostFocus()
        {
            //do something with the selected station
        }

        private void SearchTextChanged()
        {
            CollectionViewSource.GetDefaultView(StationList).Refresh();
        }

        private void LoadStationList()
        {
            stations = new List<Station>();
            stations.Add(new Station { StationName = "Mogra", StationId = 1 });
            stations.Add(new Station { StationName = "Dahisar", StationId = 2 });
            stations.Add(new Station { StationName = "Dahanukar Wadi", StationId = 3 });
            stations.Add(new Station { StationName = "Andheri", StationId = 4 });
            stations.Add(new Station { StationName = "National Park", StationId = 5 });
            stations.Add(new Station { StationName = "Gundavali", StationId = 6 });
            stations.Add(new Station { StationName = "Goregaon", StationId = 7 });
            StationList.AddRange(stations);
        }

        private void WindowLoaded()
        {
            LoadStationList();
            CollectionViewSource.GetDefaultView(StationList).Filter = FilterStations;
        }

        private bool FilterStations(object obj)
        {
            if (string.IsNullOrEmpty(SearchCriteria))
                return true;

            Station station = (Station)obj;

            var result = station.StationName.ToLower().StartsWith(SearchCriteria)
                || station.StationName.ToLower().Contains(SearchCriteria);

            return result;
        }
    }

CollectionViewSource class provides a static method GetDefaultView, which accepts the object as a source and returns an object of ICollectionView type. This is the default view which is attached to the given source collection.

ICollectionView has a Predicate named as Filter. This predicate is used to determine if the object passed to it can be included in the view.

I have used this predicate and provided my own implementation by attaching the FilterStations method in WindowLoaded event.

So until now we have set the filter criteria. Now we have to monitor the TextChanged event of text box and have to refresh the ICollectionView of the station collection.
This will trigger the FilterStations delegate and filter out the not required station.
Station names containing the text entered in text box is filtered and shown in the list view.

This filter operation do not change the underlying collection source. It just changes the view.
This is an awesome feature provided by WPF.

Code can be downloaded from Git

WPF MultiDataTrigger and IMultiValueConverter

It’s been a very long since I posted my last article. I am back now with new enthusiasm and with more energy.

So, today I am going to write about how to use MultiDataTrigger and IMultiValueConverter.
Recently I came across a situation where in I had to make a choice between these two.

I won’t say that both serve a same purpose. But there could be some situations where in one has to choose between these two choices.

Before proceeding let us try to understand the concept of MultiDataTrigger and IMultiValueConverter.
Definition of MultiDataTrigger given on docs says that,

“Represents a trigger that applies property values or performs actions when the bound data meet a set of conditions.”

While using MultiDataTrigger in XAML, we need to specify the conditions on which trigger would be activated. Once these conditions are met, a corresponding value in the setter tag would be set against the required property.

Let us have a look at hypothetical example. Application screen is having two check boxes and one text block.
Background color of the textblock needs to be set on click of these check boxes. Conditions for the same are:

  1. Background should be red when none of the check box is checked
  2. Background should be yellow when only first check box is checked
  3. Background should be blue when only second check box is checked
  4. Background should be green when both check boxes are checked

To achieve above condition we will use MultiDataTrigger in following mentioned way.

<StackPanel>
	<CheckBox Content="Weld" Name="cbWeld"/>
	<CheckBox Content="Assembly" Name="cbAssembly"/>               

	<TextBlock Text="Material">
		<TextBlock.Style>
			
<Style TargetType="{x:Type TextBlock}">
				<Style.Triggers>
					<MultiDataTrigger>
						<MultiDataTrigger.Conditions>
							<Condition Binding="{Binding ElementName=cbWeld, Path=IsChecked}" Value="True"/>
							<Condition Binding="{Binding ElementName=cbAssembly, Path=IsChecked}" Value="True"/>
						</MultiDataTrigger.Conditions>
						<Setter Property="Background" Value="Green"></Setter>
					</MultiDataTrigger>
					<MultiDataTrigger>
						<MultiDataTrigger.Conditions>
							<Condition Binding="{Binding ElementName=cbWeld, Path=IsChecked}" Value="False"/>
							<Condition Binding="{Binding ElementName=cbAssembly, Path=IsChecked}" Value="True"/>
						</MultiDataTrigger.Conditions>
						<Setter Property="Background" Value="Blue"></Setter>
					</MultiDataTrigger>
					<MultiDataTrigger>
						<MultiDataTrigger.Conditions>
							<Condition Binding="{Binding ElementName=cbWeld, Path=IsChecked}" Value="True"/>
							<Condition Binding="{Binding ElementName=cbAssembly, Path=IsChecked}" Value="False"/>
						</MultiDataTrigger.Conditions>
						<Setter Property="Background" Value="Yellow"></Setter>
					</MultiDataTrigger>
					<MultiDataTrigger>
						<MultiDataTrigger.Conditions>
							<Condition Binding="{Binding ElementName=cbWeld, Path=IsChecked}" Value="False"/>
							<Condition Binding="{Binding ElementName=cbAssembly, Path=IsChecked}" Value="False"/>
						</MultiDataTrigger.Conditions>
						<Setter Property="Background" Value="Red"></Setter>
					</MultiDataTrigger>
				</Style.Triggers>
			</Style>


		</TextBlock.Style>
	</TextBlock>
</StackPane>

Here I have used more than one MultiDataTrigger to achieve the objective. In every condition of MultiDataTrigger, different values of check boxes are monitored.
Background property of the textblock is set accordingly.
But the problem with this approach is that, MultiDataTrigger needs to be repeated in XAML to cater different requirements.

This problem can be solved using IMultiValueConverter. Documentation for IMultiValueConverter can be found here. IMultiValueConverter is used with Multibinding. In Multibinding, more that one binding can be specified and IMultiValueConverter can be used to convert the bound values to a single desired value.

Here we will bind IsChecked property and will implement IMultiValueConverter to convert the boolean values of check boxes to Brushes. This converted value would be assigned to Background property of the Textblock.

Let us implement IMultiValueConverter.

public class BooleanToColorConverter : IMultiValueConverter
{
	public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
	{
		bool cb1 = (bool)values[0];
		bool cb2 = (bool)values[1];

		if (cb1 && cb2)
			return Brushes.Green;
		else if (cb1 && !cb2)
			return Brushes.Yellow;
		else if (!cb1 && cb2)
			return Brushes.Blue;
		else
			return Brushes.Red;
	}

	public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
	{
		return null;
	}
}

To use this BooleanToColorConverter, it’s namespace needs to be included in XAML and a resource needs to be defined for it.

<Window x:Class="WpfBasics.MainWindow"
        xmlns:custom="clr-namespace:WpfBasics">
<Window.Resources>        
	<custom:BooleanToColorConverter x:Key="ColorConverter"/>
</Window.Resources>
<StackPanel>
	<CheckBox Content="Weld" Name="cbWeld"/>
	<CheckBox Content="Assembly" Name="cbAssembly"/>               

	<TextBlock Text="Material">
		<TextBlock.Style>
			
<Style TargetType="{x:Type TextBlock}">
				<Setter Property="Background">
					<Setter.Value>
						<MultiBinding Converter="{StaticResource ColorConverter}">
							<Binding ElementName="cbWeld" Path="IsChecked"></Binding>
							<Binding ElementName="cbAssembly" Path="IsChecked"></Binding>
						</MultiBinding>
					</Setter.Value>
				</Setter>
			</Style>

		</TextBlock.Style>
	</TextBlock>
</StackPanel>
</Window>

Above code looks more elegant than the previous one. In Setter’s value, MultiBinding is set with the Converter.
BooleanToColorConverter accepts the values from various bindings and returns a desired color. This color is used as a value in setter for Background property of TextBlock.

So we have achieved the desired result using two different solutions.
Enjoy coding!!

How to implement a Singleton pattern in C#

Singleton design pattern is one of the creational design pattern, originally designed by Gang of Fours.
Sometimes we want to have only a single point access to the functionality of the class. Our code expects that every time an instance of the class gets created it should return only a single instance of the class. In such situations this pattern come in handy.

There are many ways to create a class which returns a single instance. I am going to show one of it.

Implementation

I will create a private constructor of the class and will create a static property to get the access of the single instance of our class. Singleton object gets created lazily. i.e. an instance of the class gets created when a request to get the instance has been initialized first time.

I am going to show example from my one of the post which I wrote. In this post I had shown you how to host a WCF service in a window service.

In that post, WCF service is exposed to outside world, which can be accessed by many clients and messages received from all the requests are to be dispatched to SelfHostService class. So this makes a perfect scenario to expose our SelfHostService class as a singleton.

Lets have a look at a code which makes our class as singleton.

public class SelfHostService : ServiceBase
{
    private static SelfHostService instance = null;
    private static readonly object padlock = new object();
 
    //a private constructor
    SelfHostService()
    {       
    }
 
    //public static property to access the instance of the SelfHostService class
    public static SelfHostService Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                    instance = new SelfHostService();
 
                return instance;
            }
        }
    }
}

In above code a static property named Instance of type SelfHostService is created. This Instance property makes sure that only one instance is returned.

I have used lock statement to ensure that our code remains thread safe.i.e it assures that only one instance will get created of SelfHostService class.

This is one of the many ways to implement a singleton pattern in C#. To conclude, I can say that it would be more appropriate to make a singleton class as a Sealed class.

Enjoy Coding!!!!!

Do not forget to share this post if you like it.

Create window service using Topshelf

There are various ways to create a windows service. We can create a window service project from a standard visual studio template, or we can create a console application and can extend a ServiceBase class which will convert our application to windows service.

In all these above methods we have to write a lot of manual code to configure our application so that it will function properly, besides our business logic.

Wouldn’t it be nice to get rid of all these config related stuff and to just focus on actual service functionality, without knowing how ServiceBase works.

Yes, that is absolutely possible. There is an open source Windows Service Framework TopShelf developed for .net platform.

TopShelf makes task of creating a window service very easy. More documentation about topshelf can be found at documentation.

Lets us try our hand at coding a window service using TopShelf. We will also deploy it with a single command from command prompt.

Create a console application named as WinServTopShelf.

We will have to add a reference of Topshelf.dll in our console application. There are multiple ways to add the reference. You can use NuGet Package Manager or binaries can be directly downloaded from GitHub.

I am going with a second method. Download a zip file and unzip it. Include a reference of Topshelf.dll in WinServTopShelf console application project.

Now, add a new class named as WinTopShelf in this application. We will add two methods in this class which are Start() and Stop() as shown below

public void Start()
{
}

public void Stop()
{
}

Now Lets start writing our service logic.

public class WinTopShelf
{
	Timer timer;

	public WinTopShelf()
	{
		timer = new Timer();            
	}

	public void Start()
	{
	}

	public void Stop()
	{
	}
}

In above code I have initialized a timer class member in constructor.

I am going to create a timer based service, to which a dedicated task will be assigned. This task will be executed after elapsed time ticks which we will of course configure in the code.

Now let us write a task which would be assigned to ElapsedEventHandler event of timer.
Our task will create a file at C:\TopShelf\task.txt location and will append the text in this file.

public class WinTopShelf
{
	Timer timer;

	public WinTopShelf()
	{
		timer = new Timer();            
	}

	private void DoWork(object sender, ElapsedEventArgs e)
	{
		using (var writer = new StreamWriter(@"C:\TopShelf\task.txt", true))
		{
			writer.WriteLine(DateTime.Now + " Topshelf has made windows service development very easy");
		}
	}

	public void Start()
	{
		timer.Interval = 60000;
		timer.Elapsed += new ElapsedEventHandler(DoWork);
		timer.Start();
	}

	public void Stop()
	{
		timer.Stop();
	}        
}

Above code is self explanatory. Now I will show you how to integrate Topshelf’s capabilities to convert our this simple console application to a window service.

While creating a project, a default class Program is added, in which Main method resides.
This Main method is the entry point of the application.

To start with TopShelf, we have to use Topshelf namespace.

TopShelf provides HostFactory class to facilitate different tasks. In Main() method we just have to write a logic using HostFactory.Run() method, in which we will write a very simple and readable code which is analogous to the implementation of ServiceBase class.

static void Main(string[] args)
{
	HostFactory.Run(r =>
	{
		r.Service<WinTopShelf>
		  (service =>
		  {
			  service.ConstructUsing(instance => new WinTopShelf());
			  service.WhenStarted(instance => instance.Start());
			  service.WhenStopped(instance => instance.Stop());
		  });
	});
}

In above code, r.Service specifies that WinTopShelf should be used as the service class.

service.ConstructUsing(instance => new WinTopShelf()) statement specifies which constructor to be used to create an instance of WinTopShelf class.

service.WhenStarted(instance => instance.Start()) statement specifies method to be executed when service starts.

service.WhenStopped(instance => instance.Stop()) statement specifies method to be executed when service stops.

I will add some more essential code as shown below:

static void Main(string[] args)
{
	HostFactory.Run(r =>
	{
		r.Service<WinTopShelf>
		  (service =>
				  {
					  service.ConstructUsing(instance => new WinTopShelf());
					  service.WhenStarted(instance => instance.Start());
					  service.WhenStopped(instance => instance.Stop());
				  });
				  
		r.RunAsLocalService();

		r.SetDisplayName("Topshelf facilitated service");

		r.SetDescription("This service has been created using a TopShelf open source framework for creating a windows serviecs.");
	}
            );
}							  

r.RunAsLocalService() specifies that how to run the service when it gets installed. I chose to run the service as a local service. Other alternatives are RunAsLocalSystem(), RunAsNetworkService() and RunAsPrompt().

SetDisplayName and SetDescription are used to set the display name and description of the service which can be seen in the service control manager console.

So our service is now ready to compile and install. Compile our project WinServTopShelf.

Let us install this service. Run a command prompt as an administrator and navigate to the directory where you have to place the WinServTopShelf.exe and other compiled assemblies.

Execute WinServTopShelf.exe install command. Done!!!!!! Our service has been installed.

installation

Now to start the service you need to open the service control manager and search for service name which we have configured as Topshelf facilitated service.

scm

You can start the service and it will run smoothly. To see the output open a file C:\TopShelf\task.txt on your machine and see the result.

To summarize this we can say that it is very easy and quick way to create a window service using TopShelf and you should have a knowledge of lambda expression and syntax to use it.

A complete code sample can be downloaded from GitHub. This code sample is created using Visual Studio 2015.

Enjoy Coding!!!!

Do not forget to share this post if you liked the content.

Buy books from Amazon

Dispatcher object in WPF for multi-threading

Today I am going to show you how to use dispatcher object in WPF application. But before starting lets have some insights on dispatcher objects. DispatcherObject is meant for any object that wants to be accessed only in the thread that created it. Many WPF classes are derived from DispatcherObject class.

When a WPF application starts, two threads are spawned by the WPF application. One background thread for managing the UI and another for rendering the various controls on UI. As a developer many of the times we do not deal directly with the rendering thread. We just put required controls in the UI and implement their code behind.

UI thread picks each control to be rendered and places it in the Dispatcher. Dispatcher queue processes each control on priority basis.

I think that is enough to have the basic idea WPF threads. Now lets move back to usage of DispatcherObject.

Since Dispatcher also processes each control one by one, our application can’t leverage the power of multi threading to make the application responsive.

While developing WPF application, we often encounter a situation where in a button click or some other events take longer time to process. This can be due to fetching heavy data or might be some other time consuming task.

If we write code for this long running task in an event, WPF application has to wait till that task gets finished and ultimately freezes our app.

At this time a DispatcherObject can come to our rescue and can make our application responsive.

To demonstrate this concept I have created a WPF application in visual studio 2015.

I have added two buttons and two text boxes in this WPF application. XAML code for the same looks as below

<Window x:Class="DiapatcherDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DiapatcherDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button Name="btnLong" Click="btnLong_Click" Background="DarkSeaGreen" Width="200" HorizontalAlignment="Center">Start a long running task</Button>
            <TextBox Name="txtInfo" Background="Salmon">Task not started yet</TextBox>
            <Button Name="btnCurrent" Click="btnCurrent_Click" Background="CadetBlue" Width="200" HorizontalAlignment="Center">Do other tasks</Button>
            <TextBox Name="txtCurrent" Background="Moccasin">Result of other tasks</TextBox>
        </StackPanel>
    </Grid>
</Window>

We will use first button to start a long running task. Meanwhile we can use functionality of second button while long running task initiated by first button is still running.

Code behind for this application is

private delegate void CalculateTimeElapsed();
DateTime currentDateTime;
static int count = 0;

private void btnLong_Click(object sender, RoutedEventArgs e)
{
    btnLong.IsEnabled = false;
    currentDateTime = DateTime.Now;
    
    Thread longRunningThread = new Thread(new ThreadStart(delegate ()  { Thread.Sleep(10000); Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new CalculateTimeElapsed(PostLongRunningTasks)); }));
    longRunningThread.Start();
}

In above event, a thread has been initiated. In this thread a long running task is performed which is Thread.Sleep(10000) in our case. After this we have instructed thread delegate to invoke a method
PostLongRunningTasks on applications Dispatcher object, because a button has been created from Application’s thread. In this method we can alter/change/assign any existing WPF controls present in current application.

Lets have a look into this method’s implementation

private void PostLongRunningTasks()
{
    txtInfo.Text = "Total time elapsed required to finish the task is : " + (DateTime.Now - currentDateTime);
    btnLong.IsEnabled = true;
}

Since above method is attached to BeginInvoke, it runs asynchronously on the application thread(as we have attached it to application’s Dispatcher object).

Below is the implementation of the second button, which remains responsive while long running task initiated by first button is going on.

private void btnCurrent_Click(object sender, RoutedEventArgs e)
{
    txtCurrent.Text = "Above button is clicked " + ++count + " times";
}

This is how we can implement multi threading in WPF. There are many other ways to implement multi threading and this is one of them.

Here are the screen shots of the application.

before running a task

before running a task

after runing task

after running task

Complete code sample can be downloaded from Git