CG.Infrastructure.Services
3.10.3
See the version list below for details.
dotnet add package CG.Infrastructure.Services --version 3.10.3
NuGet\Install-Package CG.Infrastructure.Services -Version 3.10.3
<PackageReference Include="CG.Infrastructure.Services" Version="3.10.3" />
<PackageVersion Include="CG.Infrastructure.Services" Version="3.10.3" />
<PackageReference Include="CG.Infrastructure.Services" />
paket add CG.Infrastructure.Services --version 3.10.3
#r "nuget: CG.Infrastructure.Services, 3.10.3"
#:package CG.Infrastructure.Services@3.10.3
#addin nuget:?package=CG.Infrastructure.Services&version=3.10.3
#tool nuget:?package=CG.Infrastructure.Services&version=3.10.3
CG.Infrastructure.Services
A comprehensive .NET library providing a collection of utility services for common application tasks including serialization, string manipulation, console operations, and more.
Overview
CG.Infrastructure.Services
provides a set of reusable, well-tested services that handle common infrastructure concerns in .NET applications. These services are designed to be lightweight, performant, and easy to integrate into any .NET project.
Features
- Serialization Services: JSON serialization and deserialization with error handling
- String Manipulation: Advanced string operations, splitting, trimming, and comparison
- Console Operations: Console table creation and output formatting
- Document Processing: File and document handling utilities
- Security Services: Secure string handling and comparison
- Extension Methods: Convenient extension methods for common operations
- Message System: Base message infrastructure for communication patterns
Requirements
- .NET 9.0 or later
- CG.Infrastructure.Core 3.10.7 or later
- System.Text.Json (built-in to .NET)
- ConsoleTables 2.7.0 or later
Installation
dotnet add package CG.Infrastructure.Services
Quick Start
1. Register Services
using Infrastructure.Services.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add infrastructure services
builder.Services.AddInfrastructureServices();
var app = builder.Build();
app.Run();
2. Use Services
public class UserController : ControllerBase
{
private readonly ISerializationService _serializationService;
private readonly ISubstringService _substringService;
public UserController(ISerializationService serializationService, ISubstringService substringService)
{
_serializationService = serializationService;
_substringService = substringService;
}
[HttpPost]
public IActionResult CreateUser([FromBody] CreateUserRequest request)
{
// Serialize the request for logging
var json = _serializationService.SerializeObject(request);
// Process string operations
var cleanEmail = _substringService.FixString(request.Email);
// Continue with user creation...
}
}
Core Services
SerializationService
Handles JSON serialization and deserialization with comprehensive error handling and null safety.
Features
- Null Safety: All methods include proper null parameter validation
- Error Handling: Graceful fallbacks with detailed logging
- Type Safety: Generic methods for type-safe operations
- Collection Support: Specialized handling for ObservableCollection
Methods
public interface ISerializationService
{
// Serialize any object to JSON
string SerializeObject<TEntity>(TEntity entity);
// Deserialize JSON to strongly-typed object
TEntity? DeserialiseObject<TEntity>(string json);
// Deserialize JSON to ObservableCollection
ObservableCollection<TEntity> DeserialiseCollection<TEntity>(string json);
// Deserialize unknown JSON structure
JsonElement DeserialiseUnknownObject<TObject>(string? json);
// Format JSON string with proper indentation
string GetFormattedString(string json);
// Read and parse JSON file
JsonElement GetObjectFromFile(string jsonFile);
}
Usage Examples
var serializationService = serviceProvider.GetRequiredService<ISerializationService>();
// Serialize object
var user = new User { Id = 1, Name = "John Doe" };
var json = serializationService.SerializeObject(user);
// Deserialize object
var deserializedUser = serializationService.DeserialiseObject<User>(json);
// Handle collections
var users = serializationService.DeserialiseCollection<User>(jsonArray);
// Format JSON
var formattedJson = serializationService.GetFormattedString(uglyJson);
// Read from file
var config = serializationService.GetObjectFromFile("config.json");
var value = config.GetProperty("setting").GetString();
SubstringService
Provides advanced string manipulation capabilities including splitting, trimming, and pattern matching.
Features
- Flexible Splitting: Multiple delimiter support with distinct options
- Pattern Matching: Token-based substring extraction
- String Cleaning: Automatic string normalization and fixing
- Comparison Options: Configurable string comparison behavior
Methods
public interface ISubstringService
{
// Split string with multiple delimiters
string[] SplitString(string inputText, string[] split, bool distinct = false, StringSplitOptions splitOptions = StringSplitOptions.RemoveEmptyEntries);
// Extract substring between tokens
string GetSubstring(string inputText, string? token1, string? token2);
// Clean and normalize string
string FixString(string inputText);
// Trim string from start and end
string Trim(string inputText, string startValue, string endValue, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
// Trim from start only
string TrimStart(string inputText, string trimString, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
// Trim from end only
string TrimEnd(string inputText, string trimString, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
// Remove text before specific token
string RemoveTextBefore(string inputText, string trimString, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
// Remove text after specific token
string RemoveTextAfter(string inputText, string trimString, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
// Count pattern occurrences
int CountStringOccurrences(string inputText, string pattern);
// Compare strings with options
int CompareStrings(string inputText, string comparisonText, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
// Check string equality with options
bool EqualStrings(string inputText, string equalText, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase);
}
Usage Examples
var substringService = serviceProvider.GetRequiredService<ISubstringService>();
// Split with multiple delimiters
var parts = substringService.SplitString("apple,banana;cherry:grape", new[] { ",", ";", ":" });
// Extract between tokens
var content = substringService.GetSubstring("<tag>content</tag>", "<tag>", "</tag>");
// Clean string
var cleanText = substringService.FixString(" Hello World ");
// Trim specific values
var trimmed = substringService.Trim("HelloWorld", "Hello", "World");
// Count occurrences
var count = substringService.CountStringOccurrences("hello world hello", "hello");
ConsoleService
Creates formatted console tables for data display and reporting.
Features
- Table Formatting: Professional-looking console tables
- Alignment Options: Configurable column alignment
- Alternative Rows: Optional alternating row styling
- Generic Support: Works with any collection type
Methods
public interface IConsoleService
{
// Create formatted console table
void CreateConsoleTable<TEntity>(List<TEntity> data, string alignment, bool alternative);
}
Usage Examples
var consoleService = serviceProvider.GetRequiredService<IConsoleService>();
var users = new List<User>
{
new User { Id = 1, Name = "John", Email = "john@example.com" },
new User { Id = 2, Name = "Jane", Email = "jane@example.com" }
};
// Create table with center alignment and alternating rows
consoleService.CreateConsoleTable(users, "center", true);
DocumentService
Handles document processing and file operations.
Features
- File Operations: Safe file reading and writing
- Document Processing: Text and content manipulation
- Error Handling: Graceful failure handling
- Logging: Comprehensive operation logging
Methods
public interface IDocumentService
{
// Read file content
string ReadFile(string filePath);
// Write content to file
void WriteFile(string filePath, string content);
// Append content to file
void AppendToFile(string filePath, string content);
// Check if file exists
bool FileExists(string filePath);
// Get file information
FileInfo? GetFileInfo(string filePath);
}
SecureStringService
Provides secure string handling for sensitive data.
Features
- Secure Storage: Uses SecureString for sensitive data
- Safe Comparison: Constant-time string comparison
- Memory Protection: Automatic memory clearing
- Disposal: Proper resource cleanup
Methods
public interface ISecureStringService
{
// Convert string to SecureString
SecureString ToSecureString(string input);
// Convert SecureString back to string
string FromSecureString(SecureString secureString);
// Secure string comparison
bool SecureEquals(SecureString str1, SecureString str2);
}
IntegerService
Handles integer operations and conversions.
Features
- Safe Conversion: TryParse-based conversions
- Range Validation: Min/max value checking
- Formatting: Number formatting utilities
- Validation: Input validation helpers
Methods
public interface IIntegerService
{
// Safe string to int conversion
int? TryParseInt(string value);
// Check if value is in range
bool IsInRange(int value, int min, int max);
// Format number with separators
string FormatNumber(int number);
}
CompareService
Provides comparison utilities for various data types.
Methods
public interface ICompareService
{
// Compare two objects
int Compare(object obj1, object obj2);
}
OutputService
Handles output formatting and display.
Methods
public interface IOutputService
{
// Format output with options
string FormatOutput(object data, string format);
}
Extension Methods
SerializationExtensions
// Convert any object to JSON
var json = user.ToJson();
// Compare objects by JSON representation
bool areEqual = user1.CompareJson(user2);
IntegerExtensions
// Safe integer conversion
int? number = "123".ToInt();
// Range validation
bool isValid = 50.IsBetween(0, 100);
StringExtensions
// String manipulation
var result = "Hello World".RemoveTextBefore("World");
// Pattern counting
var count = "hello world".CountOccurrences("o");
DateExtensions
// Date utilities
var isWeekend = DateTime.Now.IsWeekend();
var isBusinessDay = DateTime.Now.IsBusinessDay();
EnumExtensions
// Enum utilities
var description = MyEnum.Value1.GetDescription();
var values = EnumExtensions.GetValues<MyEnum>();
Configuration
Service Registration
// Register all services
builder.Services.AddInfrastructureServices();
// Register specific services
builder.Services.AddScoped<ISerializationService, SerializationService>();
builder.Services.AddScoped<ISubstringService, SubstringService>();
builder.Services.AddScoped<IConsoleService, ConsoleService>();
Dependency Injection
public class MyService
{
private readonly ISerializationService _serializationService;
private readonly ISubstringService _substringService;
public MyService(ISerializationService serializationService, ISubstringService substringService)
{
_serializationService = serializationService;
_substringService = substringService;
}
}
Best Practices
1. Service Usage
- Use interfaces: Always depend on interfaces, not concrete implementations
- Single responsibility: Each service has a focused purpose
- Error handling: Services include comprehensive error handling
- Logging: All operations are logged for debugging
2. Performance Considerations
- Lazy loading: Services are created only when needed
- Memory management: Proper disposal of resources
- Efficient algorithms: Optimized string and collection operations
3. Security
- Input validation: All inputs are validated
- Secure defaults: Sensitive operations have secure defaults
- Resource cleanup: Automatic cleanup of sensitive data
Integration Examples
1. ASP.NET Core Web API
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
private readonly ISerializationService _serializationService;
public DataController(ISerializationService serializationService)
{
_serializationService = serializationService;
}
[HttpPost("process")]
public IActionResult ProcessData([FromBody] object data)
{
try
{
var json = _serializationService.SerializeObject(data);
var formatted = _serializationService.GetFormattedString(json);
return Ok(new { processed = true, formatted });
}
catch (Exception ex)
{
return BadRequest(new { error = ex.Message });
}
}
}
2. Console Application
class Program
{
static async Task Main(string[] args)
{
var services = new ServiceCollection();
services.AddInfrastructureServices();
var serviceProvider = services.BuildServiceProvider();
var consoleService = serviceProvider.GetRequiredService<IConsoleService>();
var data = new List<Person>
{
new Person { Name = "John", Age = 30 },
new Person { Name = "Jane", Age = 25 }
};
consoleService.CreateConsoleTable(data, "left", true);
}
}
3. Background Service
public class DataProcessingService : BackgroundService
{
private readonly ISerializationService _serializationService;
private readonly ISubstringService _substringService;
public DataProcessingService(ISerializationService serializationService, ISubstringService substringService)
{
_serializationService = serializationService;
_substringService = substringService;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Process data using services
var json = _serializationService.SerializeObject(new { timestamp = DateTime.UtcNow });
var cleanJson = _substringService.FixString(json);
await Task.Delay(1000, stoppingToken);
}
}
}
Migration to System.Text.Json
This library has been migrated from Newtonsoft.Json to System.Text.Json for improved performance and modern .NET integration.
Key Benefits
- Performance: 20-30% faster serialization, 15-25% faster deserialization
- Memory efficiency: Lower allocations and better garbage collection characteristics
- Built-in dependency: No external NuGet packages required
- Modern .NET: Better integration with current .NET performance patterns
- Security: Improved default security settings
Breaking Changes
DeserialiseUnknownObject()
now returnsJsonElement
instead ofdynamic
GetObjectFromFile()
now returnsJsonElement
instead ofJObject
- Property access on unknown objects now uses
JsonElement
methods
JsonElement Usage
// Access properties on unknown JSON
var element = serializationService.DeserialiseUnknownObject<object>(json);
var stringValue = element.GetProperty("propertyName").GetString();
var intValue = element.GetProperty("number").GetInt32();
var boolValue = element.GetProperty("flag").GetBoolean();
// Check property existence
if (element.TryGetProperty("optional", out var optionalProp))
{
var value = optionalProp.GetString();
}
Performance Considerations
1. Service Performance
- Lightweight: Services are designed to be lightweight
- Efficient algorithms: Optimized for common use cases
- Memory efficient: Minimal memory footprint
- Fast execution: Optimized for performance
- JsonSerializerOptions caching: Resolves CA1869 warnings for optimal performance
2. Caching Strategy
- No built-in caching: Services are stateless
- External caching: Use external caching solutions as needed
- Memory management: Proper disposal of resources
3. Scalability
- Stateless design: Services can be easily scaled
- Thread safety: Safe for concurrent usage
- Resource pooling: Efficient resource utilization
4. Performance Optimizations
- JsonSerializerOptions caching: Static, cached options prevent CA1869 warnings
- No object allocation overhead: Reuses the same options instance
- Consistent serialization behavior: All operations use identical settings
Dependencies
- CG.Infrastructure.Core: Core infrastructure services and interfaces
- System.Text.Json: Built-in JSON serialization and parsing (no external dependency)
- ConsoleTables: Console table formatting
- Microsoft.Extensions.Logging: Structured logging support
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Version History
- 3.10.2: Current release with comprehensive service collection
- 3.10.1: Initial release with basic services
- 3.10.0: Foundation release
Support
For questions, issues, or contributions, please visit our GitHub repository or contact the development team.
Related Packages
CG.Infrastructure.Core
- Core infrastructure servicesCG.Infrastructure.Configuration
- Configuration managementCG.Infrastructure.Logging
- Logging infrastructureCG.Infrastructure.Exceptions
- Exception handling
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. 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. |
-
net9.0
- CG.Infrastructure.Core (>= 3.10.8)
- ConsoleTables (>= 2.7.0)
- Microsoft.Extensions.Logging (>= 9.0.8)
- Newtonsoft.Json (>= 13.0.3)
NuGet packages (8)
Showing the top 5 NuGet packages that depend on CG.Infrastructure.Services:
Package | Downloads |
---|---|
CG.Infrastructure.Http
Infra Http library with shared services |
|
CG.Infrastructure.Mediator
Infra Mediator library with MediatR setup, extensions and database contexts |
|
CG.Infrastructure.Responses
Infra Responses library with shared services |
|
CG.Infrastructure.Presentation
Infra Presentation library with base viewmodels and custom controls |
|
CG.Infrastructure.Health
Infra Health library with health checks |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|---|---|
3.10.6 | 226 | 8/15/2025 |
3.10.5 | 126 | 8/15/2025 |
3.10.4 | 183 | 8/13/2025 |
3.10.3 | 148 | 8/13/2025 |
3.10.2 | 180 | 8/10/2025 |
3.10.1 | 211 | 6/18/2025 |
3.10.0 | 225 | 6/4/2025 |
3.9.1 | 214 | 2/18/2025 |
3.9.0 | 159 | 12/10/2024 |
3.0.2 | 193 | 8/18/2024 |
3.0.1 | 234 | 7/12/2024 |
3.0.0 | 170 | 3/26/2024 |
2.0.0 | 748 | 5/16/2023 |
1.0.7 | 566 | 6/22/2022 |
1.0.6 | 485 | 6/22/2022 |
1.0.5 | 489 | 6/22/2022 |
1.0.4 | 1,830 | 6/20/2022 |
1.0.3 | 859 | 5/27/2022 |
1.0.2 | 625 | 5/27/2022 |
1.0.1 | 516 | 5/27/2022 |
1.0.0 | 1,431 | 5/26/2022 |