CG.Infrastructure.Services
3.10.6
dotnet add package CG.Infrastructure.Services --version 3.10.6
NuGet\Install-Package CG.Infrastructure.Services -Version 3.10.6
<PackageReference Include="CG.Infrastructure.Services" Version="3.10.6" />
<PackageVersion Include="CG.Infrastructure.Services" Version="3.10.6" />
<PackageReference Include="CG.Infrastructure.Services" />
paket add CG.Infrastructure.Services --version 3.10.6
#r "nuget: CG.Infrastructure.Services, 3.10.6"
#:package CG.Infrastructure.Services@3.10.6
#addin nuget:?package=CG.Infrastructure.Services&version=3.10.6
#tool nuget:?package=CG.Infrastructure.Services&version=3.10.6
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 and dynamic object support
- 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
- Newtonsoft.Json 13.0.3 or later
- 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 as dynamic object
dynamic? DeserialiseUnknownObject<TObject>(string? json);
// Format JSON string with proper indentation
string GetFormattedString(string json);
// Read and parse JSON file as JToken
JToken GetObjectFromFile(string jsonFile);
// Read and parse JSON file as dynamic object (easier property access)
dynamic? GetObjectFromFileAsDynamic(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 as JToken
var config = serializationService.GetObjectFromFile("config.json");
var value = config["setting"]?.ToString();
// Read from file as dynamic (easier property access)
var dynamicConfig = serializationService.GetObjectFromFileAsDynamic("config.json");
var dynamicValue = dynamicConfig?.setting?.ToString();
// Handle unknown JSON structures dynamically
var unknownData = serializationService.DeserialiseUnknownObject<object>(jsonString);
if (unknownData != null)
{
var propertyValue = unknownData.propertyName?.ToString();
}
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 Newtonsoft.Json
This library uses Newtonsoft.Json for comprehensive JSON handling with dynamic object support.
Key Benefits
- Dynamic Object Support: Full runtime dynamic object access with dot notation
- Flexible JSON Handling: JToken provides flexible JSON structure manipulation
- Mature Library: Extensive features and excellent compatibility
- Runtime Flexibility: Access unknown JSON properties dynamically at runtime
- Better Error Handling: Comprehensive error handling and fallback options
Dynamic Object Features
DeserialiseUnknownObject()
returnsdynamic?
for runtime property accessGetObjectFromFile()
returnsJToken
for programmatic JSON manipulationGetObjectFromFileAsDynamic()
returnsdynamic?
for easy property access- All methods provide proper null handling and error recovery
Dynamic Object Usage
// Access properties on unknown JSON dynamically
var dynamicData = serializationService.DeserialiseUnknownObject<object>(json);
if (dynamicData != null)
{
var stringValue = dynamicData.propertyName?.ToString();
var intValue = (int?)dynamicData.number;
var nestedValue = dynamicData.nested?.subProperty?.ToString();
}
// Read JSON file as dynamic object
var guildData = serializationService.GetObjectFromFileAsDynamic("guild.json");
if (guildData != null)
{
var memberCount = (int?)guildData.data?.members?.Count;
var guildName = guildData.data?.guild_name?.ToString();
// Access nested properties easily
foreach (var member in guildData.data?.members ?? new dynamic[0])
{
var allyCode = member.ally_code?.ToString();
var playerName = member.player_name?.ToString();
if (!string.IsNullOrEmpty(allyCode))
{
// Process member data...
}
}
}
JToken Usage
// Access properties programmatically with JToken
var config = serializationService.GetObjectFromFile("config.json");
if (config is JObject jObject)
{
var setting = jObject["setting"]?.ToString();
var number = jObject["number"]?.Value<int>();
// Check property existence
if (jObject.ContainsKey("optional"))
{
var optionalValue = jObject["optional"]?.ToString();
}
}
Benefits of Newtonsoft.Json:
- True Dynamic Objects: Runtime property access with dot notation
- Flexible JSON Handling: JToken handles any JSON structure
- Better Error Recovery: Graceful handling of malformed JSON
- Runtime Flexibility: Access unknown properties without compile-time knowledge
- Mature Ecosystem: Extensive documentation and community support
When to Use Each Approach:
Use
GetObjectFromFile
(JToken) when you need:- Programmatic JSON manipulation
- Property existence checking
- Type-safe property access
- JSON structure validation
Use
GetObjectFromFileAsDynamic
when you need:- Easy property access with dot notation
- Runtime property discovery
- Dynamic property access
- Simplified JSON navigation
Use
DeserialiseUnknownObject
when you need:- Handle completely unknown JSON structures
- Runtime property exploration
- Dynamic data processing
- Flexible JSON handling
## 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
- **JsonSerializerSettings caching**: Cached settings 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
- **JsonSerializerSettings caching**: Static, cached settings prevent repeated configuration
- **No object allocation overhead**: Reuses the same settings instance
- **Consistent serialization behavior**: All operations use identical settings
- **Dynamic object optimization**: Efficient runtime property access
## Dependencies
- **CG.Infrastructure.Core**: Core infrastructure services and interfaces
- **Newtonsoft.Json**: Comprehensive JSON serialization and parsing with dynamic object support
- **ConsoleTables**: Console table formatting
- **Microsoft.Extensions.Logging**: Structured logging support
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request
## License
This project is licensed under the MIT License - see the [LICENSE](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](https://github.com/your-username/your-repo) or contact the development team.
## Related Packages
- `CG.Infrastructure.Core` - Core infrastructure services
- `CG.Infrastructure.Configuration` - Configuration management
- `CG.Infrastructure.Logging` - Logging infrastructure
- `CG.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 | 565 | 6/22/2022 |
1.0.6 | 484 | 6/22/2022 |
1.0.5 | 488 | 6/22/2022 |
1.0.4 | 1,829 | 6/20/2022 |
1.0.3 | 858 | 5/27/2022 |
1.0.2 | 624 | 5/27/2022 |
1.0.1 | 515 | 5/27/2022 |
1.0.0 | 1,430 | 5/26/2022 |