Azure Logic Apps - Mapping with .NET Application

Azure Logic Apps is a cloud-based service provided by Microsoft Azure that allows you to automate workflows and integrate various applications, data sources, and services across cloud and on-premises environments without writing extensive code.

What are Azure Logic Apps?

Azure Logic Apps provide a visual designer and a rich set of connectors that enable you to create workflows or "logic apps" by connecting different tasks and triggers. These logic apps can automate business processes, data integrations, and workflow orchestrations across diverse systems and platforms.

Why Do We Need Azure Logic Apps?

  1. Simplify Integration: Logic Apps abstract away the complexities of integration by providing a user-friendly interface for creating workflows. This allows developers and IT professionals to focus on business logic rather than plumbing code.
  2. Accelerate Development: With pre-built connectors and templates for popular services like Office 365, Dynamics 365, Salesforce, Azure services, and more, Logic Apps streamline development and reduce time-to-market for new solutions.
  3. Increase Efficiency: By automating repetitive tasks and orchestrating complex workflows, Logic Apps help organizations improve efficiency, reduce manual errors, and increase productivity.

Mapping to .NET Application

Let's consider a scenario where we have a .NET application that needs to process incoming orders from an e-commerce website and send order confirmation emails to customers. We can use Azure Logic Apps to automate this process.

  1. Trigger: Set up a Logic App trigger to listen for new orders placed on the e-commerce website's webhook endpoint.
  2. Data Transformation: Use the built-in data transformation capabilities of Logic Apps to map the incoming order data to the format expected by the .NET application.
  3. Integration: Use a custom connector or HTTP connector in Logic Apps to call an API endpoint exposed by the .NET application, passing the transformed order data.
  4. Processing: In the .NET application, receive the incoming order data, process it, and generate order confirmation emails for customers.
  5. Email Notification: Use another Logic App action to send order confirmation emails using an email connector like Office 365 Outlook or SMTP.

Here's an example of how you can call the .NET application API from Azure Logic Apps using the HTTP connector:

{
    "method": "POST",
    "uri": "https://your-dotnet-app-api.com/api/orders",
    "headers": {
        "Content-Type": "application/json"
    },
    "body": {
        "orderId": "<orderId>",
        "customerName": "<customerName>",
        "email": "<customerEmail>",
        "orderDetails": "<orderDetails>"
    }
}

Example to include the code snippet for handling incoming orders in the .NET application.

Incoming Orders Handling in .NET Application

// WebhookController.cs

using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class WebhookController : ControllerBase
{
    private readonly OrderProcessor _orderProcessor;

    public WebhookController(OrderProcessor orderProcessor)
    {
        _orderProcessor = orderProcessor;
    }

    [HttpPost("order")]
    public IActionResult HandleIncomingOrder(OrderModel order)
    {
        try
        {
            _orderProcessor.ProcessOrder(order);
            return Ok("Order received and processed successfully");
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Failed to process order: {ex.Message}");
        }
    }
}

Order Processor Service in .NET Application

// OrderProcessor.cs

public class OrderProcessor
{
    private readonly OrderService _orderService;

    public OrderProcessor(OrderService orderService)
    {
        _orderService = orderService;
    }

    public void ProcessOrder(OrderModel order)
    {
        // Validate the order (e.g., check for required fields, format)
        if (string.IsNullOrEmpty(order.OrderId) || string.IsNullOrEmpty(order.CustomerName))
        {
            throw new ArgumentException("Invalid order data");
        }

        // Process the order (e.g., save to database, generate confirmation)
        _orderService.SaveOrder(order);
    }
}

Order Service in .NET Application

// OrderService.cs

public class OrderService
{
    public void SaveOrder(OrderModel order)
    {
        // Save the order to the database or perform any other necessary operations
        // For demonstration purposes, we'll just log the order details
        Console.WriteLine($"Order received: ID - {order.OrderId}, Customer - {order.CustomerName}");
    }
}

In the above snippets

  • The WebhookController in the .NET application listens for incoming orders sent to the /api/webhook/order endpoint via HTTP POST requests.
  • The OrderProcessor class processes the incoming orders by validating them and then passing them to the OrderService for further processing.
  • The OrderService class performs the actual processing of the orders, such as saving them to a database or performing other business logic.

