SWEETPONY
SWEETPONY
CC#
Created by SWEETPONY on 11/10/2024 in #help
✅ I don't undertand the error: capacity was less than the current size
Hey I have two versions of code and second one doesn't work first version:
int[] array = Enumerable.Range(0, 1000000000).ToArray();
var lst = new List<double>();

var stopWatch = new Stopwatch();
stopWatch.Start();

for (int i = 0; i < array.Length; i++)
{
var result = Math.Pow(i, 100000000000);
lst.Add(result);
}

stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
int[] array = Enumerable.Range(0, 1000000000).ToArray();
var lst = new List<double>();

var stopWatch = new Stopwatch();
stopWatch.Start();

for (int i = 0; i < array.Length; i++)
{
var result = Math.Pow(i, 100000000000);
lst.Add(result);
}

stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
second version:
int[] array = Enumerable.Range(0, 1000000000).ToArray();
var lst = new List<double>();

var stopWatch = new Stopwatch();
stopWatch.Start();

Parallel.For(0, array.Length, i =>
{
var result = Math.Pow(i, 100000000000);
lst.Add(result);
});

stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
int[] array = Enumerable.Range(0, 1000000000).ToArray();
var lst = new List<double>();

var stopWatch = new Stopwatch();
stopWatch.Start();

Parallel.For(0, array.Length, i =>
{
var result = Math.Pow(i, 100000000000);
lst.Add(result);
});

stopWatch.Stop();
Console.WriteLine(stopWatch.Elapsed);
second version always throws the exception: Unhandled exception. System.AggregateException: One or more errors occurred. (capacity was less than the current size. (Parameter 'value')) (capacity was less than the current size. (Parameter 'value')) (capacity was less than the current size. (Parameter 'value')) (capacity was less than the current size.
17 replies
CC#
Created by SWEETPONY on 11/6/2024 in #help
✅ How to write unit test for this?
I have controller with this method:
[HttpGet("stream")]
public async Task StreamAsync(CancellationToken cancellationToken)
{
Response.Headers.Append("Content-Type", "text/event-stream");

while(!cancellationToken.IsCancellationRequested)
{
var sseEvent = new SseEvent<object>
{
Action = SseAction.Heartbeat,
Timestamp = timeProvider.GetUtcNow().DateTime
};

var serializedSseEvent = Serialization.Serialize(sseEvent);

await Response.WriteAsync($"{serializedSseEvent}", cancellationToken).ConfigureAwait(false);
await Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);

await Task.Delay(sseSettings.Timeout, cancellationToken).ConfigureAwait(false);
}
}
[HttpGet("stream")]
public async Task StreamAsync(CancellationToken cancellationToken)
{
Response.Headers.Append("Content-Type", "text/event-stream");

while(!cancellationToken.IsCancellationRequested)
{
var sseEvent = new SseEvent<object>
{
Action = SseAction.Heartbeat,
Timestamp = timeProvider.GetUtcNow().DateTime
};

var serializedSseEvent = Serialization.Serialize(sseEvent);

await Response.WriteAsync($"{serializedSseEvent}", cancellationToken).ConfigureAwait(false);
await Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);

await Task.Delay(sseSettings.Timeout, cancellationToken).ConfigureAwait(false);
}
}
unit test:
[Test]
public async Task StreamAsync_ShouldWriteHeartbeatEvents()
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

await controller.StreamAsync(cts.Token).ConfigureAwait(false);
}
[Test]
public async Task StreamAsync_ShouldWriteHeartbeatEvents()
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));

await controller.StreamAsync(cts.Token).ConfigureAwait(false);
}
I want to check that Response contains sseEvents but always get an exception: System.Threading.Tasks.TaskCanceledException : A task was canceled. how to fix it?
3 replies
CC#
Created by SWEETPONY on 11/6/2024 in #help
✅ Is it worth to use stackalloc here?
Hey, I have this:
[HttpGet("stream")]
public async Task StreamHeartbeatAsync(CancellationToken cancellationToken)
{
Response.Headers.Append("Content-Type", "text/event-stream");
Response.Headers.Append("Cache-Control", "no-cache");
Response.Headers.Append("Connection", "keep-alive");

while(!cancellationToken.IsCancellationRequested)
{
var sseEvent = new SseEvent<object>
{
Action = SseAction.Heartbeat,
Timestamp = DateTime.UtcNow
};

await Response.WriteAsJsonAsync(sseEvent, cancellationToken);
await Response.Body.FlushAsync(cancellationToken);

await Task.Delay(sseSettings.Timeout, cancellationToken);
}
}

