fasadin
fasadin
CC#
Created by fasadin on 5/13/2024 in #help
MassTransit unit test does not hit breakpoint in consumer
I have problem with writing an unit test that will check my consumer. It's not hitting breakpoint in my Consumer when I am debugging test code for test
[Theory]
[AutoData]
public async Task GivenUserCreatedEventIsSend_WhenProperlyEventIsHandled_ThenUserIsCreated(Guid userId)
{
await using var provider = new ServiceCollection()
.AddDbContext<ChatContext>(options => options.UseInMemoryDatabase("TestChatDatabase"))
.AddMassTransitTestHarness(cfg =>
{
cfg.AddConsumer<UserCreatedMessageHandler>();
})
.BuildServiceProvider(true);

using (var scope = provider.CreateScope())
{
var chatContext = scope.ServiceProvider.GetRequiredService<ChatContext>();

var harness = scope.ServiceProvider.GetRequiredService<ITestHarness>();
await harness.Start();

try
{
await harness.Bus.Publish<UserCreated>(new
{
Id = userId
});

Assert.True(await harness.Consumed.Any<UserCreated>());


await using (chatContext)
{
// Verify changes in the database
var entity = await chatContext.Users.FirstOrDefaultAsync( /* Add conditions to find the entity */);
entity.Should().NotBeNull();
// Add additional assertions to verify the state of the entity in the database
}
}
finally
{
await harness.Stop();
}
}
}
[Theory]
[AutoData]
public async Task GivenUserCreatedEventIsSend_WhenProperlyEventIsHandled_ThenUserIsCreated(Guid userId)
{
await using var provider = new ServiceCollection()
.AddDbContext<ChatContext>(options => options.UseInMemoryDatabase("TestChatDatabase"))
.AddMassTransitTestHarness(cfg =>
{
cfg.AddConsumer<UserCreatedMessageHandler>();
})
.BuildServiceProvider(true);

using (var scope = provider.CreateScope())
{
var chatContext = scope.ServiceProvider.GetRequiredService<ChatContext>();

var harness = scope.ServiceProvider.GetRequiredService<ITestHarness>();
await harness.Start();

try
{
await harness.Bus.Publish<UserCreated>(new
{
Id = userId
});

Assert.True(await harness.Consumed.Any<UserCreated>());


await using (chatContext)
{
// Verify changes in the database
var entity = await chatContext.Users.FirstOrDefaultAsync( /* Add conditions to find the entity */);
entity.Should().NotBeNull();
// Add additional assertions to verify the state of the entity in the database
}
}
finally
{
await harness.Stop();
}
}
}
what's confusing it's that assertions passes fine, but my class UserCreatedMessageHandler it's never called / hit by breakpoint (ctor nor Consume method)
2 replies
CC#
Created by fasadin on 2/10/2024 in #help
config from test it's not used
I am running intergration test. I've implemented it by using WebApplicationFactory here it's how I am getting client
public static HttpClient CreateClient()
{
var projectDir = Directory.GetCurrentDirectory();
var configPath = Path.Combine(projectDir, "appsettings.test.json");
var factory = new WebApplicationFactory<Program>();
factory = factory.WithWebHostBuilder(
builder =>
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "test");
builder.ConfigureAppConfiguration((_, conf) => { conf.AddJsonFile(configPath); });
builder.UseEnvironment("test");
}
);
var client = factory.CreateClient();
return client;
}
public static HttpClient CreateClient()
{
var projectDir = Directory.GetCurrentDirectory();
var configPath = Path.Combine(projectDir, "appsettings.test.json");
var factory = new WebApplicationFactory<Program>();
factory = factory.WithWebHostBuilder(
builder =>
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "test");
builder.ConfigureAppConfiguration((_, conf) => { conf.AddJsonFile(configPath); });
builder.UseEnvironment("test");
}
);
var client = factory.CreateClient();
return client;
}
in Program.cs when I will check what's inside configuration builder. I can see that appsettings.test.json it's one of it's sources. Yet, it is using appsettings.json from application and not from test. Here is code How I retrieve settings

var configurationBuilder = builder
.Configuration
.AddJsonFile($"appsettings.{environment}.json", true, true)
.AddJsonFile("appsettings.json", false, true)
.AddEnvironmentVariables();

var configuration = configurationBuilder.Build();
var settings = configuration.GetSection("Settings").Get<Settings>();

var configurationBuilder = builder
.Configuration
.AddJsonFile($"appsettings.{environment}.json", true, true)
.AddJsonFile("appsettings.json", false, true)
.AddEnvironmentVariables();

