NotiCOO.Core.Publisher 1.0.0

dotnet add package NotiCOO.Core.Publisher --version 1.0.0
                    
NuGet\Install-Package NotiCOO.Core.Publisher -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NotiCOO.Core.Publisher" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NotiCOO.Core.Publisher" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="NotiCOO.Core.Publisher" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NotiCOO.Core.Publisher --version 1.0.0
                    
#r "nuget: NotiCOO.Core.Publisher, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NotiCOO.Core.Publisher@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NotiCOO.Core.Publisher&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=NotiCOO.Core.Publisher&version=1.0.0
                    
Install as a Cake Tool

NotiCOO.Core.Publisher

Message broker publisher wrapper library for the NotiCOO notification system.

Overview

This package provides a simple, dependency injection-friendly way to publish notifications to message brokers (currently supports RabbitMQ). It supports broker-agnostic configuration through environment variables, making it ideal for containerized and cloud deployments.

Features

  • ✅ Broker-agnostic configuration for message publishing
  • ✅ Currently supports RabbitMQ with extensible design for other brokers
  • ✅ Environment variable configuration support
  • ✅ Dependency injection integration
  • ✅ Support for different message priorities
  • ✅ Automatic connection and channel management
  • ✅ Disposable pattern for resource cleanup
  • ✅ Retry logic for failed notification deliveries

Installation

Install the package:

dotnet add package NotiCOO.Core.Publisher

Usage

Basic Setup

Add to your Program.cs or service configuration:

using NotiCOO.Core.Publisher.Extensions;

var builder = Host.CreateApplicationBuilder(args);

// Add configuration sources including environment variables
builder.Configuration
    .AddJsonFile("appsettings.json", optional: true)
    .AddEnvironmentVariables()
    .AddCommandLine(args);

// Register Publisher services with environment variable support
builder.Services.AddNotiCOOCorePublisher();

var host = builder.Build();

Using the Publisher

Basic Usage

Inject and use INotificationPublisher in your services:

using NotiCOO.Core.Publisher.Interfaces;
using NotiCOO.Core.Models;

public class NotificationService
{

    public NotificationService()
    {
    }

    public async Task SendNotificationAsync()
    {
        var notification = new NotificationMessage
        {
            Title = "Hello World",
            Body = "This is a test notification",
            Priority = NotificationPriority.High
        };

        using (var publisher = new NotificationPublisher()     ) {
            // Send the notification

            var messageId = publisher.SendNotification(notification);
            Console.WriteLine($"Message sent with ID: {messageId}");
        }
    }
}

Real-World Usage Examples from NotiCOO.Consumer

Based on the production implementation in NotiCOO.Consumer.Services.PushSingleClientService:

1. Publishing User Notifications with Retry Logic
using Microsoft.Extensions.Options;
using NotiCOO.Core.Publisher.Services;
using NotiCOO.Core.Models;

public class PushSingleClientService
{
    private readonly NotiCooConfig _noticooConfig;
    private const int MAX_RETRY_COUNT = 5;

    public PushSingleClientService(IOptions<NotiCooConfig> notiCooConfig)
    {
        _noticooConfig = notiCooConfig.Value;
    }