public sealed class SseEvent<T>
{
public required DateTime Timestamp { get; set; }
public required SseAction Action { get; set; }
public string? Store { get; set; }
public string? Identity { get; set; }
public T? Data { get; set; }
}
[HttpGet("stream")]
public async Task StreamHeartbeatAsync(CancellationToken cancellationToken)
{
Response.Headers.Append("Content-Type", "text/event-stream");
Response.Headers.Append("Cache-Control", "no-cache");
Response.Headers.Append("Connection", "keep-alive");

while(!cancellationToken.IsCancellationRequested)
{
var sseEvent = new SseEvent<object>
{
Action = SseAction.Heartbeat,
Timestamp = DateTime.UtcNow
};

await Response.WriteAsJsonAsync(sseEvent, cancellationToken);
await Response.Body.FlushAsync(cancellationToken);

await Task.Delay(sseSettings.Timeout, cancellationToken);
}
}

public sealed class SseEvent<T>
{
public required DateTime Timestamp { get; set; }
public required SseAction Action { get; set; }
public string? Store { get; set; }
public string? Identity { get; set; }
public T? Data { get; set; }
}
I think it is not good to create sseEvent every second without any memory clean. Is it worth to use stackalloc here?
41 replies
CC#
Created by SWEETPONY on 10/25/2024 in #help
✅ How to save to database with ISO format?
No description
6 replies
CC#
Created by SWEETPONY on 10/23/2024 in #help
✅ How to optimize this code?
Hello, I'd like to optimize my code. The best time I got: 00:00:00.536 with chunks count = 256 536ms actually is not too bad but is it possible to speed up method?
private async Task<IEnumerable<JsonNode?>?> GetDmnTasksAsync(IReadOnlyList<PassengerArrivalChunk> chunks)
{
var tasks = chunks.Select(async chunk =>
{
var serializedChunk = Serializer.Serialize(new { passengerArrivalChunk = chunk });

using var response = await httpClient
.PostAsync(processingSettings.DmnUrl, new StringContent(serializedChunk, Encoding.UTF32, MediaTypeNames.Application.Json));

var responseMessage = await response.Content.ReadAsStringAsync();
var jsonArray = JsonNode.Parse(responseMessage)?["Tasks"]?.AsArray();

return jsonArray?.Select(el => el).Where(x => x != null);
}).ToList();

var results = await Task.WhenAll(tasks);
return results.SelectMany(result => result ?? []);
}
private async Task<IEnumerable<JsonNode?>?> GetDmnTasksAsync(IReadOnlyList<PassengerArrivalChunk> chunks)
{
var tasks = chunks.Select(async chunk =>
{
var serializedChunk = Serializer.Serialize(new { passengerArrivalChunk = chunk });

using var response = await httpClient
.PostAsync(processingSettings.DmnUrl, new StringContent(serializedChunk, Encoding.UTF32, MediaTypeNames.Application.Json));

var responseMessage = await response.Content.ReadAsStringAsync();
var jsonArray = JsonNode.Parse(responseMessage)?["Tasks"]?.AsArray();

return jsonArray?.Select(el => el).Where(x => x != null);
}).ToList();

var results = await Task.WhenAll(tasks);
return results.SelectMany(result => result ?? []);
}
19 replies
CC#
Created by SWEETPONY on 10/6/2024 in #help
✅ How to speed up execution of BigInteger.Pow?
I have this: var result = BigInteger.Pow(1000, 10000000); I know this is a big number but generation of this number takes too much time. Is it possible to speed up?
13 replies
CC#
Created by SWEETPONY on 9/11/2024 in #help
Error: The value of shadow key property 'ResourceDemandChunks.Id' is unknown when attempting to save
Hey everyone! I'm stuck with this problem: The value of shadow key property 'ResourceDemandChunks.Id' is unknown when attempting to save changes. This is because shadow property values cannot be preserved when the entity is not being tracked. Consider adding the property to the entity's .NET type this is how I register entity in db context:
modelBuilder.Entity<WorkingTaskEntity>().OwnsOne(c => c.CustomData, t =>
{
t.ToJson();
t.OwnsMany(customData => customData.ResourceDemandChunks);
});
modelBuilder.Entity<WorkingTaskEntity>().OwnsOne(c => c.CustomData, t =>
{
t.ToJson();
t.OwnsMany(customData => customData.ResourceDemandChunks);
});
CustomData is jsonb property, in DDL it is jsonb, I absolutely no idea what happening..
public WorkingTaskData? CustomData { get; init; }
public record WorkingTaskData
{
public List<ResourceDemandChunks> ResourceDemandChunks { get; set; }
public WorkingTaskData? CustomData { get; init; }
public record WorkingTaskData
{
public List<ResourceDemandChunks> ResourceDemandChunks { get; set; }
3 replies
CC#
Created by SWEETPONY on 7/28/2024 in #help
✅ How to correctly write conditions with expressions?
I have this code:
public static class BookPolicy
{
public static void AllowRead(Book book)
{
var isHorrorBook = Specifications.IsHorrorBook().Compile();
var isPonyBook = Specifications.IsPonyBook().Compile();

if (isHorrorBook(book) || isPonyBook(book))
throw new Exception("Horror or pony books don't allow here");
}
}

public static class Specifications
{
public static Expression<Func<Book, bool>> IsHorrorBook() =>
book => book.Title.Contains("Frankenstein");

public static Expression<Func<Book, bool>> IsPonyBook() =>
book => book.Title.Contains("Pony");
}
public static class BookPolicy
{
public static void AllowRead(Book book)
{
var isHorrorBook = Specifications.IsHorrorBook().Compile();
var isPonyBook = Specifications.IsPonyBook().Compile();

if (isHorrorBook(book) || isPonyBook(book))
throw new Exception("Horror or pony books don't allow here");
}
}

public static class Specifications
{
public static Expression<Func<Book, bool>> IsHorrorBook() =>
book => book.Title.Contains("Frankenstein");

public static Expression<Func<Book, bool>> IsPonyBook() =>
book => book.Title.Contains("Pony");
}
everything is ok but i would like to know is it possible to write smth like this? if(book is Horror or Pony) {...} I don't understand how to do this with expressions
10 replies
CC#
Created by SWEETPONY on 7/18/2024 in #help
✅ A problem with tracking behavior in unit tests
I have this error in unit tests:
The instance of entity type 'QualificationEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
The instance of entity type 'QualificationEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Unit tests look like this:
[Test]
public Task AddAsync_AddWorkingTask_Success() =>
ExecuteTestCaseWithTestingContextAsync(async context => {
context.DbContext.Qualifications.Add(qualification);
context.DbContext.SaveChanges();

...

await context.WorkingTaskRepository.ScheduleWorkingTaskAsync(workingTask, eventContext);
});
[Test]
public Task AddAsync_AddWorkingTask_Success() =>
ExecuteTestCaseWithTestingContextAsync(async context => {
context.DbContext.Qualifications.Add(qualification);
context.DbContext.SaveChanges();

...

await context.WorkingTaskRepository.ScheduleWorkingTaskAsync(workingTask, eventContext);
});
protected async Task ExecuteTestCaseWithTestingContextAsync(Func<TestingContext, Task> asserter)
{
if(asserter == null)
Assert.Fail();
var options = CreateDbOptions();
using(var dbContext = new DbContext(options))
{
await dbContext.Database.EnsureDeletedAsync().ConfigureAwait(false);
await dbContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
var testingContext = new TestingContext(dbContext);
await asserter.Invoke(testingContext).ConfigureAwait(false);
}
}
protected async Task ExecuteTestCaseWithTestingContextAsync(Func<TestingContext, Task> asserter)
{
if(asserter == null)
Assert.Fail();
var options = CreateDbOptions();
using(var dbContext = new DbContext(options))
{
await dbContext.Database.EnsureDeletedAsync().ConfigureAwait(false);
await dbContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
var testingContext = new TestingContext(dbContext);
await asserter.Invoke(testingContext).ConfigureAwait(false);
}
}
everything will be ok if I remove context.DbContext.Qualifications.Add(qualification); but I don't want to
1 replies
CC#
Created by SWEETPONY on 7/16/2024 in #help
✅ is there any way to delete items from the database and return the deleted list in one request?
is there any way to delete items from the database and return the deleted list in one request? I can do something like this: DbContext.T.Where(entity => ..).ExecuteDelete(), but my business logic assumes that I will return items that were deleted I can do this: var deleted = DbContext.T.Where(entity => ..) DbContext.RemoveRange(deleted) but these are already two requests to database
14 replies
CC#
Created by SWEETPONY on 7/2/2024 in #help
✅ How to optimize this method?
I have this method:
protected override async Task UpdateCoreAsync(WorkingTaskModel workingTask, EventHandlingContext context)
{
var exist = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
if(exist == null)
return;
if(await UpdateInternalAsync(workingTask, exist, context).ConfigureAwait(false))
{
var stateIsChanged = exist.State != workingTask.State;
if(stateIsChanged)
{
var historyModel = new WorkingTaskHistoryModel
{
ChangedData = new ChangedWorkingTaskModel(){State = workingTask.State},
UserIdentity = context.Context.UserAccountIdentity,
SourceName = context.Context.SourceName,
UpdatedAt = timeProvider.GetUtcNow().DateTime
};

await UpdateWorkingTaskHistoryAsync(historyModel, exist, context).ConfigureAwait(false);
}

var found = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
await eventDispatcher.WorkingTaskUpdatedAsync(found!, exist, context).ConfigureAwait(false);
}
}
protected override async Task UpdateCoreAsync(WorkingTaskModel workingTask, EventHandlingContext context)
{
var exist = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
if(exist == null)
return;
if(await UpdateInternalAsync(workingTask, exist, context).ConfigureAwait(false))
{
var stateIsChanged = exist.State != workingTask.State;
if(stateIsChanged)
{
var historyModel = new WorkingTaskHistoryModel
{
ChangedData = new ChangedWorkingTaskModel(){State = workingTask.State},
UserIdentity = context.Context.UserAccountIdentity,
SourceName = context.Context.SourceName,
UpdatedAt = timeProvider.GetUtcNow().DateTime
};

await UpdateWorkingTaskHistoryAsync(historyModel, exist, context).ConfigureAwait(false);
}

var found = await FindByIdentityAsync(workingTask.Identity, context).ConfigureAwait(false);
await eventDispatcher.WorkingTaskUpdatedAsync(found!, exist, context).ConfigureAwait(false);
}
}
the problem is: I need to call FindByIdentityAsync twice and we need this just to check updated property and send event. is it possible to remove second FindByIdentityAsync?
4 replies
CC#
Created by SWEETPONY on 6/21/2024 in #help
Is it possible to update public IReadOnlyList?
There is public IReadOnlyList<ISelectionNode> Selections { get; } from public api I know it is not a good idea but I want to extend it. Is it possible?
12 replies
CC#
Created by SWEETPONY on 6/19/2024 in #help
✅ how to convert Dictionary to C# object?
I have Dictionary<string, object> map string is property name and object is property value is it possible to deserialize this to real object?
2 replies
CC#
Created by SWEETPONY on 5/28/2024 in #help
The instance of entity type 'OptimizerInstanceEntity' cannot be tracked
Can someone help me to update model?
public sealed record OptimizerSettingsSetsEntity : OptimizerSettingsSets, IIdentityEntity
{
public new string Identity { get => base.Identity; init => base.Identity = value; }
public List<OptimizerInstanceEntity> OptimizerInstances { get; init; } = [];
public DateTime Created { get; init; }
public Guid Id { get; init; }
public DateTime Timestamp { get; init; }
public DateTime? Updated { get; init; }
}

public sealed record OptimizerInstanceEntity : IdentityEntity
{
public required string Url { get; set; }
}
public sealed record OptimizerSettingsSetsEntity : OptimizerSettingsSets, IIdentityEntity
{
public new string Identity { get => base.Identity; init => base.Identity = value; }
public List<OptimizerInstanceEntity> OptimizerInstances { get; init; } = [];
public DateTime Created { get; init; }
public Guid Id { get; init; }
public DateTime Timestamp { get; init; }
public DateTime? Updated { get; init; }
}

public sealed record OptimizerInstanceEntity : IdentityEntity
{
public required string Url { get; set; }
}
I want to create entity, add it to database and then update only instances My command doesn't work, I got exception after trying to update:
protected override async Task UpdateCoreAsync(OptimizerSettingsSetsModel model, EventHandlingContext context)
{
var exists = await FindByIdentityAsync(model.Identity, context);
if(exists == null)
return;

if(!ChangesComparer.HasChanges(exists.ToModel(), model))
return;

var entity = CreateEntity(model, exists);
var entry = dbContext.OptimizerSettingsSets.Update(entity);
await dbContext.SaveChangesAsync(context.CancellationToken);
entry.State = EntityState.Detached;
await eventDispatcher.OptimizerSettingsSetsUpdatedAsync(entity, context);
}
protected override async Task UpdateCoreAsync(OptimizerSettingsSetsModel model, EventHandlingContext context)
{
var exists = await FindByIdentityAsync(model.Identity, context);
if(exists == null)
return;

if(!ChangesComparer.HasChanges(exists.ToModel(), model))
return;

var entity = CreateEntity(model, exists);
var entry = dbContext.OptimizerSettingsSets.Update(entity);
await dbContext.SaveChangesAsync(context.CancellationToken);
entry.State = EntityState.Detached;
await eventDispatcher.OptimizerSettingsSetsUpdatedAsync(entity, context);
}
6 replies
CC#
Created by SWEETPONY on 5/16/2024 in #help
✅ is it okay to use try/catch for logic behavior?
for example here, what is better and why
private string GetHost(string endpoint)
{
try
{
var myUri = new Uri(endpoint as string);
return myUri.Host;
}
catch
{
return endpoint;
}
}
private string GetHost(string endpoint)
{
try
{
var myUri = new Uri(endpoint as string);
return myUri.Host;
}
catch
{
return endpoint;
}
}
private string GetHost(string endpoint)
{
return Uri.TryCreate(endpoint, UriKind.Absolute, out var validUri)
? validUri.Host
: endpoint;
}
private string GetHost(string endpoint)
{
return Uri.TryCreate(endpoint, UriKind.Absolute, out var validUri)
? validUri.Host
: endpoint;
}
12 replies
CC#
Created by SWEETPONY on 5/6/2024 in #help
✅ How to get all data without Include?
maybe stupid question but I want to ask it: I have two methods:
[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskWithFlights?> SingleWorkingTaskWithFlightAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> HealthCheck(npgsqlHealthChecker, async () =>
{
var workingTask = await dbContext.WorkingTasks
.Include(workingTask => workingTask.RequiredQualifications)
.ThenInclude(workingTask => workingTask.Qualification)
.Include(workingTask => workingTask.StartLocation)
.Include(workingTask => workingTask.EndLocation)
.Include(workingTask => workingTask.WorkingShift)
.FirstOrDefaultAsync(workingTask => workingTask.Identity == identity, cancellationToken)
.ConfigureAwait(false);

if(workingTask == null)
return default;

var inboundIdentity = workingTask.CustomData?.InboundFlightLegIdentity;
var outboundIdentity = workingTask.CustomData?.OutboundFlightLegIdentity;

var flights = await dbContext.Flights
.Where(flight => flight.Identity == inboundIdentity || flight.Identity == outboundIdentity)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);

return new WorkingTaskWithFlights { WorkingTask = workingTask, Flights = flights.AsReadOnly()};
});

[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskEntity?> SingleWorkingTaskAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> GetByIdentityAsync(dbContext.WorkingTasks, identity, w => w.Project(context), npgsqlHealthChecker, cancellationToken);
[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskWithFlights?> SingleWorkingTaskWithFlightAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> HealthCheck(npgsqlHealthChecker, async () =>
{
var workingTask = await dbContext.WorkingTasks
.Include(workingTask => workingTask.RequiredQualifications)
.ThenInclude(workingTask => workingTask.Qualification)
.Include(workingTask => workingTask.StartLocation)
.Include(workingTask => workingTask.EndLocation)
.Include(workingTask => workingTask.WorkingShift)
.FirstOrDefaultAsync(workingTask => workingTask.Identity == identity, cancellationToken)
.ConfigureAwait(false);

if(workingTask == null)
return default;

var inboundIdentity = workingTask.CustomData?.InboundFlightLegIdentity;
var outboundIdentity = workingTask.CustomData?.OutboundFlightLegIdentity;

var flights = await dbContext.Flights
.Where(flight => flight.Identity == inboundIdentity || flight.Identity == outboundIdentity)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);

return new WorkingTaskWithFlights { WorkingTask = workingTask, Flights = flights.AsReadOnly()};
});

[UseProjection]
[Authorize(Roles = [Permissions.Rms.Task.Read])]
public Task<WorkingTaskEntity?> SingleWorkingTaskAsync([Service(ServiceKind.Resolver)] ReadModelDbContext dbContext, IResolverContext context, string identity, [Service] NpgsqlHealthChecker npgsqlHealthChecker, CancellationToken cancellationToken)
=> GetByIdentityAsync(dbContext.WorkingTasks, identity, w => w.Project(context), npgsqlHealthChecker, cancellationToken);
7 replies
CC#
Created by SWEETPONY on 5/3/2024 in #help
✅ How to fill the object without populating properties?
I have this record:
public sealed record WorkingTaskWithFlights: WorkingTask
{
public List<Flight>? Flights { get; init; }
}
public sealed record WorkingTaskWithFlights: WorkingTask
{
public List<Flight>? Flights { get; init; }
}
and in my code:
var workingTask = dbContext.WorkingTasks.FirstOrDefault(...);
var flights = dbContext.Flights.Select(...);
var workingTask = dbContext.WorkingTasks.FirstOrDefault(...);
var flights = dbContext.Flights.Select(...);
workingTask is WorkingTask record and flights is Flight record, I need now somehow create a WorkingTaskWithFlights but without populating properties of workingTask
1 replies
CC#
Created by SWEETPONY on 4/30/2024 in #help
✅ why dispose call is the latest in the chain?
Actually I have two questions here: 1. How actually duck typing works? Why I can do this:
using var refStruct = new RefStruct();
public ref struct RefStruct
{
public void Dispose()
{
Console.WriteLine("Hello from ref struct!");
}
}
using var refStruct = new RefStruct();
public ref struct RefStruct
{
public void Dispose()
{
Console.WriteLine("Hello from ref struct!");
}
}
but can't do the same with class, class requires to inherit IDisposable and it is strange:
using var simpleClass = new SimpleClass();
public class SimpleClass
{
public void Dispose()
{
Console.WriteLine("Hello from class!");
}
}
using var simpleClass = new SimpleClass();
public class SimpleClass
{
public void Dispose()
{
Console.WriteLine("Hello from class!");
}
}
2 question is: why dispose call is the latest in the chain? for example:
using var refStruct = new RefStruct();
using var simpleClass = new SimpleClass();
var factory = Factory.Create();
Console.WriteLine(factory);
using var refStruct = new RefStruct();
using var simpleClass = new SimpleClass();
var factory = Factory.Create();
Console.WriteLine(factory);
and output will be: Created Factory! Hello from class! Hello from ref struct!
11 replies
CC#
Created by SWEETPONY on 4/26/2024 in #help
✅ how to merge two objects?
Sometimes ago I had this object:
public sealed record CreateFlightLegModel
{
public string? Identity { get; init; }
public LegIdentityArgument? LegIdentity { get; init; }
public JsonDocument? LegData { get; set; }
}
public sealed record CreateFlightLegModel
{
public string? Identity { get; init; }
public LegIdentityArgument? LegIdentity { get; init; }
public JsonDocument? LegData { get; set; }
}
LegData used in method for merging and for example we can do this: var firstLeg =
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": ""2"",
""fuel_invoice_3"": ""3""
}
}");
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": ""2"",
""fuel_invoice_3"": ""3""
}
}");
var secondLeg=
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}");
JsonDocument.Parse(@"{
""fuel"":
{
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}");
and the output will be:
{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}
{
""fuel"":
{
""fuel_invoice_1"": ""1"",
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
}
then we decided move from JsonDocument to model and this merge doesn't work anymore in case I pasted earlier output will be:
""fuel"":
{
""fuel_invoice_1"": null,
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
""fuel"":
{
""fuel_invoice_1"": null,
""fuel_invoice_2"": null,
""fuel_invoice_3"": null
}
can someone understand me what to do?
9 replies
CC#
Created by SWEETPONY on 4/15/2024 in #help
how to add new property to json?
I have following code:
var schema = File.ReadAllText("legData.json");
var result = Parse(schema);

Console.WriteLine(result);

string Parse(string jsonSchema)
{
using var document = JsonDocument.Parse(jsonSchema);
var root = document.RootElement;

if(!root.TryGetProperty("properties", out _))
return "";

var properties = root.GetProperty("properties").EnumerateObject();
var property = properties.FirstOrDefault(prop => prop.Value.TryGetProperty("generateModelClassName", out _));
var propertyProperties = property.Value.GetProperty("properties");
var formatted = $$"""{"properties": {{propertyProperties}}}""";
return formatted;
}
var schema = File.ReadAllText("legData.json");
var result = Parse(schema);

Console.WriteLine(result);

string Parse(string jsonSchema)
{
using var document = JsonDocument.Parse(jsonSchema);
var root = document.RootElement;

if(!root.TryGetProperty("properties", out _))
return "";

var properties = root.GetProperty("properties").EnumerateObject();
var property = properties.FirstOrDefault(prop => prop.Value.TryGetProperty("generateModelClassName", out _));
var propertyProperties = property.Value.GetProperty("properties");
var formatted = $$"""{"properties": {{propertyProperties}}}""";
return formatted;
}
I need to add following property to each property in propertyProperties: "additionalProperties": true but I don't understand how to do it correctly
13 replies