Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed sonar issues #938

Merged
merged 3 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .sonarlint/Orso.Arpa.Api.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"sonarCloudOrganization": "orso-co",
"projectKey": "orso-co_Orso.Arpa.Api"
}
3 changes: 2 additions & 1 deletion Orso.Arpa.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using NLog.Web;
using Orso.Arpa.Api.Middleware;
using Orso.Arpa.Api.ModelBinding;
using Orso.Arpa.Domain._General.Errors;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

namespace Orso.Arpa.Api
Expand All @@ -28,7 +29,7 @@ public static void Main(string[] args)
catch (Exception exception)
{
logger.Error(exception, "Stopped program because of exception");
throw;
throw new SystemStartException("Stopped program because of exception", exception);
}
finally
{
Expand Down
7 changes: 4 additions & 3 deletions Orso.Arpa.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
using Orso.Arpa.Application.UserApplication.Services;
using Orso.Arpa.Application.VenueApplication.Interfaces;
using Orso.Arpa.Application.VenueApplication.Services;
using Orso.Arpa.Domain._General.Errors;
using Orso.Arpa.Domain.AuditLogDomain.Model;
using Orso.Arpa.Domain.General.Configuration;
using Orso.Arpa.Domain.General.Interfaces;
Expand Down Expand Up @@ -626,7 +627,7 @@ protected virtual void EnsureDatabaseMigrations(IApplicationBuilder app)
{
ILogger<Startup> logger = services.GetRequiredService<ILogger<Startup>>();
logger.LogError(ex, "An error occured during database migration");
throw;
throw new SystemStartException("An error occured during database migration", ex);
}
}

Expand All @@ -642,8 +643,8 @@ protected void PreloadTranslationsFromDb(IApplicationBuilder app)
catch (Exception ex)
{
ILogger<Startup> logger = services.GetRequiredService<ILogger<Startup>>();
logger.LogError(ex, "Error during localization of data");
throw;
logger.LogError(ex, "Error during preload of localization data from database");
throw new SystemStartException("Error during preload of localization data from database", ex);
}
}
}
Expand Down
22 changes: 10 additions & 12 deletions Orso.Arpa.Api/Swagger/SwaggerAuthorizeOperationFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,7 @@ private static void HandleRoleAttributes(OpenApiOperation operation, IEnumerable
operation.Responses.Add("403 a", new OpenApiResponse
{
Description = $"If current user does not have the role of '{string.Join(", ", roleAttributes)}'",
Content = new Dictionary<string, OpenApiMediaType>()
{
{ "application/json", new OpenApiMediaType() { Schema = new OpenApiSchema() { Type = "object", Properties = new Dictionary<string, OpenApiSchema>() {
{ "title", new OpenApiSchema() { Type = "string" } },
{ "description", new OpenApiSchema() {Type="string" } },
{ "status", new OpenApiSchema() { Type = "integer" } }
} } } }
}
Content = CreateContent()
});
}
}
Expand All @@ -55,16 +48,21 @@ private static void HandlePolicyAttributes(OpenApiOperation operation, IEnumerab
operation.Responses.Add("403 b", new OpenApiResponse
{
Description = $"If current user does not meet policy '{string.Join(", ", policyAttributes)}'",
Content = new Dictionary<string, OpenApiMediaType>()
Content = CreateContent()
});
}
}

