# Flexbase and Azure Logic Apps Integration

### 🚀 Overview

FlexBase provides seamless integration with **Azure Logic Apps** through its REST client architecture, enabling enterprise applications to leverage Azure's powerful workflow automation capabilities. This integration allows developers to orchestrate complex business processes, integrate with external systems, and implement sophisticated workflows without writing complex integration code.

### 🏗️ Architecture Overview

#### **FlexBase REST Client Pattern**

FlexBase implements a clean, maintainable pattern for Azure Logic Apps integration:

```
┌─────────────────────────────────────┐
│ Controller Layer (API Endpoint)     │ ← REST API entry point
├─────────────────────────────────────┤
│ Handler Layer (Business Logic)      │ ← Command processing
├─────────────────────────────────────┤
│ REST Client Layer (Integration)     │ ← Azure Logic Apps communication
├─────────────────────────────────────┤
│ Azure Logic Apps (Workflow)         │ ← External workflow processing
└─────────────────────────────────────┘
```

#### **Key Components**

1. **Controller** - REST API endpoint for external access
2. **Handler** - Business logic orchestration and command processing
3. **REST Client** - Azure Logic Apps communication layer
4. **Azure Logic Apps** - External workflow processing and automation

### 🔧 Implementation Example: Logic App Basic Call

#### **1. Controller Layer - API Endpoint**

```csharp
// MiscsController_DemonstrateLogicAppCallBasic.cs
public partial class MiscsController : FlexControllerBridge<MiscsController>
{
    [HttpPost]
    [Route("DemonstrateLogicAppCallBasic")]
    [ProducesResponseType(typeof(BadRequestResult), 400)]
    [ProducesResponseType(typeof(string), 201)]
    public async Task<IActionResult> DemonstrateLogicAppCallBasic([FromBody]DemonstrateLogicAppCallBasicDto dto)
    {
        return await RunService(201, dto, _processMiscsService.DemonstrateLogicAppCallBasic);
    }
}
```

**Key Features:**

* **RESTful API** - Standard HTTP POST endpoint
* **Type Safety** - Strongly-typed DTO parameters
* **Error Handling** - Built-in HTTP status code management
* **FlexBase Integration** - Uses FlexControllerBridge for consistent behavior

#### **2. Handler Layer - Business Logic**

```csharp
// DemonstrateLogicAppCallBasicHandler.cs
public partial class DemonstrateLogicAppCallBasicHandler : IDemonstrateLogicAppCallBasicHandler
{
    protected readonly ILogger<DemonstrateLogicAppCallBasicHandler> _logger;
    protected readonly IFlexHost _flexHost;
    protected MiscsRESTClient _restClient;

    public virtual async Task Execute(DemonstrateLogicAppCallBasicCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        // Convert command to request parameters
        DemonstrateLogicAppCallBasicRequestDto requestParams = new DemonstrateLogicAppCallBasicRequestDto
        {
            // Map command data to request DTO
        };

        // Call Azure Logic App
        var response = await _restClient.DemonstrateLogicAppCallBasic(requestParams);

        // Process response
        var jsonContent = await response.Content.ReadAsStringAsync();
        _logger.LogInformation(jsonContent);

        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Key Features:**

* **Command Pattern** - Encapsulates business operations
* **Dependency Injection** - Clean dependency management
* **Error Handling** - Comprehensive logging and error management
* **Event Publishing** - Domain event integration

#### **3. REST Client Layer - Azure Integration**

```csharp
// MiscsRESTClient.cs
public partial class MiscsRESTClient : LogicAppDemonstrationRESTClientBase, IFlexRESTClientService
{
    public async Task<HttpResponseMessage> DemonstrateLogicAppCallBasic(DemonstrateLogicAppCallBasicRequestDto model)
    {
        var httpClient = _httpClientFactory.CreateClient(LogicAppDemonstrationRESTClientMaster.Name);

        var serializedModel = JsonConvert.SerializeObject(model);

        var request = new HttpRequestMessage(
            HttpMethod.Post,
            $"workflows/{workflowId}/triggers/When_a_HTTP_request_is_received/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2FWhen_a_HTTP_request_is_received%2Frun&sv=1.0&sig={signature}");
        
        request.Content = new StringContent(serializedModel, Encoding.UTF8, "application/json");
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

        return await response.HandleHttpResponse();
    }
}
```

**Key Features:**

* **HTTP Client Factory** - Managed HTTP client lifecycle
* **JSON Serialization** - Automatic object serialization
* **Authentication** - Built-in Azure Logic Apps authentication
* **Error Handling** - FlexBase HTTP response handling

### 🎯 Azure Logic Apps Integration Scenarios

#### **1. HTTP Request Trigger (Basic)**

**Use Case**: Simple workflow initiation via REST API call

```csharp
// Basic HTTP trigger scenario
public async Task<HttpResponseMessage> TriggerBasicWorkflow(WorkflowRequestDto request)
{
    var httpClient = _httpClientFactory.CreateClient("LogicAppClient");
    
    var request = new HttpRequestMessage(
        HttpMethod.Post,
        $"workflows/{workflowId}/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig={signature}");
    
    request.Content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
    
    return await httpClient.SendAsync(request);
}
```

**Business Scenarios:**

* **Order Processing** - Trigger order fulfillment workflow
* **Document Generation** - Generate reports and documents
* **Notification Sending** - Send emails, SMS, or push notifications
* **Data Validation** - Validate and process incoming data

#### **2. Azure Storage Queue Trigger**

**Use Case**: Process messages from Azure Storage Queues

```csharp
// FlexBase Handler for Azure Storage Queue
public class StorageQueueHandler : IStorageQueueHandler
{
    private readonly QueueClient _queueClient;
    private readonly ILogger<StorageQueueHandler> _logger;
    
