![]() |
VOOZH | about |
dotnet add package CG.Infrastructure.Services --version 3.10.7
NuGet\Install-Package CG.Infrastructure.Services -Version 3.10.7
<PackageReference Include="CG.Infrastructure.Services" Version="3.10.7" />
<PackageVersion Include="CG.Infrastructure.Services" Version="3.10.7" />Directory.Packages.props
<PackageReference Include="CG.Infrastructure.Services" />Project file
paket add CG.Infrastructure.Services --version 3.10.7
#r "nuget: CG.Infrastructure.Services, 3.10.7"
#:package CG.Infrastructure.Services@3.10.7
#addin nuget:?package=CG.Infrastructure.Services&version=3.10.7Install as a Cake Addin
#tool nuget:?package=CG.Infrastructure.Services&version=3.10.7Install as a Cake Tool
A comprehensive .NET library providing a collection of utility services for common application tasks including serialization, string manipulation, console operations, and more.
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.
dotnet add package CG.Infrastructure.Services
using Infrastructure.Services.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add infrastructure services
builder.Services.AddInfrastructureServices();
var app = builder.Build();
app.Run();
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...
}
}
Handles JSON serialization and deserialization with comprehensive error handling and null safety.
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);
}
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();
}
Provides advanced string manipulation capabilities including splitting, trimming, and pattern matching.
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);
}
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");
Creates formatted console tables for data display and reporting.
public interface IConsoleService
{
// Create formatted console table
void CreateConsoleTable<TEntity>(List<TEntity> data, string alignment, bool alternative);
}
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);
Handles document processing and file operations.
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);
}
Provides secure string handling for sensitive data.
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);
}
Handles integer operations and conversions.
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);
}
Provides comparison utilities for various data types.
public interface ICompareService
{
// Compare two objects
int Compare(object obj1, object obj2);
}
Handles output formatting and display.
public interface IOutputService
{
// Format output with options
string FormatOutput(object data, string format);
}
// Convert any object to JSON
var json = user.ToJson();
// Compare objects by JSON representation
bool areEqual = user1.CompareJson(user2);
// Safe integer conversion
int? number = "123".ToInt();
// Range validation
bool isValid = 50.IsBetween(0, 100);
// String manipulation
var result = "Hello World".RemoveTextBefore("World");
// Pattern counting
var count = "hello world".CountOccurrences("o");
// Date utilities
var isWeekend = DateTime.Now.IsWeekend();
var isBusinessDay = DateTime.Now.IsBusinessDay();
// Enum utilities
var description = MyEnum.Value1.GetDescription();
var values = EnumExtensions.GetValues<MyEnum>();
// Register all services
builder.Services.AddInfrastructureServices();
// Register specific services
builder.Services.AddScoped<ISerializationService, SerializationService>();
builder.Services.AddScoped<ISubstringService, SubstringService>();
builder.Services.AddScoped<IConsoleService, ConsoleService>();
public class MyService
{
private readonly ISerializationService _serializationService;
private readonly ISubstringService _substringService;
public MyService(ISerializationService serializationService, ISubstringService substringService)
{
_serializationService = serializationService;
_substringService = substringService;
}
}
[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 });
}
}
}
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);
}
}
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);
}
}
}
This library uses Newtonsoft.Json for comprehensive JSON handling with dynamic object support.
DeserialiseUnknownObject() returns dynamic? for runtime property accessGetObjectFromFile() returns JToken for programmatic JSON manipulationGetObjectFromFileAsDynamic() returns dynamic? for easy property access// 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...
}
}
}
// 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:
When to Use Each Approach:
Use GetObjectFromFile (JToken) when you need:
Use GetObjectFromFileAsDynamic when you need:
Use DeserialiseUnknownObject when you need:
## 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.6**: Current release with comprehensive service collection
- Supports .NET 10.0
- CG.Infrastructure.Core 3.10.8
- **3.10.2**: Previous 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 | net10.0 net10.0 is compatible. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
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 |
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.10.7 | 190 | 4/1/2026 |
| 3.10.6 | 410 | 8/15/2025 |
| 3.10.5 | 207 | 8/15/2025 |
| 3.10.4 | 289 | 8/13/2025 |
| 3.10.3 | 249 | 8/13/2025 |
| 3.10.2 | 287 | 8/10/2025 |
| 3.10.1 | 336 | 6/18/2025 |
| 3.10.0 | 361 | 6/4/2025 |
| 3.9.1 | 338 | 2/18/2025 |
| 3.9.0 | 260 | 12/10/2024 |
| 3.0.2 | 278 | 8/18/2024 |
| 3.0.1 | 365 | 7/12/2024 |
| 3.0.0 | 275 | 3/26/2024 |
| 2.0.0 | 854 | 5/16/2023 |
| 1.0.7 | 677 | 6/22/2022 |
| 1.0.6 | 564 | 6/22/2022 |
| 1.0.5 | 578 | 6/22/2022 |
| 1.0.4 | 1,995 | 6/20/2022 |
| 1.0.3 | 954 | 5/27/2022 |
| 1.0.2 | 733 | 5/27/2022 |