    // Example: Republishing failed tokens with retry count
    private async Task RepublishFailedTokens(NotificationMessage originalMessage, 
        NotificationResult result, int newRetryCount)
    {
        try
        {
            // Get failed tokens by matching indices
            var failedTokens = new List<string>();
            for (int i = 0; i < result.TokenResults.Count && i < originalMessage.DeviceTokens.Count; i++)
            {
                if (!result.TokenResults[i].IsSuccess)
                {
                    failedTokens.Add(originalMessage.DeviceTokens[i]);
                }
            }

            if (failedTokens.Any())
            {
                // Create new message with only failed tokens
                var retryMessage = new NotificationMessage
                {
                    MessageId = originalMessage.MessageId,
                    ClientId = originalMessage.ClientId,
                    Title = originalMessage.Title,
                    Body = originalMessage.Body,
                    ImageUrl = originalMessage.ImageUrl,
                    Data = new Dictionary<string, string>(originalMessage.Data),
                    Topic = originalMessage.Topic,
                    Condition = originalMessage.Condition,
                    Priority = NotificationPriority.High,  // Retry messages should be high priority
                    ScheduledTime = originalMessage.ScheduledTime,
                    DeviceTokens = failedTokens
                };

                using (var publisherNotif = new NotificationPublisher(_noticooConfig))
                {
                    // Publish the retry message with retry count
                    var republishResult = publisherNotif.SendUserNotification(retryMessage, newRetryCount);

                    // Log the republish result
                    if (!string.IsNullOrEmpty(republishResult))
                    {
                        Logger.LogInformation("Republished message {OriginalMessageId} with {FailedTokenCount} failed tokens (Retry {RetryCount}/{MaxRetry})",
                            originalMessage.MessageId, failedTokens.Count, newRetryCount, MAX_RETRY_COUNT);
                    }
                    else
                    {
                        Logger.LogError("Failed to republish message {MessageId} for retry {RetryCount}",
                            originalMessage.MessageId, newRetryCount);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Error republishing failed tokens for message {MessageId}", originalMessage.MessageId);
            throw;
        }
    }
}
2. Logging Notification Results
// Example: Logging successful notifications
if (shouldAck)
{
    Logger.LogInformation("Successfully processed single client message: {MessageId} for client: {ClientId}. All {TotalTokens} notifications sent successfully",
        message.MessageId, message.ClientId, notificationResult.TotalTokens);

    using (var publisherNotif = new NotificationPublisher(_noticooConfig))
    {
        publisherNotif.SendLogNotification(message, notificationResult);
    }
}
else
{
    // Log failures
    Logger.LogWarning("Single client message processing completed with failures: {MessageId} for client: {ClientId}. Success: {SuccessCount}/{TotalTokens}, Failures: {FailureCount}",
        message.MessageId, message.ClientId, notificationResult.SuccessCount, notificationResult.TotalTokens, notificationResult.FailureCount);

    using (var publisherNotif = new NotificationPublisher(_noticooConfig))
    {
        publisherNotif.SendLogNotification(message, notificationResult);
    }
}
3. Configuration Injection Pattern
// Constructor injection for NotiCooConfig
public class YourService
{
    private readonly NotiCooConfig _noticooConfig;

    public YourService(IOptions<NotiCooConfig> notiCooConfig)
    {
        _noticooConfig = notiCooConfig.Value;
    }

    public async Task ProcessNotificationAsync()
    {
        // Always use 'using' statement for proper disposal
        using (var publisher = new NotificationPublisher(_noticooConfig))
        {
            var notification = new NotificationMessage
            {
                MessageId = Guid.NewGuid().ToString(),
                ClientId = "client-123",
                Title = "Important Update",
                Body = "Your request has been processed",
                Priority = NotificationPriority.High,
                DeviceTokens = new List<string> { "device-token-1", "device-token-2" }
            };

            // Send with optional retry count
            var result = publisher.SendUserNotification(notification, retryCount: 1);
            
            if (!string.IsNullOrEmpty(result))
            {
                Console.WriteLine($"Notification sent successfully: {result}");
            }
            else
            {
                Console.WriteLine("Failed to send notification");
            }
        }
    }
}

Key Methods

SendUserNotification

Publishes a notification message to the message broker queue.

string SendUserNotification(NotificationMessage message, int retryCount = 0)
  • Parameters:
    • message: The notification message to send
    • retryCount: Optional retry count for tracking republish attempts
  • Returns: Message ID if successful, empty string if failed
SendLogNotification

Logs notification results for monitoring and auditing.

void SendLogNotification(NotificationMessage message, NotificationResult result)
  • Parameters:
    • message: The original notification message
    • result: The result of the notification delivery attempt

Configuration

Environment Variables

The publisher supports the following environment variables with the NOTICOO_CONFIG__ prefix:

Environment Variable Description Default
NOTICOO_CONFIG__BrokerHost Message broker hostname localhost
NOTICOO_CONFIG__BrokerPort Message broker port 5672
NOTICOO_CONFIG__BrokerUserName Message broker username guest
NOTICOO_CONFIG__BrokerPassword Message broker password guest
NOTICOO_CONFIG__VirtualHost RabbitMQ virtual host /
NOTICOO_CONFIG__TopicName Topic/Exchange name notifications
NOTICOO_CONFIG__QueueName Queue name notification-queue
NOTICOO_CONFIG__RoutingKey Routing key notification.singleclient
NOTICOO_CONFIG__Durable Queue durability true
NOTICOO_CONFIG__AutoDelete Auto-delete queue false
NOTICOO_CONFIG__Exclusive Exclusive queue false
NOTICOO_CONFIG__PrefetchCount Message prefetch count 1

appsettings.json Configuration

You can also configure through appsettings.json:

{
  "NOTICOO_CONFIG": {
    "BrokerHost": "rabbitmq.example.com",
    "BrokerPort": 5672,
    "BrokerUserName": "publisher",
    "BrokerPassword": "your-password",
    "VirtualHost": "/",
    "TopicName": "notifications-prod",
    "QueueName": "notification-queue-prod",
    "RoutingKey": "notification.singleclient.prod",
    "Durable": true,
    "AutoDelete": false,
    "Exclusive": false,
    "PrefetchCount": 1
  }
}

Custom Configuration

For custom configurations, you can provide your own NotiCooConfig:

var customConfig = new NotiCooConfig
{
    BrokerHost = "my-rabbitmq-server",
    BrokerPort = 5672,
    BrokerUserName = "myuser",
    BrokerPassword = "mypassword",
    TopicName = "my-exchange"
};

builder.Services.AddNotiCOOCorePublisher(customConfig);

Environment Examples

Command Line / Shell

# Set all required environment variables
export NOTICOO_CONFIG__BrokerHost="rabbitmq.example.com"
export NOTICOO_CONFIG__BrokerPort="5672"
export NOTICOO_CONFIG__BrokerUserName="publisher"
export NOTICOO_CONFIG__BrokerPassword="your-secure-password"
export NOTICOO_CONFIG__VirtualHost="/"
export NOTICOO_CONFIG__TopicName="notifications"
export NOTICOO_CONFIG__QueueName="notification-queue"
export NOTICOO_CONFIG__RoutingKey="notification.singleclient"
export NOTICOO_CONFIG__Durable="true"
export NOTICOO_CONFIG__AutoDelete="false"
export NOTICOO_CONFIG__Exclusive="false"
export NOTICOO_CONFIG__PrefetchCount="1"

# Firebase Configuration
export NOTICOO_FIREBASE__ProjectId="your-firebase-project-id"
export NOTICOO_FIREBASE__ServiceAccountKeyPath="/path/to/firebase-service-account.json"

Docker

# Environment variables for Docker containers
ENV NOTICOO_CONFIG__BrokerHost=rabbitmq
ENV NOTICOO_CONFIG__BrokerPort=5672
ENV NOTICOO_CONFIG__BrokerUserName=publisher
ENV NOTICOO_CONFIG__BrokerPassword=publisher-password
ENV NOTICOO_CONFIG__VirtualHost=/
ENV NOTICOO_CONFIG__TopicName=notifications
ENV NOTICOO_CONFIG__QueueName=notification-queue
ENV NOTICOO_CONFIG__RoutingKey=notification.singleclient
ENV NOTICOO_CONFIG__Durable=true
ENV NOTICOO_CONFIG__AutoDelete=false
ENV NOTICOO_CONFIG__Exclusive=false
ENV NOTICOO_CONFIG__PrefetchCount=1

# Firebase Configuration
ENV NOTICOO_FIREBASE__ProjectId=your-firebase-project-id
ENV NOTICOO_FIREBASE__ServiceAccountKeyPath=/app/firebase-service-account.json

Dependencies

Package Version Description
NotiCOO.Core 1.0.0 Core models and utilities
RabbitMQ.Client 7.1.2 RabbitMQ .NET client library
Microsoft.Extensions.Configuration 9.0.6 Configuration abstractions
Microsoft.Extensions.Configuration.Binder 8.0.0 Configuration binding extensions
Microsoft.Extensions.DependencyInjection.Abstractions 8.0.0 Dependency injection abstractions
Microsoft.Extensions.Hosting.Abstractions 8.0.0 Hosting abstractions
Microsoft.Extensions.Logging.Abstractions 8.0.0 Logging abstractions
Microsoft.Extensions.Options 8.0.0 Options pattern support
Newtonsoft.Json 13.0.1 JSON serialization library

NuGet Package

Package ID: NotiCOO.Core.Publisher

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 156 7/28/2025