Skip to main content

Utilities Overview

MasLazu.AspNet provides a comprehensive collection of utility libraries designed to accelerate development with production-ready, enterprise-grade functionality. Each utility is built following clean architecture principles and can be used independently or together.

๐ŸŽฏ Available Utilitiesโ€‹

๐Ÿ“ง EmailSenderโ€‹

Professional email delivery with beautiful templates

A comprehensive email sending solution supporting multiple providers (Gmail, SendGrid) with responsive HTML templates, Razor rendering, and enterprise features.

Key Features:

  • Multi-provider support (Gmail API, SendGrid)
  • Professional responsive email templates
  • Razor template engine with C# models
  • Fluent API for easy email construction
  • Attachment support and tracking capabilities
  • Security and compliance features

Use Cases:

  • Welcome and onboarding emails
  • Order confirmations and receipts
  • Password reset and security notifications
  • Marketing newsletters and campaigns
  • System notifications and alerts

Quick Start:

var email = new EmailMessageBuilder()
.From("noreply@yourapp.com", "Your Company")
.To("customer@example.com", "John Doe")
.Subject("๐ŸŽ‰ Welcome to Your Company!")
.RenderOptions(new EmailRenderOptions
{
Theme = "Modern",
CompanyName = "Your Company",
PrimaryColor = "#3b82f6"
})
.Model(new { UserName = "John" })
.Build();

await _emailSender.SendEmailAsync(email, _htmlRenderer);

๐Ÿ“– View EmailSender Documentation


๐Ÿ’พ Storageโ€‹

Unified cloud storage abstraction with 13+ providers

A powerful storage abstraction library that provides a single, consistent API for multiple cloud storage providers including AWS S3, Azure Blob Storage, Google Cloud Storage, and more.

Key Features:

  • 13+ storage providers supported
  • Single unified IBlobStorage interface
  • Dependency injection integration
  • Strongly-typed configuration
  • Built on FluentStorage library
  • Production-ready with validation

Supported Providers:

  • Amazon S3, MinIO, DigitalOcean Spaces
  • Azure Blob Storage, Data Lake Gen2, Key Vault
  • Google Cloud Storage
  • Local filesystem and in-memory storage
  • FTP, SFTP, ZIP archives
  • Databricks filesystem

Use Cases:

  • File uploads and downloads
  • Static asset storage and CDN
  • Backup and archival solutions
  • Document management systems
  • Media streaming and processing
  • Cross-cloud data migration

Quick Start:

// Configure in appsettings.json
{
"Storage": {
"Provider": "S3",
"S3": {
"AccessKey": "your-key",
"SecretKey": "your-secret",
"BucketName": "your-bucket",
"Region": "us-east-1"
}
}
}

// Inject and use
public class FileService(IBlobStorage storage)
{
public async Task UploadAsync(string fileName, Stream content)
=> await storage.WriteAsync(fileName, content);
}

๐Ÿ“– View Storage Documentation


๐Ÿงน Data Retentionโ€‹

Configurable data cleanup system

Automatically manage soft-deleted records based on retention policies. Ensure your database stays lean and compliant by permanently deleting or archiving old data on a schedule.

Key Features:

  • Multiple retention strategies (Delete, Archive)
  • Table-specific retention periods
  • Automated background cleanup service
  • Global and table-level toggle switches
  • Extensible for custom cleanup logic

๐Ÿ“– View Data Retention Documentation


๐Ÿ—๏ธ Utility Architectureโ€‹

๐ŸŽฏ Design Principlesโ€‹

1. Independence & Modularityโ€‹

  • Each utility can be used standalone
  • No dependencies between utilities
  • Minimal external dependencies
  • Clear separation of concerns

2. Provider Abstractionโ€‹

  • Support for multiple service providers
  • Unified interfaces across providers
  • Easy provider switching
  • Provider-specific optimizations

3. Production Readyโ€‹

  • Comprehensive error handling
  • Logging and monitoring support
  • Security best practices
  • Performance optimizations

4. Developer Experienceโ€‹

  • Fluent APIs for ease of use
  • Rich documentation and examples
  • Type-safe configurations
  • IntelliSense support

๐Ÿš€ Getting Startedโ€‹

Installation Strategyโ€‹

# Install specific utilities as needed
dotnet add package MasLazu.AspNet.EmailSender.Abstraction
dotnet add package MasLazu.AspNet.EmailSender.Gmail

# Or install the complete utility suite
dotnet add package MasLazu.AspNet.Utilities

Configuration Patternโ€‹

All utilities follow a consistent configuration pattern:

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Register utilities
builder.Services.AddEmailSenderGmail(builder.Configuration);
// Future utilities will follow the same pattern
// builder.Services.AddSmsProvider(builder.Configuration);
// builder.Services.AddFileStorage(builder.Configuration);

var app = builder.Build();

Service Registrationโ€‹

// Utility services are registered with proper lifetimes
services.AddScoped<IEmailSender, GmailEmailService>();
services.AddScoped<IHtmlRenderer, GmailHtmlRenderer>();

// Configuration is bound from appsettings.json
services.Configure<GmailConfiguration>(
builder.Configuration.GetSection("Gmail"));

๐ŸŽฏ Integration Patternsโ€‹

1. Framework Integrationโ€‹