we have demonstrated how to handle incoming orders in the .NET application, and now we see how to integrate them seamlessly with Azure Logic Apps for workflow automation.

Azure Logic App to handle incoming orders and call the .NET application's webhook endpoint.

Azure Logic App for Handling Incoming Orders

{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Create_order": {
                "inputs": {
                    "body": {
                        "CustomerName": "<customerName>",
                        "OrderId": "<orderId>",
                        "OrderDetails": "<orderDetails>",
                        "Email": "<customerEmail>"
                    },
                    "method": "post",
                    "uri": "https://your-dotnet-app.com/api/webhook/order"
                },
                "runAfter": {},
                "type": "Http"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {},
        "triggers": {
            "manual": {
                "inputs": {
                    "schema": {}
                },
                "kind": "Http",
                "type": "Request"
            }
        }
    }
}

In the Azure Logic App

  • The trigger is set to "Manual" with an HTTP request trigger, meaning it can be initiated by an external HTTP request.
  • The action "Create_order" sends an HTTP POST request to the .NET application's webhook endpoint (https://your-dotnet-app.com/api/webhook/order) with the order details provided as dynamic content (<customerName>, <orderId>, <orderDetails>, <customerEmail>).

By integrating this Azure Logic App with the .NET application's webhook endpoint, you can easily handle incoming orders and trigger the necessary processing logic within the .NET application.

Now we will include email sending and order processing within the .NET application in the example of integrating Azure Logic Apps with a .NET application for order processing and email notifications.

Order Processing in .NET Application

// OrderController.cs

using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
    [HttpPost]
    public IActionResult ProcessOrder(OrderModel order)
    {
        // Process the order (e.g., save to database, generate confirmation)
        var orderConfirmation = $"Thank you, {order.CustomerName}, for your order!";

        // Send order confirmation email
        EmailService.SendOrderConfirmationEmail(order.Email, orderConfirmation);

        return Ok("Order processed successfully");
    }
}

public class OrderModel
{
    public string OrderId { get; set; }
    public string CustomerName { get; set; }
    public string Email { get; set; }
    public string OrderDetails { get; set; }
}

Email Sending Service in .NET Application

// EmailService.cs

using System.Net;
using System.Net.Mail;

public static class EmailService
{
    public static void SendOrderConfirmationEmail(string recipientEmail, string orderConfirmation)
    {
        var smtpClient = new SmtpClient("smtp.example.com")
        {
            Port = 587,
            Credentials = new NetworkCredential("[email protected]", "your-password"),
            EnableSsl = true,
        };

        var mailMessage = new MailMessage
        {
            From = new MailAddress("[email protected]"),
            Subject = "Order Confirmation",
            Body = orderConfirmation,
        };

        mailMessage.To.Add(recipientEmail);

        smtpClient.Send(mailMessage);
    }
}

Azure Logic Apps Email Sending Action

{
    "type": "action",
    "apiVersion": "2016-06-01",
    "inputs": {
        "host": {
            "connection": {
                "name": "@parameters('$connections')['office365']['connectionId']"
            }
        },
        "method": "post",
        "body": {
            "Subject": "Order Confirmation",
            "Body": "<orderConfirmation>",
            "To": "<customerEmail>"
        },
        "path": "/Mail/Send"
    }
}

In the above snippets

  • The OrderController in the .NET application handles incoming order requests and processes them, including generating the order confirmation message and sending it via email.
  • The EmailService class provides a method SendOrderConfirmationEmail to send order confirmation emails using SMTP.
  • The Azure Logic Apps action sends an email using the Office 365 connector, passing the order confirmation message and recipient email dynamically.

Conclusion

Azure Logic Apps offer a powerful platform for automating workflows and integrating systems in the cloud. By leveraging Logic Apps alongside .NET applications, organizations can streamline business processes, improve efficiency, and drive digital transformation initiatives effectively.

With its intuitive design experience, extensive connector ecosystem, and seamless integration capabilities, Azure Logic Apps empower developers and IT professionals to build scalable and resilient solutions that meet the demands of modern business environments.