    public StorageQueueHandler(IConfiguration configuration, ILogger<StorageQueueHandler> logger)
    {
        var connectionString = configuration.GetConnectionString("StorageAccount");
        var queueName = configuration["StorageQueue:QueueName"];
        _queueClient = new QueueClient(connectionString, queueName);
        _logger = logger;
    }
    
    public async Task Execute(ProcessQueueMessageCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        // Send message to Azure Storage Queue
        // Logic App will automatically trigger when message arrives
        var message = new QueueMessageDto
        {
            MessageId = cmd.MessageId,
            Data = cmd.Data,
            Priority = cmd.Priority,
            Timestamp = DateTime.UtcNow
        };
        
        await _queueClient.SendMessageAsync(JsonConvert.SerializeObject(message));
        
        _logger.LogInformation($"Message sent to queue: {cmd.MessageId}");
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Business Scenarios:**

* **Batch Processing** - Process large volumes of data
* **Asynchronous Workflows** - Decouple processing from user requests
* **Retry Logic** - Handle failed operations with automatic retries
* **Load Balancing** - Distribute workload across multiple instances

#### **3. Event Grid Trigger**

**Use Case**: React to Azure Event Grid events

```csharp
// FlexBase Handler for Event Grid
public class EventGridHandler : IEventGridHandler
{
    private readonly EventGridPublisherClient _eventGridClient;
    private readonly ILogger<EventGridHandler> _logger;
    
    public EventGridHandler(IConfiguration configuration, ILogger<EventGridHandler> logger)
    {
        var eventGridEndpoint = configuration["EventGrid:Endpoint"];
        var eventGridKey = configuration["EventGrid:Key"];
        _eventGridClient = new EventGridPublisherClient(
            new Uri(eventGridEndpoint), 
            new AzureKeyCredential(eventGridKey));
        _logger = logger;
    }
    
    public async Task Execute(PublishEventCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var events = new List<EventGridEvent>
        {
            new EventGridEvent(cmd.Subject, cmd.EventType, "1.0", cmd.EventData)
        };
        
        await _eventGridClient.SendEventsAsync(events);
        
        _logger.LogInformation($"Event published: {cmd.EventType}");
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Business Scenarios:**

* **Real-time Processing** - React to system events immediately
* **Integration Events** - Communicate between microservices
* **Audit Logging** - Track system changes and user actions
* **Compliance** - Meet regulatory requirements with event tracking

#### **4. Azure Service Bus Trigger**

**Use Case**: Process messages from Azure Service Bus

```csharp
// FlexBase Handler for Azure Service Bus
public class ServiceBusHandler : IServiceBusHandler
{
    private readonly ServiceBusClient _serviceBusClient;
    private readonly ILogger<ServiceBusHandler> _logger;
    
    public ServiceBusHandler(IConfiguration configuration, ILogger<ServiceBusHandler> logger)
    {
        var connectionString = configuration.GetConnectionString("ServiceBus");
        var queueName = configuration["ServiceBus:QueueName"];
        _serviceBusClient = new ServiceBusClient(connectionString);
        _logger = logger;
    }
    
    public async Task Execute(SendServiceBusMessageCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var sender = _serviceBusClient.CreateSender(cmd.QueueName);
        
        var serviceBusMessage = new ServiceBusMessage(JsonConvert.SerializeObject(cmd.MessageData))
        {
            MessageId = cmd.MessageId,
            Subject = cmd.Subject,
            ContentType = "application/json"
        };
        
        await sender.SendMessageAsync(serviceBusMessage);
        
        _logger.LogInformation($"Message sent to Service Bus: {cmd.MessageId}");
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Business Scenarios:**

* **Enterprise Messaging** - Reliable message delivery
* **Transaction Processing** - Ensure message processing consistency
* **Dead Letter Handling** - Manage failed message processing
* **Topic Subscriptions** - Publish-subscribe messaging patterns

### 🔄 Advanced Integration Patterns

#### **1. Multi-Step Workflow Orchestration with FlexBase Handlers and Subscribers**

FlexBase provides a sophisticated event-driven architecture for complex workflows using **Handlers** and **Subscribers** that seamlessly integrate with **Azure Logic Apps** for business logic execution. This pattern ensures resilience, scalability, and maintainability while leveraging the full power of Azure Logic Apps.

**Example: Order Processing Workflow with Azure Logic Apps Integration**

> **💡 Key Insight**: Each step in the workflow calls Azure Logic Apps to execute complex business logic, while FlexBase handles the orchestration, resilience, and event flow. You get the best of both worlds - FlexBase's robust architecture and Azure Logic Apps' powerful workflow capabilities.

```csharp
// Step 1: Command Handler - Process Payment (Synchronous)
public class ProcessPaymentHandler : IProcessPaymentHandler
{
    private readonly ILogger<ProcessPaymentHandler> _logger;
    private readonly PaymentProcessingRESTClient _restClient;
    
    public ProcessPaymentHandler(ILogger<ProcessPaymentHandler> logger, PaymentProcessingRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(ProcessPaymentCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        // Validate payment data
        if (!ValidatePaymentData(cmd.PaymentData))
        {
            throw new BusinessException("Invalid payment data");
        }
        
        // Process payment via Azure Logic Apps - Complex business logic executed in Logic Apps
        // Logic Apps handles: payment gateway selection, fraud detection, retry logic, compliance checks
        var response = await _restClient.ProcessPayment(cmd.PaymentData);
        
        if (response.IsSuccessStatusCode)
        {
            _logger.LogInformation($"Payment processed successfully for Order: {cmd.OrderId}");
            
            // Fire event to trigger next step - FlexBase handles the orchestration
            await this.Fire("PAYMENT_SUCCESS", serviceBusContext);
        }
        else
        {
            _logger.LogError($"Payment failed for Order: {cmd.OrderId}");
            await this.Fire("PAYMENT_FAILED", serviceBusContext);
        }
    }
}

// Step 2: Event Subscriber - Update Inventory (Asynchronous)
public class UpdateInventorySubscriber : IUpdateInventorySubscriber
{
    private readonly ILogger<UpdateInventorySubscriber> _logger;
    private readonly InventoryRESTClient _restClient;
    
    public UpdateInventorySubscriber(ILogger<UpdateInventorySubscriber> logger, InventoryRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(PaymentProcessedEvent @event, IFlexServiceBusContext serviceBusContext)
    {
        _logger.LogInformation($"Updating inventory for Order: {@event.OrderId}");
        
        // Update inventory via Azure Logic Apps - Complex business logic executed in Logic Apps
        // Logic Apps handles: stock validation, allocation, reservation, low-stock alerts, supplier notifications
        var response = await _restClient.UpdateInventory(@event.OrderItems);
        
        if (response.IsSuccessStatusCode)
        {
            _logger.LogInformation($"Inventory updated successfully for Order: {@event.OrderId}");
            
            // Fire event to trigger next step - FlexBase handles the orchestration
            await this.Fire("INVENTORY_UPDATED", serviceBusContext);
        }
        else
        {
            _logger.LogError($"Inventory update failed for Order: {@event.OrderId}");
            await this.Fire("INVENTORY_UPDATE_FAILED", serviceBusContext);
        }
    }
}

// Step 3: Event Subscriber - Send Notifications (Asynchronous)
public class SendNotificationSubscriber : ISendNotificationSubscriber
{
    private readonly ILogger<SendNotificationSubscriber> _logger;
    private readonly NotificationRESTClient _restClient;
    
    public SendNotificationSubscriber(ILogger<SendNotificationSubscriber> logger, NotificationRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(InventoryUpdatedEvent @event, IFlexServiceBusContext serviceBusContext)
    {
        _logger.LogInformation($"Sending notifications for Order: {@event.OrderId}");
        
        // Send notifications via Azure Logic Apps - Complex business logic executed in Logic Apps
        // Logic Apps handles: email template selection, personalization, multi-channel delivery, delivery tracking
        var response = await _restClient.SendOrderConfirmation(@event.OrderId, @event.CustomerEmail);
        
        if (response.IsSuccessStatusCode)
        {
            _logger.LogInformation($"Notifications sent successfully for Order: {@event.OrderId}");
        }
        else
        {
            _logger.LogError($"Notification sending failed for Order: {@event.OrderId}");
        }
    }
}
```

#### **2. Built-in Resilience in FlexBase Handlers**

FlexBase provides **built-in resilience** through NServiceBus integration, eliminating the need for custom retry logic:

**Automatic Retry Features:**

* **Exponential Backoff**: Automatic retry with increasing delays
* **Dead Letter Queue**: Failed messages moved to DLQ after max retries
* **Circuit Breaker**: Automatic circuit breaking on repeated failures
* **Message Durability**: Messages persisted until successfully processed
* **Idempotency**: Safe to retry operations without side effects

```csharp
// FlexBase handles resilience automatically - no custom retry code needed
public class ProcessPaymentHandler : IProcessPaymentHandler
{
    public async Task Execute(ProcessPaymentCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        // FlexBase automatically handles:
        // - Retry on transient failures
        // - Exponential backoff
        // - Dead letter queue on permanent failures
        // - Message durability and ordering
        
        var response = await _restClient.ProcessPayment(cmd.PaymentData);
        
        // Business logic only - resilience is handled by FlexBase
        if (response.IsSuccessStatusCode)
        {
            await this.Fire("PAYMENT_SUCCESS", serviceBusContext);
        }
    }
}
```

#### **3. FlexBase + Azure Logic Apps: The Perfect Partnership**

**Why This Combination is Powerful:**

1. **FlexBase Handles**: Architecture, resilience, event orchestration, scaling, testing
2. **Azure Logic Apps Handles**: Complex business logic, integrations, visual workflows, connectors
3. **Result**: You get enterprise-grade architecture with powerful business logic execution

**What You Can Build with This Partnership:**

* **Complex Workflows**: Multi-step business processes with visual design
* **System Integrations**: Connect to 400+ services without custom code
* **Data Transformations**: Visual data mapping and transformation
* **Conditional Logic**: Branching workflows based on business rules
* **Error Handling**: Sophisticated retry and compensation logic
* **Monitoring**: Built-in workflow monitoring and analytics

#### **4. FlexBase Handler and Subscriber Pattern**

FlexBase implements a sophisticated **Command-Query-Event** pattern that provides clean separation of concerns and automatic resilience:

**Architecture Flow:**

```
┌─────────────────────────────────────────────────────────────────┐
│ 1. Command Handler (Synchronous)                               │
│    - ProcessPaymentHandler                                     │
│    - Validates data & calls Azure Logic Apps                   │
│    - Fires events on success/failure                          │
├─────────────────────────────────────────────────────────────────┤
│ 2. Event Subscribers (Asynchronous)                           │
│    - UpdateInventorySubscriber (triggered by PaymentProcessedEvent) │
│    - SendNotificationSubscriber (triggered by InventoryUpdatedEvent) │
│    - Each subscriber calls Azure Logic Apps independently     │
└─────────────────────────────────────────────────────────────────┘
```

**Key Benefits:**

1. **Separation of Concerns**: Each handler/subscriber has a single responsibility
2. **Automatic Resilience**: NServiceBus handles retries, dead letter queues, and circuit breakers
3. **Eventual Consistency**: Subscribers process events asynchronously
4. **Scalability**: Each component can be scaled independently
5. **Testability**: Each handler/subscriber can be tested in isolation
6. **Maintainability**: Easy to add/remove workflow steps

**Event Flow Example:**

```csharp
// 1. Command Handler fires event
await this.Fire("PAYMENT_SUCCESS", serviceBusContext);

// 2. Event automatically triggers subscribers
// - UpdateInventorySubscriber.Execute() is called
// - SendNotificationSubscriber.Execute() is called after inventory update

// 3. Each subscriber can fire its own events
await this.Fire("INVENTORY_UPDATED", serviceBusContext);
```

### 🚀 **The Power of FlexBase + Azure Logic Apps: Do Anything, Compromise Nothing**

**You Don't Have to Choose Between Architecture and Business Logic**

Many developers face a dilemma: use a robust enterprise framework (and lose flexibility) or use powerful business logic tools (and lose architectural benefits). With FlexBase + Azure Logic Apps, you get **both**.

#### **🎯 What This Means for You:**

**✅ Keep Your Azure Logic Apps Investment**

* **Visual Workflows**: Continue using the drag-and-drop designer
* **400+ Connectors**: Access all existing Logic Apps connectors
* **No Code Changes**: Your existing Logic Apps workflows work unchanged
* **Familiar Tools**: Use the Azure portal and Logic Apps designer

**✅ Get Enterprise Architecture Benefits**

* **Resilience**: Automatic retry, dead letter queues, circuit breakers
* **Scalability**: Scale handlers and subscribers independently
* **Testing**: Unit test each component in isolation
* **Monitoring**: Comprehensive logging and health checks
* **Security**: Built-in authentication and authorization

**✅ Build Anything You Can Imagine**

* **E-commerce**: Order processing, inventory management, payment flows
* **CRM Integration**: Lead management, customer onboarding, support workflows
* **Document Processing**: PDF generation, approval workflows, compliance
* **IoT**: Device data processing, alerting, automated responses
* **Financial**: Payment processing, fraud detection, reconciliation

#### **🔄 Real-World Example: E-commerce Order Processing**

```csharp
// Your existing Azure Logic Apps workflows remain unchanged
// FlexBase just orchestrates them with enterprise-grade reliability

// 1. Payment Processing Logic App
// - Handles multiple payment gateways
// - Fraud detection algorithms
// - Compliance checks
// - Retry logic for failed payments

// 2. Inventory Management Logic App  
// - Stock validation
// - Allocation algorithms
// - Supplier notifications
// - Low-stock alerts

// 3. Notification Logic App
// - Email template selection
// - Personalization engine
// - Multi-channel delivery
// - Delivery tracking

// FlexBase orchestrates these with:
// - Event-driven architecture
// - Automatic resilience
// - Independent scaling
// - Comprehensive monitoring
```

### 🛠️ FlexBase Integration Benefits

#### **1. Clean Architecture**

* **Separation of Concerns** - Clear boundaries between layers
* **Dependency Injection** - Easy testing and maintenance
* **Type Safety** - Compile-time validation throughout
* **Error Handling** - Consistent error management patterns

#### **2. Scalability**

* **Horizontal Scaling** - Stateless handlers can be scaled independently
* **Load Balancing** - Multiple instances can handle increased load
* **Async Processing** - Non-blocking operations for better performance
* **Resource Management** - Efficient HTTP client lifecycle management

#### **3. Maintainability**

* **Consistent Patterns** - Same structure across all integrations
* **Easy Testing** - Each layer can be tested independently
* **Configuration Management** - Centralized configuration for all integrations
* **Logging and Monitoring** - Built-in logging and monitoring capabilities

#### **4. Enterprise Features**

* **Authentication** - Built-in Azure authentication support
* **Security** - Secure communication with Azure services
* **Compliance** - Audit trails and compliance reporting
* **Monitoring** - Health checks and performance monitoring

### 🚀 Best Practices

#### **1. Error Handling**

```csharp
// Comprehensive error handling
public async Task<HttpResponseMessage> ExecuteWithErrorHandling<T>(T request)
{
    try
    {
        var response = await _restClient.ExecuteLogicApp(request);
        
        if (!response.IsSuccessStatusCode)
        {
            _logger.LogWarning($"Logic App returned {response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
        }
        
        return response;
    }
    catch (HttpRequestException ex)
    {
        _logger.LogError(ex, "HTTP request failed");
        return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
    }
    catch (TaskCanceledException ex)
    {
        _logger.LogError(ex, "Request timeout");
        return new HttpResponseMessage(HttpStatusCode.RequestTimeout);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Unexpected error occurred");
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
}
```

#### **2. Configuration Management**

```csharp
// Configuration-driven integration
public class LogicAppConfiguration
{
    public string BaseUrl { get; set; }
    public string WorkflowId { get; set; }
    public string Signature { get; set; }
    public int TimeoutSeconds { get; set; } = 30;
    public int MaxRetries { get; set; } = 3;
    public bool EnableLogging { get; set; } = true;
}
```

#### **3. Performance Optimization**

```csharp
// Performance-optimized HTTP client
public class OptimizedLogicAppClient
{
    private readonly HttpClient _httpClient;
    
    public OptimizedLogicAppClient(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("LogicAppClient");
        
        // Configure for optimal performance
        _httpClient.Timeout = TimeSpan.FromSeconds(30);
        _httpClient.DefaultRequestHeaders.Add("User-Agent", "FlexBase-Client/1.0");
    }
    
    public async Task<HttpResponseMessage> ExecuteOptimized<T>(T request)
    {
        // Use connection pooling and keep-alive
        var response = await _httpClient.PostAsJsonAsync("workflows/execute", request);
        return response;
    }
}
```

### 🎯 Key Takeaways

#### **FlexBase + Azure Logic Apps = Powerful Integration**

1. **Clean Architecture** - Clear separation of concerns with FlexBase patterns
2. **Multiple Triggers** - Support for HTTP, Storage Queue, Event Grid, and Service Bus
3. **Enterprise Features** - Authentication, security, monitoring, and compliance
4. **Scalability** - Horizontal scaling and load balancing capabilities
5. **Maintainability** - Consistent patterns and easy testing

#### **Business Value**

* **Rapid Development** - Quick integration with Azure Logic Apps
* **Reliable Processing** - Robust error handling and retry logic
* **Cost Effective** - Pay-per-use Azure Logic Apps pricing
* **Future Proof** - Easy to extend and modify as requirements change

### 🔄 Common Azure Logic Apps Flow Examples

#### **1. Email Notification Flow**

**Business Scenario**: Send automated email notifications for order confirmations, password resets, or system alerts.

```csharp
// FlexBase Handler for Email Notification
public class EmailNotificationHandler : IEmailNotificationHandler
{
    private readonly ILogger<EmailNotificationHandler> _logger;
    private readonly EmailNotificationRESTClient _restClient;
    
    public EmailNotificationHandler(ILogger<EmailNotificationHandler> logger, EmailNotificationRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(SendEmailCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var emailRequest = new EmailNotificationRequestDto
        {
            To = cmd.RecipientEmail,
            Subject = cmd.Subject,
            Body = cmd.MessageBody,
            TemplateId = cmd.TemplateId
        };

        var response = await _restClient.SendEmailNotification(emailRequest);
        
        if (response.IsSuccessStatusCode)
        {
            _logger.LogInformation($"Email sent successfully to {cmd.RecipientEmail}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **HTTP Request Trigger** - Receive email request from FlexBase
2. **Condition** - Check if email template exists
3. **Get Template** - Retrieve email template from storage
4. **Send Email** - Send email via Office 365 or SendGrid
5. **Log Result** - Log success/failure to monitoring system

#### **2. Document Generation Flow**

**Business Scenario**: Generate PDF reports, invoices, or contracts automatically.

```csharp
// FlexBase Handler for Document Generation
public class DocumentGenerationHandler : IDocumentGenerationHandler
{
    private readonly ILogger<DocumentGenerationHandler> _logger;
    private readonly DocumentGenerationRESTClient _restClient;
    
    public DocumentGenerationHandler(ILogger<DocumentGenerationHandler> logger, DocumentGenerationRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(GenerateDocumentCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var documentRequest = new DocumentGenerationRequestDto
        {
            DocumentType = cmd.DocumentType,
            TemplateId = cmd.TemplateId,
            Data = cmd.DocumentData,
            OutputFormat = cmd.OutputFormat
        };

        var response = await _restClient.GenerateDocument(documentRequest);
        
        if (response.IsSuccessStatusCode)
        {
            var documentUrl = await response.Content.ReadAsStringAsync();
            _logger.LogInformation($"Document generated: {documentUrl}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **HTTP Request Trigger** - Receive document generation request
2. **Get Template** - Retrieve document template from Azure Storage
3. **Populate Template** - Fill template with provided data
4. **Generate PDF** - Convert to PDF using Azure Functions or third-party service
5. **Store Document** - Save to Azure Blob Storage
6. **Return URL** - Send document URL back to FlexBase

#### **3. Data Synchronization Flow**

**Business Scenario**: Sync data between different systems (CRM, ERP, external APIs).

```csharp
// FlexBase Handler for Data Synchronization
public class DataSyncHandler : IDataSyncHandler
{
    private readonly ILogger<DataSyncHandler> _logger;
    private readonly DataSyncRESTClient _restClient;
    
    public DataSyncHandler(ILogger<DataSyncHandler> logger, DataSyncRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(SyncDataCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var syncRequest = new DataSyncRequestDto
        {
            SourceSystem = cmd.SourceSystem,
            TargetSystem = cmd.TargetSystem,
            DataType = cmd.DataType,
            LastSyncDate = cmd.LastSyncDate
        };

        var response = await _restClient.SyncData(syncRequest);
        
        if (response.IsSuccessStatusCode)
        {
            var syncResult = await response.Content.ReadAsStringAsync();
            _logger.LogInformation($"Data sync completed: {syncResult}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **Recurrence Trigger** - Run every hour or daily
2. **Get Data** - Fetch data from source system (API, database)
3. **Transform Data** - Convert data format for target system
4. **Validate Data** - Check data integrity and business rules
5. **Send to Target** - Push data to target system
6. **Log Results** - Record sync statistics and errors

#### **4. Payment Processing Flow**

**Business Scenario**: Process payments through multiple payment gateways with fallback options.

```csharp
// FlexBase Handler for Payment Processing
public class PaymentProcessingHandler : IPaymentProcessingHandler
{
    private readonly ILogger<PaymentProcessingHandler> _logger;
    private readonly PaymentProcessingRESTClient _restClient;
    
    public PaymentProcessingHandler(ILogger<PaymentProcessingHandler> logger, PaymentProcessingRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(ProcessPaymentCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var paymentRequest = new PaymentProcessingRequestDto
        {
            Amount = cmd.Amount,
            Currency = cmd.Currency,
            PaymentMethod = cmd.PaymentMethod,
            CustomerId = cmd.CustomerId,
            OrderId = cmd.OrderId
        };

        var response = await _restClient.ProcessPayment(paymentRequest);
        
        if (response.IsSuccessStatusCode)
        {
            var paymentResult = await response.Content.ReadAsStringAsync();
            _logger.LogInformation($"Payment processed: {paymentResult}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **HTTP Request Trigger** - Receive payment request
2. **Validate Payment** - Check payment details and business rules
3. **Try Primary Gateway** - Attempt payment with primary provider
4. **Condition** - Check if primary payment succeeded
5. **Try Secondary Gateway** - Fallback to secondary provider if needed
6. **Update Order Status** - Update order status in database
7. **Send Confirmation** - Send payment confirmation email

#### **5. File Processing Flow**

**Business Scenario**: Process uploaded files (images, documents, CSV files) with validation and transformation.

```csharp
// FlexBase Handler for File Processing
public class FileProcessingHandler : IFileProcessingHandler
{
    private readonly ILogger<FileProcessingHandler> _logger;
    private readonly FileProcessingRESTClient _restClient;
    
    public FileProcessingHandler(ILogger<FileProcessingHandler> logger, FileProcessingRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(ProcessFileCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var fileRequest = new FileProcessingRequestDto
        {
            FileUrl = cmd.FileUrl,
            FileType = cmd.FileType,
            ProcessingOptions = cmd.ProcessingOptions,
            OutputFormat = cmd.OutputFormat
        };

        var response = await _restClient.ProcessFile(fileRequest);
        
        if (response.IsSuccessStatusCode)
        {
            var processingResult = await response.Content.ReadAsStringAsync();
            _logger.LogInformation($"File processed: {processingResult}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **HTTP Request Trigger** - Receive file processing request
2. **Download File** - Get file from Azure Blob Storage
3. **Validate File** - Check file format and size
4. **Process File** - Apply transformations (resize images, parse CSV, etc.)
5. **Store Processed File** - Save processed file to storage
6. **Update Database** - Record processing results
7. **Send Notification** - Notify user of completion

#### **6. Approval Workflow Flow**

**Business Scenario**: Implement approval workflows for expenses, leave requests, or document approvals.

```csharp
// FlexBase Handler for Approval Workflow
public class ApprovalWorkflowHandler : IApprovalWorkflowHandler
{
    private readonly ILogger<ApprovalWorkflowHandler> _logger;
    private readonly ApprovalWorkflowRESTClient _restClient;
    
    public ApprovalWorkflowHandler(ILogger<ApprovalWorkflowHandler> logger, ApprovalWorkflowRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(SubmitApprovalCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var approvalRequest = new ApprovalWorkflowRequestDto
        {
            RequestId = cmd.RequestId,
            RequestType = cmd.RequestType,
            RequesterId = cmd.RequesterId,
            ApproverId = cmd.ApproverId,
            RequestData = cmd.RequestData
        };

        var response = await _restClient.SubmitApproval(approvalRequest);
        
        if (response.IsSuccessStatusCode)
        {
            var approvalResult = await response.Content.ReadAsStringAsync();
            _logger.LogInformation($"Approval submitted: {approvalResult}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **HTTP Request Trigger** - Receive approval request
2. **Validate Request** - Check request data and business rules
3. **Send Approval Email** - Send approval request to approver
4. **Wait for Response** - Wait for approver decision (with timeout)
5. **Process Decision** - Handle approval or rejection
6. **Update Status** - Update request status in database
7. **Notify Requester** - Send notification to original requester

#### **7. Integration with External APIs Flow**

**Business Scenario**: Integrate with third-party services like weather APIs, shipping providers, or social media platforms.

```csharp
// FlexBase Handler for External API Integration
public class ExternalApiHandler : IExternalApiHandler
{
    private readonly ILogger<ExternalApiHandler> _logger;
    private readonly ExternalApiRESTClient _restClient;
    
    public ExternalApiHandler(ILogger<ExternalApiHandler> logger, ExternalApiRESTClient restClient)
    {
        _logger = logger;
        _restClient = restClient;
    }
    
    public async Task Execute(CallExternalApiCommand cmd, IFlexServiceBusContext serviceBusContext)
    {
        var apiRequest = new ExternalApiRequestDto
        {
            ApiEndpoint = cmd.ApiEndpoint,
            RequestData = cmd.RequestData,
            Authentication = cmd.Authentication,
            RetryCount = cmd.RetryCount
        };

        var response = await _restClient.CallExternalApi(apiRequest);
        
        if (response.IsSuccessStatusCode)
        {
            var apiResult = await response.Content.ReadAsStringAsync();
            _logger.LogInformation($"External API call successful: {apiResult}");
        }
        
        // Fire domain events if needed
        await this.Fire(EventCondition, serviceBusContext);
    }
}
```

**Azure Logic Apps Flow:**

1. **HTTP Request Trigger** - Receive API call request
2. **Prepare Request** - Format request for external API
3. **Authenticate** - Handle API authentication (OAuth, API keys, etc.)
4. **Call External API** - Make HTTP request to external service
5. **Handle Response** - Process API response
6. **Transform Data** - Convert response to internal format
7. **Return Result** - Send processed data back to FlexBase

### 🎯 Flow Pattern Benefits

#### **1. Reliability**

* **Retry Logic** - Automatic retry on failures
* **Error Handling** - Comprehensive error management
* **Monitoring** - Built-in logging and monitoring
* **Fallback Options** - Alternative paths when primary fails

#### **2. Scalability**

* **Parallel Processing** - Handle multiple requests simultaneously
* **Load Balancing** - Distribute workload across instances
* **Auto-scaling** - Scale based on demand
* **Resource Management** - Efficient resource utilization

#### **3. Maintainability**

* **Visual Design** - Easy to understand and modify
* **Reusable Components** - Common patterns across workflows
* **Version Control** - Track changes and rollback if needed
* **Testing** - Built-in testing capabilities

#### **4. Integration**

* **Multiple Connectors** - Connect to hundreds of services
* **Custom Connectors** - Build custom integrations
* **API Management** - Secure and manage API calls
* **Data Transformation** - Easy data format conversion

***

*This document demonstrates how FlexBase provides a clean, maintainable, and scalable approach to integrating with Azure Logic Apps, enabling enterprise applications to leverage powerful workflow automation capabilities.*