var configuration = configurationBuilder.Build();
var settings = configuration.GetSection("Settings").Get<Settings>();
file it's copied and it's in debug folder. Environment it's set to test. I realize, webapplication factory has "double" instructions (setting environment, or adding json file to builder which is not needed). It's just current state of code after many attempts of fixing it
1 replies
CC#
Created by fasadin on 1/1/2024 in #help
Chaining async methods. Method not found
I want to have something like this
var foo = await new UserBuilder(_client)
.CreateUser()
.VerifyUser()
.Build();
var foo = await new UserBuilder(_client)
.CreateUser()
.VerifyUser()
.Build();
but this gives me an error Cannot resolve symbol 'VerifyUser' it's because CreateUser returns Task<T> if I write like this
var foo = await new UserBuilder(_client)
.CreateUser();
foo = await asd.VerifyUser();
var bar = await asd.Build();
var foo = await new UserBuilder(_client)
.CreateUser();
foo = await asd.VerifyUser();
var bar = await asd.Build();
or like this
var asd = await (await (await new UserBuilder(_grupieClient)
.CreateUser())
.VerifyUser())
.Build();
var asd = await (await (await new UserBuilder(_grupieClient)
.CreateUser())
.VerifyUser())
.Build();
then it works as expected but second and third solution it's ugly. How to achieve desired syntax?
34 replies
CC#
Created by fasadin on 12/28/2023 in #help
active reports trial has expired
I am working on active reports v8 I split repositories to smaller ones and after that split I am getting error with trial has expired. License.licx it’s there. key in webconfig it’s there dll gendered for license it’s there bin folder looks the same as before splitting (if it comes to active reports) yet it does not work I tried regenerating license, but that didn’t solved the problem What else I could do?
1 replies
CC#
Created by fasadin on 12/2/2023 in #help
Clean architecture, how to register dbcontext
So in Presentation layer that's where API (controller) will be. Also that's an entry point for application. As this is entry of application, it has to do registrations of all services How to register Infrastructure layer? It has implementation of interfaces and dbcontext Somehow I have feeling that Presentation should know nothing about Infrastructure layer yet there are implementation of interfaces that are inside of Application
27 replies
CC#
Created by fasadin on 11/30/2023 in #help
✅ trying to debug but app is crashing
it cannot go even to program.cs. It just crashes.
2 replies
CC#
Created by fasadin on 11/9/2023 in #help
CS00012 The type is defined in an assembly that is not referenced. But that assembly it is reference
Otherwise if I remove that reference I am getting more than 100 errors, the moment I add that reference. Then I see this error that its on topic and this is the only error. I can see that type in referenced project projects are on 4.8 Framework
37 replies
CC#
Created by fasadin on 11/9/2023 in #help
Storing binary files in GIT
I know there is LFS for git and I know in general you should not store any binary files. But I have big and complex project (for one repo there are more than 7k files, and those are with .gitignore) There are a lot of files like *.pdf or *.xls but a lot of tests depends on those tests I thought initialy to make submodule for all those files and store them in LFS, but those files won't ever change. There is no need for versioning on them My question is. What is the best way to store binary files that are not changing in repository but are needed for build/run/test process?
12 replies
CC#
Created by fasadin on 10/16/2023 in #help
❔ Running aspnet_compiler.exe gives an error
so when I am trying to build one of projects I am getting “could not load file or assembly microsoft.build.framework version 4.0.0.0” but I don’t have that package anywhere listed. My nuget it’s version 6.4.0 and on another machine this command works what I can do next?
117 replies
CC#
Created by fasadin on 8/18/2023 in #help
❔ could not load file or assembly
Hey, I have complex project. I’ve upgraded it to higher version of .net framework. With it I installed newer version of packages Now some tests are failing because they cannot find System.runtime.compiler.unsafe package if I ran the same code isolated with completely new project then same line of code works without any problems. any idea how to proceed with this?
4 replies
CC#
Created by fasadin on 4/23/2023 in #help
✅ Decorate class (controller) with item from httpcontext
In httpContextAccessor.HttpContext?.Items["User"] I am storing Id of user that performs calls. The way I am retrieving it
public GroupController(IHttpContextAccessor httpContextAccessor)
{
_profileId = (Guid)(httpContextAccessor.HttpContext?.Items["User"] ?? throw new ArgumentException("Invalid token"));
}
public GroupController(IHttpContextAccessor httpContextAccessor)
{
_profileId = (Guid)(httpContextAccessor.HttpContext?.Items["User"] ?? throw new ArgumentException("Invalid token"));
}
I have two questions. 1) I don't want to in constructor always build profileId I would prefer that it would be injected into constructor itself or injected into method. How to achieve this? For example something like this
[Authorize]
[HttpGet("groups")]
public async Task<IActionResult> GetGroupsByProfile(Guid profileId, CancellationToken cancellationToken)
[Authorize]
[HttpGet("groups")]
public async Task<IActionResult> GetGroupsByProfile(Guid profileId, CancellationToken cancellationToken)
2) Is there a better approach of finding out what user (id) it's performing request? The way I set this information is following: I have Middleware that performs call to another service
var response = await _httpClient.PostAsync($"authentication/authenticate?token={token}", new StringContent(""));
var response = await _httpClient.PostAsync($"authentication/authenticate?token={token}", new StringContent(""));
later I deserialize response
var userPayload = JsonSerializer.Deserialize<UserResponse>(responseContent, options)
var userPayload = JsonSerializer.Deserialize<UserResponse>(responseContent, options)
and for final part I am adding UserId to httpContext
context.Items["User"] = userPayload.Id;
context.Items["User"] = userPayload.Id;
28 replies
CC#
Created by fasadin on 2/5/2023 in #help
✅ Exception is caught, but not?
I have this piece of code
try
{
await _dbContext.RunningTotals.AddAsync(new RunningTotal
{
Value = runningTotalDto.Value
});

await _dbContext.SaveChangesAsync();

return new Result<OptionNone>(OptionNone.Default);
}
catch (Exception e)
{
return new Result<OptionNone>(e);
}
try
{
await _dbContext.RunningTotals.AddAsync(new RunningTotal
{
Value = runningTotalDto.Value
});

await _dbContext.SaveChangesAsync();

return new Result<OptionNone>(OptionNone.Default);
}
catch (Exception e)
{
return new Result<OptionNone>(e);
}
on await _dbContext.SaveChangesAsync(); I am getting exception. Breakpoint hits catch (Exception e) it goes into return new Result<OptionNone>(e); and then it just skips execution... it shows on IDE that exception is still present I don't understand nothing from it 😦
52 replies