// Utilities work seamlessly with framework services
public class UserService : CrudService<User>
{
private readonly IEmailSender _emailSender;

public async Task<User> CreateAsync(CreateUserRequest request)
{
var user = await base.CreateAsync(request);

// Send welcome email using EmailSender utility
await _emailSender.SendWelcomeEmailAsync(user);

return user;
}
}

2. Module Integrationโ€‹

// Utilities enhance module functionality
public class VerificationService
{
private readonly IEmailSender _emailSender;

public async Task SendVerificationCodeAsync(string email, string code)
{
var emailMessage = new EmailMessageBuilder()
.To(email)
.Subject("๐Ÿ” Your Verification Code")
.RenderOptions(new EmailRenderOptions
{
Theme = "VerificationCode"
})
.Model(new { VerificationCode = code })
.Build();

await _emailSender.SendEmailAsync(emailMessage);
}
}

3. Cross-Utility Communicationโ€‹

// Future utilities will work together
public class NotificationService
{
private readonly IEmailSender _emailSender;
// private readonly ISmsProvider _smsProvider;
// private readonly IPushNotificationService _pushService;

public async Task SendMultiChannelNotificationAsync(
NotificationRequest request)
{
// Send via email
await _emailSender.SendEmailAsync(request.Email);

// Future: Send via SMS
// await _smsProvider.SendSmsAsync(request.Sms);

// Future: Send push notification
// await _pushService.SendAsync(request.Push);
}
}

๐Ÿ“Š Utility Comparisonโ€‹

UtilityPurposeProvidersStatusUse Cases
EmailSenderEmail communicationsGmail, SendGridโœ… AvailableWelcome emails, notifications, marketing
DataRetentionData cleanup serviceSQL DELETE strategyโœ… AvailableDeleting old soft-deleted records
StorageFile managementAWS S3, Azure Blobโœ… AvailableDocument storage, image uploads
PushNotificationsReal-time notificationsFirebase, OneSignal๐Ÿ”„ PlannedApp notifications, alerts
PaymentProcessorPayment processingStripe, PayPal๐Ÿ”„ PlannedE-commerce, subscriptions

๐Ÿ”ง Configuration Examplesโ€‹

Environment-Specific Configurationsโ€‹

// Development
{
"Gmail": {
"ServiceAccountCredentialsPath": "credentials/dev-gmail.json",
"DefaultFromEmail": "dev-noreply@yourapp.com",
"ApplicationName": "YourApp Development"
}
}

// Production
{
"SendGrid": {
"ApiKey": "{{SENDGRID_API_KEY}}",
"DefaultFromEmail": "noreply@yourapp.com",
"EnableClickTracking": true,
"EnableOpenTracking": true
}
}

Provider Switchingโ€‹

// Easy provider switching based on environment
if (builder.Environment.IsDevelopment())
{
// Use Gmail for development
builder.Services.AddEmailSenderGmail(builder.Configuration);
}
else
{
// Use SendGrid for production
builder.Services.AddEmailSenderSendGrid(builder.Configuration);
}

๐ŸŽฏ Best Practicesโ€‹

โœ… Do'sโ€‹

  • Use dependency injection for utility services
  • Configure providers through appsettings.json
  • Implement proper error handling and retry logic
  • Monitor usage and performance metrics
  • Follow security best practices for credentials
  • Use background processing for non-critical operations

โŒ Don'tsโ€‹

  • Don't hardcode configurations in code
  • Don't ignore rate limits and quotas
  • Don't mix utility concerns in business logic
  • Don't forget to handle failures gracefully
  • Don't expose sensitive data in logs
  • Don't block UI threads with utility operations

๐Ÿ”’ Security Considerationsโ€‹

1. Credential Managementโ€‹

// Use secure credential storage
// Azure Key Vault, AWS Secrets Manager, etc.
builder.Configuration.AddAzureKeyVault(keyVaultEndpoint);

// Environment variables for sensitive data
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");

2. Data Protectionโ€‹

// Implement data sanitization
public class SecureEmailService
{
public async Task SendEmailAsync(EmailMessage email)
{
// Remove PII from logs
_logger.LogInformation("Sending email to {EmailHash}",
email.To.First().Address.ComputeHash());

await _emailSender.SendEmailAsync(email);
}
}

3. Rate Limitingโ€‹

// Implement rate limiting
services.AddRateLimiter(options =>
{
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(
httpContext => RateLimitPartition.GetFixedWindowLimiter(
partitionKey: httpContext.User.Identity?.Name ?? "anonymous",
factory: _ => new FixedWindowRateLimiterOptions
{
AutoReplenishment = true,
PermitLimit = 100,
Window = TimeSpan.FromHours(1)
}));
});

๐ŸŽฏ Future Roadmapโ€‹

Q1 2025โ€‹

  • SmsProvider - SMS messaging with Twilio and AWS SNS
  • FileStorage - Cloud file storage with AWS S3 and Azure Blob
  • Enhanced EmailSender - Calendar invites, advanced templates

Q2 2025โ€‹

  • PushNotifications - Real-time notifications with Firebase
  • PaymentProcessor - Payment processing with Stripe
  • CacheProvider - Distributed caching with Redis

Q3 2025โ€‹

  • SearchEngine - Full-text search with Elasticsearch
  • QueueProcessor - Message queuing with RabbitMQ
  • ReportGenerator - PDF/Excel report generation

๐Ÿ“š Next Stepsโ€‹

  1. EmailSender Documentation - Start with email functionality
  2. Framework Overview - Understand core concepts
  3. Module Examples - See utilities in action