Skip to content

Advanced Usage

LoSkroefie edited this page Jan 19, 2025 · 1 revision

Advanced Usage

Custom Type Extensions

Creating Custom Types

public class GeoPoint : IFlexonType
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }

    public byte TypeCode => 0x0B;

    public void Serialize(FlexonWriter writer)
    {
        writer.WriteDouble(Latitude);
        writer.WriteDouble(Longitude);
    }

    public void Deserialize(FlexonReader reader)
    {
        Latitude = reader.ReadDouble();
        Longitude = reader.ReadDouble();
    }
}

// Register custom type
FlexonConfiguration.RegisterType<GeoPoint>();

Using Custom Types

var location = new GeoPoint 
{
    Latitude = 37.7749,
    Longitude = -122.4194
};

// Encode
byte[] data = FlexonEncoder.Encode(location);

// Decode
var decoded = FlexonDecoder.Decode<GeoPoint>(data);

Streaming Operations

Large File Processing

using var stream = File.OpenRead("large.flexon");
using var reader = new FlexonStreamReader(stream);

while (reader.HasMore)
{
    var chunk = reader.ReadNext();
    ProcessChunk(chunk);
}

Batch Processing

using var writer = new FlexonBatchWriter("output.flexon");

foreach (var item in largeDataset)
{
    writer.Write(item);
    if (writer.BatchSize >= 1000)
    {
        await writer.FlushAsync();
    }
}

await writer.CompleteAsync();

Advanced Schema Features

Conditional Validation

{
  "type": "object",
  "properties": {
    "type": {
      "type": "string",
      "enum": ["user", "admin"]
    },
    "permissions": {
      "type": "object",
      "if": {
        "properties": { "type": { "const": "admin" } }
      },
      "then": {
        "required": ["superuser"]
      }
    }
  }
}

Custom Formats

public class EmailFormatValidator : IFormatValidator
{
    public string Format => "email";

    public bool Validate(string value)
    {
        return Regex.IsMatch(value, 
            @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
    }
}

FlexonSchema.RegisterFormat(new EmailFormatValidator());

Performance Tuning

Memory Optimization

var options = new FlexonOptions
{
    BufferSize = 8192,
    PooledBuffers = true,
    MaxStringLength = 1024 * 1024,
    MaxDepth = 64
};

using var encoder = new FlexonEncoder(options);

Parallel Processing

var options = new FlexonOptions
{
    EnableParallel = true,
    MaxDegreeOfParallelism = Environment.ProcessorCount,
    BatchSize = 1000
};

await FlexonProcessor.ProcessParallel(items, options);

Security Features

Encryption

var options = new FlexonSecurityOptions
{
    EnableEncryption = true,
    EncryptionKey = GetSecureKey(),
    SigningKey = GetSigningKey()
};

// Encode with encryption
var encoded = FlexonEncoder.EncodeSecure(data, options);

// Decode with verification
var decoded = FlexonDecoder.DecodeSecure(encoded, options);

Data Validation

var options = new FlexonValidationOptions
{
    MaxSize = 10 * 1024 * 1024, // 10MB
    AllowedTypes = new[] { typeof(User), typeof(Order) },
    DisallowedProperties = new[] { "password", "secret" }
};

var validator = new FlexonValidator(options);
var isValid = validator.Validate(data);

Integration Examples

Web API Integration

[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Post(
        [FromBody] FlexonData data)
    {
        using var stream = new MemoryStream();
        await FlexonEncoder.EncodeAsync(data, stream);
        
        // Process or store the data
        await ProcessData(stream.ToArray());
        
        return Ok();
    }
}

Database Integration

public class FlexonRepository<T> where T : class
{
    private readonly DbContext _context;

    public async Task Store(T entity)
    {
        var flexonData = await FlexonEncoder
            .EncodeAsync(entity);
            
        _context.FlexonDocuments.Add(new FlexonDocument
        {
            Id = Guid.NewGuid(),
            Type = typeof(T).Name,
            Data = flexonData
        });
        
        await _context.SaveChangesAsync();
    }
}

Monitoring and Diagnostics

Performance Metrics

public class FlexonMetrics
{
    public static readonly Counter EncodingOperations = 
        Metrics.CreateCounter("flexon_encoding_total");
        
    public static readonly Histogram EncodingDuration =
        Metrics.CreateHistogram("flexon_encoding_duration");
        
    public static readonly Gauge ActiveConnections =
        Metrics.CreateGauge("flexon_active_connections");
}

Logging

public class FlexonLogger
{
    private readonly ILogger _logger;

    public void LogOperation(
        string operation, 
        long duration, 
        long size)
    {
        _logger.LogInformation(
            "Operation: {Op}, Duration: {Duration}ms, Size: {Size}bytes",
            operation, duration, size);
    }
}

Testing Utilities

Unit Testing

public class FlexonTests
{
    [Fact]
    public void TestCustomType()
    {
        var original = new GeoPoint
        {
            Latitude = 37.7749,
            Longitude = -122.4194
        };

        var encoded = FlexonEncoder.Encode(original);
        var decoded = FlexonDecoder.Decode<GeoPoint>(encoded);

        Assert.Equal(original.Latitude, decoded.Latitude);
        Assert.Equal(original.Longitude, decoded.Longitude);
    }
}

Performance Testing

public class FlexonBenchmarks
{
    [Benchmark]
    public void EncodeLargeDataset()
    {
        var data = GenerateLargeDataset();
        using var stream = new MemoryStream();
        FlexonEncoder.Encode(data, stream);
    }
}

Clone this wiki locally