private static Dictionary<string, OpenApiMediaType> CreateContent()
{
return new Dictionary<string, OpenApiMediaType>()
{
{ "application/json", new OpenApiMediaType() { Schema = new OpenApiSchema() { Type = "object", Properties = new Dictionary<string, OpenApiSchema>() {
{ "title", new OpenApiSchema() { Type = "string" } },
{ "description", new OpenApiSchema() {Type="string" } },
{ "status", new OpenApiSchema() { Type = "integer" } }
} } } }
}
});
}
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ public Handler(

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
Appointment existingAppointment = await _arpaContext.Appointments.FindAsync(new object[] { request.Id }, cancellationToken);
Project existingProject = await _arpaContext.Projects.FindAsync(new object[] { request.ProjectId }, cancellationToken);
Appointment existingAppointment = await _arpaContext.Appointments.FindAsync([request.Id], cancellationToken);
Project existingProject = await _arpaContext.Projects.FindAsync([request.ProjectId], cancellationToken);

_arpaContext.ProjectAppointments.Add(new ProjectAppointment(null, existingProject, existingAppointment));
await _arpaContext.ProjectAppointments.AddAsync(new ProjectAppointment(null, existingProject, existingAppointment), cancellationToken);

if (await _arpaContext.SaveChangesAsync(cancellationToken) > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ public Handler(

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
Appointment existingAppointment = await _arpaContext.Appointments.FindAsync(new object[] { request.Id }, cancellationToken);
Room existingRoom = await _arpaContext.Rooms.FindAsync(new object[] { request.RoomId }, cancellationToken);
Appointment existingAppointment = await _arpaContext.Appointments.FindAsync([request.Id], cancellationToken);
Room existingRoom = await _arpaContext.Rooms.FindAsync([request.RoomId], cancellationToken);

var appointmentRoom = new AppointmentRoom(null, existingAppointment, existingRoom);

_arpaContext.AppointmentRooms.Add(appointmentRoom);
await _arpaContext.AppointmentRooms.AddAsync(appointmentRoom, cancellationToken);

if (await _arpaContext.SaveChangesAsync(cancellationToken) > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public Validator(IArpaContext arpaContext)
RuleFor(d => d.SectionId)
.EntityExists<Command, Section>(arpaContext)

.MustAsync(async (dto, sectionId, cancellation) => !(await arpaContext.SectionAppointments
.AnyAsync(sa => sa.SectionId == sectionId && sa.AppointmentId == dto.Id, cancellation)))
.MustAsync(async (dto, sectionId, cancellation) => !await arpaContext.SectionAppointments
.AnyAsync(sa => sa.SectionId == sectionId && sa.AppointmentId == dto.Id, cancellation))
.WithMessage("The section is already linked to the appointment");
}
}
Expand All @@ -68,10 +68,10 @@ public Handler(

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
Appointment existingAppointment = await _arpaContext.Appointments.FindAsync(new object[] { request.Id }, cancellationToken);
Section existingSection = await _arpaContext.Sections.FindAsync(new object[] { request.SectionId }, cancellationToken);
Appointment existingAppointment = await _arpaContext.Appointments.FindAsync([request.Id], cancellationToken);
Section existingSection = await _arpaContext.Sections.FindAsync([request.SectionId], cancellationToken);

_arpaContext.SectionAppointments.Add(new SectionAppointment(null, existingSection, existingAppointment));
await _arpaContext.SectionAppointments.AddAsync(new SectionAppointment(null, existingSection, existingAppointment), cancellationToken);

if (await _arpaContext.SaveChangesAsync(cancellationToken) > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ public async Task<Unit> Handle(Command request, CancellationToken cancellationTo
.Select(a => a.Id)
.ToListAsync(cancellationToken);

if(personIds.Count == 0) {
if (personIds.Count == 0)
{
throw new ValidationException([new ValidationFailure(nameof(request.AppointmentId), "No persons are eligible for this appointment. Cannot send email to empty recipient list.")]);
}

Expand All @@ -101,8 +102,8 @@ public async Task<Unit> Handle(Command request, CancellationToken cancellationTo
ClubPhoneNumber = _clubConfiguration.Phone,
AppointmentName = appointment.ToString(),
DateAndTime = $"{appointment.StartTime.ToGermanDateTimeString()} - {appointment.EndTime.ToGermanTimeString()}",
PublicDetails = appointment.PublicDetails ?? "- ohne -",
Venue = appointment.Venue?.ToString() ?? "- ohne -",
PublicDetails = appointment.PublicDetails,
Venue = appointment.Venue?.ToString(),
ArpaUrl = _jwtConfiguration.Audience,
Status = appointment.Status.ToString(),
Sections = string.Join(", ", appointment.SectionAppointments.Select(sa => sa.Section.ToString()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,26 +47,27 @@ public Handler(IArpaContext arpaContext)

public async Task<IEnumerable<AppointmentParticipation>> Handle(Query request, CancellationToken cancellationToken)
{
Guid personId = (await _arpaContext.FindAsync<MusicianProfile>(new object[] { request.MusicianProfileId }, cancellationToken)).PersonId;
Guid personId = (await _arpaContext.FindAsync<MusicianProfile>([request.MusicianProfileId], cancellationToken)).PersonId;

IQueryable<AppointmentParticipation> appointmentParticipations = _arpaContext.AppointmentParticipations
.Where(ap => ap.PersonId.Equals(personId));

if (appointmentParticipations.Any() && request.StartTime.HasValue)
if (await appointmentParticipations.AnyAsync(cancellationToken) && request.StartTime.HasValue)
{
var normalizedTime = new DateTime(request.StartTime.Value.Ticks, DateTimeKind.Unspecified);
appointmentParticipations = appointmentParticipations.Where(ap => ap.Appointment.StartTime.Equals(normalizedTime));
}

if (appointmentParticipations.Any() && request.EndTime.HasValue)
if (await appointmentParticipations.AnyAsync(cancellationToken) && request.EndTime.HasValue)
{
var normalizedTime = new DateTime(request.EndTime.Value.Ticks, DateTimeKind.Unspecified);
appointmentParticipations = appointmentParticipations.Where(ap => ap.Appointment.EndTime.Equals(normalizedTime));
}

if (appointmentParticipations.Any() && request.ProjectId.HasValue)
if (await appointmentParticipations.AnyAsync(cancellationToken) && request.ProjectId.HasValue)
{
appointmentParticipations = appointmentParticipations.Where(ap => ap.Appointment.ProjectAppointments.Any(pa => pa.ProjectId.Equals(request.ProjectId)));
appointmentParticipations = appointmentParticipations.Where(ap =>
ap.Appointment.ProjectAppointments.Any(pa => pa.ProjectId.Equals(request.ProjectId)));
}

return await appointmentParticipations.ToListAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ public Handler(IArpaContext arpaContext, IDateTimeProvider dateTimeProvider)
.Where(appointment => appointmentIds.Contains(appointment.Id) && appointment.EndTime > _dateTimeProvider.GetUtcNow())
.OrderBy(p => p.StartTime);

return (await userAppointments.Skip(request.Offset ?? 0).Take(request.Limit ?? count).ToListAsync(cancellationToken), userAppointments.Count());
return (
await userAppointments.Skip(request.Offset ?? 0).Take(request.Limit ?? count).ToListAsync(cancellationToken),
await userAppointments.CountAsync(cancellationToken)
);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public async Task<Unit> Handle(Command request, CancellationToken cancellationTo
{
var availableDocument = new MusicianProfileDocument(request.Id, request.DocumentId);

_arpaContext.MusicianProfileDocuments.Add(availableDocument);
await _arpaContext.MusicianProfileDocuments.AddAsync(availableDocument, cancellationToken);

if (await _arpaContext.SaveChangesAsync(cancellationToken) > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ public Handler(

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
Person existingPerson = await _arpaContext.Persons.FindAsync(new object[] { request.Id }, cancellationToken);
Section existingSection = await _arpaContext.Sections.FindAsync(new object[] { request.StakeholderGroupId }, cancellationToken);
Person existingPerson = await _arpaContext.Persons.FindAsync([request.Id], cancellationToken);
Section existingSection = await _arpaContext.Sections.FindAsync([request.StakeholderGroupId], cancellationToken);

var personSection = new PersonSection(null, existingPerson, existingSection);

_ = _arpaContext.Set<PersonSection>().Add(personSection);
_ = await _arpaContext.Set<PersonSection>().AddAsync(personSection, cancellationToken);

return await _arpaContext.SaveChangesAsync(cancellationToken) > 0
? Unit.Value
Expand Down
6 changes: 3 additions & 3 deletions Orso.Arpa.Domain/ProjectDomain/Commands/AddRoleToUrl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public Validator(IArpaContext arpaContext, RoleManager<Role> roleManager)
.WithErrorCode("404")
.WithMessage("Role could not be found.")

.MustAsync(async (dto, roleId, cancellation) => !(await arpaContext.EntityExistsAsync<UrlRole>(ar => ar.RoleId == roleId && ar.UrlId == dto.UrlId, cancellation)))
.MustAsync(async (dto, roleId, cancellation) => !await arpaContext.EntityExistsAsync<UrlRole>(ar => ar.RoleId == roleId && ar.UrlId == dto.UrlId, cancellation))
.WithMessage("The role is already linked to the url")

.MustAsync(async (roleId, cancellation) => !await roleManager.Roles.AnyAsync(r => r.Id == roleId && r.Name == RoleNames.Admin, cancellation))
Expand All @@ -79,12 +79,12 @@ public Handler(

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
Url existingUrl = await _arpaContext.Urls.FindAsync(new object[] { request.UrlId }, cancellationToken);
Url existingUrl = await _arpaContext.Urls.FindAsync([request.UrlId], cancellationToken);
Role existingRole = await _roleManager.Roles.SingleAsync(r => r.Id == request.RoleId, cancellationToken);

var urlRole = new UrlRole(null, existingUrl, existingRole);

_arpaContext.UrlRoles.Add(urlRole);
await _arpaContext.UrlRoles.AddAsync(urlRole, cancellationToken);

if (await _arpaContext.SaveChangesAsync(cancellationToken) > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,13 @@
var template = new ProjectParticipationChangedByStaffTemplate
{
ArpaLogo = _jwtConfiguration.ArpaLogo,
CommentByStaff = notification.ProjectParticipation.CommentByStaffInner ?? "- ohne -",
Comment = notification.ProjectParticipation.CommentByPerformerInner ?? "- ohne -",
CommentByStaff = notification.ProjectParticipation.CommentByStaffInner,
Comment = notification.ProjectParticipation.CommentByPerformerInner,
DisplayName = musician.DisplayName,
ParticipationStatusInner = notification.ProjectParticipation.ParticipationStatusInner?.ToString() ?? "- ohne -",
ParticipationStatusInternal = notification.ProjectParticipation.ParticipationStatusInternal?.ToString() ?? "- ohne -",
ParticipationStatusInner = notification.ProjectParticipation.ParticipationStatusInner?.ToString(),
ParticipationStatusInternal = notification.ProjectParticipation.ParticipationStatusInternal?.ToString(),

InvitationStatus = notification.ProjectParticipation?.InvitationStatus?.ToString() ?? "- ohne -",
InvitationStatus = notification.ProjectParticipation?.InvitationStatus?.ToString(),
ProjectName = notification.ProjectParticipation.Project.ToString(),

ClubAddress = _clubConfiguration.Address,
Expand All @@ -111,7 +111,7 @@
}
else
{
_logger.LogError("Could not send the project participation changed email to {musician} because there is no email address assigned to this person.", musician.DisplayName);

Check warning on line 114 in Orso.Arpa.Domain/ProjectDomain/Notifications/ProjectParticipationChangedNotification.cs

View workflow job for this annotation

GitHub Actions / Build and run sonar analysis

Use PascalCase for named placeholders. (https://rules.sonarsource.com/csharp/RSPEC-6678)
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions Orso.Arpa.Domain/UserDomain/Commands/RegisterUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public async Task<Unit> Handle(Command request, CancellationToken cancellationTo
break;
default:
throw new ValidationException(
new ValidationFailure[] { new(nameof(Command.Email), "Multiple persons found with this email address. Registration aborted. Please contact your system admin.") });
[new(nameof(Command.Email), "Multiple persons found with this email address. Registration aborted. Please contact your system admin.")]);
}

var user = new User
Expand All @@ -119,13 +119,13 @@ public async Task<Unit> Handle(Command request, CancellationToken cancellationTo
throw new IdentityException("Problem creating user", result.Errors);
}

_arpaContext.Set<PersonSection>().AddRange(request.StakeholderGroupIds.Select(sg => new PersonSection(null, person.Id, sg)));
_ = _arpaContext.Set<ContactDetail>().Add(new ContactDetail(null, new CreateContactDetail.Command
await _arpaContext.Set<PersonSection>().AddRangeAsync(request.StakeholderGroupIds.Select(sg => new PersonSection(null, person.Id, sg)), cancellationToken);
_ = await _arpaContext.Set<ContactDetail>().AddAsync(new ContactDetail(null, new CreateContactDetail.Command
{
Key = ContactDetailKey.EMail,
PersonId = person.Id,
Value = request.Email,
}));
}), cancellationToken);

return (await _arpaContext.SaveChangesAsync(cancellationToken)) < request.StakeholderGroupIds.Count + 1
? throw new AffectedRowCountMismatchException(nameof(PersonSection))
Expand Down
Loading
Loading