What, Why, and How of Microservices?

What are Microservices?

Historically applications were Monolithic applications where the architecture was a unified and closely coupled integrated unit. Microservices, on the contrary, are smaller independent unified business modules. Each module in Microservices performs its own unique business functionality, at times with dedicated databases.

Monolith and Microservices

As shown in the above image, the architecture of Microservices consists of independent smaller units, which are interconnected and managed with the help of API Gateway.

Why opt for Microservices instead of Monolithic Applications?

A Monolithic application is a big container with a collection of different smaller independent parts combined and coupled tightly together, which creates varied inseparable disadvantages.

Here are a few disadvantages of Monolithic services.

• Inflexible – Monolithic applications cannot be built using different technologies.
• Unreliable – One bug or issue in the application may result in the shutdown of the entire system.
• Not Scalable – The tightly coupled nature of a Monolithic application does not scale easily, as workloads cannot be easily distributed across multiple nodes or hardware.
• Hinders continuous deployment – Continuous delivery and deployment in short cycles of time is difficult due to the monolithic nature of the application
• Longer development timelines – The development of Monolithic applications requires lengthy timelines since every feature demands rebuilding of the entire application.
• Complex applications –Incorporating changes in complex monolithic applications become expensive and a maintenance nightmare.

As mentioned earlier, a microservices application is a collection of small independent services designed for different business purposes. In Microservices, each individual service is self-contained. Communication with each self-contained unit is managed by an API Gateway. There are various API Gateways available, and the client can communicate with different business functions of Microservices via the API Gateway.

Features of Microservices

• Decoupled Components – Decoupled services in Microservices architecture enables the entire application to be built, modified, and scaled up quickly with ease.
• Componentization –As each service is an independent component, they can be easily individually replaced and upgraded.

• Undivided business capability –Each Microservice is effortless and focuses on a single business capability

• Autonomy – Developers and teams can work with minimal dependencies, thus increasing development speed and turnaround time.
• Continuous delivery – Allows frequent releases of features by systematic automation of application creation, testing, and approval.
• Responsibility – Microservices treat applications as products and not projects, ensuring the responsibility is in-built.
• Decentralized governance – With no fixed or standardized tool or any technology patterns, developers have the freedom to choose tools based on the requirements to accomplish the job within stipulated timelines.
• Agility – New features can be added easily and quickly developed. A Microservices architecture supports agile development.

Advantages of Microservices

• Independent development – all services are independent of their business purposes and usage.
• Independent deployment –The architecture of Microservices allows services to be individually deployed.
• Isolation of fault – the system continues to function even if one service or a part of the application ceases to work.
• Mixed technologies stack – it is not mandatory to use only one of the platforms for development. We can use multiple platforms and built Microservices architecture as per the need of the application.
• Individual scaling – scale different individual components and deploy them individually without affecting other components.

Best Practices to Design Microservices

• Separate data store for each Microservices
• Maintain the level of code maturity
• Separate build for each Microservice
• Deploy services into containers
• Treat server as stateless

Disadvantages of Microservices

• Huge number of services makes application management tough to track
• The developer will require to solve issues pertaining to Network latency and load balancing

How to create Microservices and API Gateway interface?

Note: This is for those who are familiar with ASP.Net project concepts.

In this demo, we’ll cover the following points,

1. Create two Microservices
2. Create an API Gateway
3. For creating the demo project VS2019 or VS Code, .Net Core 3.1 SDK needs to be installed on the machine

Steps to Create a Microservices Demo Project

Step 1
• Create two .Net Core web API template project for different purposes
• First, UserService project for user data purpose
• Second, ProductService project for product data purpose
• Create UserController in UserService project and ProductController in ProductService
• Add simple action into the controller that returns the string for testing purpose
• If required, connect API project with the database

Simplemicroservice

Step 2 – Test the above web API project with the help of postman individually

1.) Product Service Output

Product service output

2.) User Service Output

User service output

 

Step 3 – Create .net core web empty template project for API Gateway with the desired name. In this instance, we chose ‘APIGateway’

Step 4 – Include the dependency of ocelot API Gateway from NuGet package manager

Ocelot

Step 5 –
• Create a JSON file to configure API Gateway for web API and assign a name. In this instance, it is ‘ocelot.json’
• Include the following code text to the JSON file for configuring the API Gateway. In this demo project, API Gateway is used for routing purpose. API Gateway serves different purposes such as:
o Routing
o Caching
o Logging
o Authentication
o Authorization
o Load balancing
o Service Discovery

Ocelot.JSON

Note: In the above image, detail of ocelot.JSON are in the comments

Some details of ocelot.JSON are considered while configuring API Gateway from the ocelot package.

• The request forwarded to URL set byDownstreamPathTemplate, DownstreamHostAndPorts and DownstreamScheme
• Ocelot will use the UpstreamPathTemplate URL to identify where the DownstreamPathTemplate request is to be used.
• Ocelot uses UpstreamHttpMethod to make a difference between multiple requests with the same URLs but with different HTTP verbs. We can set a specific list of HTTP Methods or set a blank to allow any of them.

Step 6 – Configure the JSON file for application configuration as shown below in Program.cs file

Program.cs file

Step 7 – Set Ocelot middleware ASP.Net project as shown below in Startup.cs file

Startup.cs file

Step 8 – Run the application to test the working condition of API Gateway. Before running, make sure all projects are marked as startup projects. To handle request from the API Gateway application UserService and ProductService must be running.

Note: If you are testing project through VS2019, the following steps will help you mark all projects as the startup project.

Step 9 – Right-click on the main solution and click on the property, alter the settings as shown below

Simplemicroservice image 2
Step 10 – Below screen shows the final output. When you run the project, all three startup projects will be running, at times, on different ports. We need to check if Customer and User service received a call from the API Gateway project, as shown below.

API Gateway project

 

Hope this article has helped you understand the know-how of Microservices. If you have any questions, please feel free to drop them in our comments section. Happy to Help!
Happy Coding!

Exporting JSON data from your ASP .Net Web API to a Microsoft Excel Spreadsheet using Macro Programming

Exporting your data to an excel spread sheet is a very common requirement, but what if this data is coming from a  database as a Web API  service . This is possible using Macro Programming.

In this article, I would like to give a  brief overview of how to export your data from the ASP .net Web API controller to your Excel Spread Sheet on a specific look up field using a live example.

Example:  We had a sport lookup field which populated the data from a second tab sheet where there was Master data.

Sports lookup field on Excel tab sheet 1

Sport Look Up Field
We had a web application developed in MVC and a Web API. The web application had a feature where the end-users could download an excel file template with columns of static data on one sheet and master data present on the second sheet using data validations (Feature of Excel). As the data fields increased we had to keep updating this excel template with the static data for selection so that the end users could use the template with the latest data. As this was quite a tedious process, we decided to write a program in macro. The macro program was supposed to get the latest data from the database and populate the excel file with the same fields whenever you opened it.

Master values for the Sports look-up field from the second tab sheet.

Mastervalues 2

On the Web API side, we had the controller Method Get() returning a JSON object with all the data in it. You can name it as GetSportsData(). On the macro program side, we consumed the service from the API with the below code.

Here is the following code snippet which we wrote for macro programming. The programming langauge which was used here is VB;

Dim requestObject As Object

Dim URL As String

Dim boolAsync As Boolean

Dim strResponse As String

Set requestObject = CreateObject(“MSXML2.XMLHTTP”)

URL = http://mylittleblog.com/api/GetSportsData <>

boolAsync = True

With requestObject

.Open “GET”, URL, boolAsync

.SetRequestHeader “Content-Type”, “application/json”

.Send

While requestObject.readyState <> 4

DoEvents

Wend

strResponse = .ResponseText

End With

The variable ‘strResponse‘ contains the JSON object and the data from this JSON object can be used in the sheet and formatted into rows and columns.

The readyState property holds the status of the XMLHttpRequest which you can find in any AJAX Server reponses.

readyState

The various status of the XMLHttpRequest.

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Points to consider:

You must make sure that while executing the macro program, the WEB API service must be running or else we will not get the latest data from the API.
If you are not able to hit the WEB API endpoint, then you can write the code to populate the data from the master tab sheet as it may happen that the user may not be connected to the internet.

This way, one can find a solution to connect to the WEB API world from the Microsoft Excel sheet. We at MetaSys Software have been building such customized solutions using Microsoft technologies for clients across different industry verticals. For more info. https://www.metasyssoftware.com/dot-net

What is EWS?

Exchange Web Services is an Application Program Interface (API) by Microsoft that allows programmers to fetch Microsoft Exchange items including calendars, contacts and emails. It can be used to read the email box and retrieve emails along with all the metadata such as headers, body and attachments. This is useful when the same information needs to be extracted from Exchange items repeatedly. The example I’m using in this article is retrieval of order details from emails, and is based on a recent assignment for a client at MetaSys.

How does it help?

The client wanted the ability to read the email inbox, import the order to the system and then send the email with the order details generated to the sales representatives.

With regular mail reading API’s the process would have been as follows. First the email is read, secondly the order is imported, and finally a new function is called that sends a new email with new order details to the sales representative. In this case the details of the requester are saved and reused for sending the confirmation email.

Using the EWS managed API, a more efficient solution was developed. The email was directly forwarded from the email inbox, without the need to create a separate email for the order confirmation. The confirmation email is created directly from the received email object, as is the forwarded email to the sales representative. The following code sample shows how the forwarded email is created and sent:

ResponseMessage responseMessage = message.CreateForward();
responseMessage.ToRecipients.Add(email.FromAddress);
responseMessage.BodyPrefix = messageBodyPrefix;
responseMessage.Send();

In the code snippet above, “message” is the object which contains all the details of the order email and we use it to create the new forward email without saving any details to the local system or variables.

Similarly, we can use reply functionality of the API to maintain the email conversation chain by using the following code:

bool replyToAll = true;
ResponseMessage responseMessage = message.CreateReply(replyToAll);

string emailbody= “Please find the attachment below.”;
responseMessage.BodyPrefix = emailbody;
responseMessage.Send();

Setting the “replyToAll” variable to true specifies that mail will be forwarded to all the recipients who were present in the original conversation. The text contained in the variable “emailbody” will be on the top of the email body of the conversation.

Additional features of EWS managed API

EWS provides useful features for dealing with emails with invalid delivery email addresses. The postmaster bot may send a mail delivery failure email to the same inbox, which can cause issues with the importing of other orders. These issues can be resolved in EWS by checking the subject lines, and automatically deleting delivery failure emails, or moving them to a separate folder. These orders can then be separately corrected and resent without interfering with the remaining orders in the inbox.

The following code sample can be used to move all the email items from the inbox to the “DidNotDelivered” folder:

Folder rootfolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot);
rootfolder.Load();
foreach (Folder folder in rootfolder.FindFolders(new FolderView(100)))
{
FindItemsResults findResults =
service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
// The if below checks if the folder “DidNotDelivered” is present in the email box
if (folder.DisplayName == “DidNotDelivered”)
{
var fid = folder.Id;
foreach (Item item in findResults.Items)
{
item.Load();
item.Move(fid);
}
}
}

This is how EWS helped us simplify the processing of emails with minimal lines of code.

We hope that this article gives you some useful ideas for dealing with Microsoft Exchange using EWS. If you are having issues, feel free to get in touch with us at https://www.metasyssoftware.com/dot-net