Skip to content

Commit

Permalink
- Made calls to npgsql params async (#519)
Browse files Browse the repository at this point in the history
- Div other sonarcloud suggestions

Co-authored-by: Henning Normann <[email protected]>
  • Loading branch information
HenningNormann and Henning Normann authored Oct 8, 2024
1 parent f3fdfa9 commit a96d26e
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 72 deletions.
34 changes: 15 additions & 19 deletions src/Storage/Controllers/ContentOnDemandController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,28 +148,24 @@ public async Task<Stream> GetFormdataAsPdf([FromRoute] string org, [FromRoute] s
if (xsls.Count > 1 && xsls.Exists(x => x.IsPortrait) && xsls.Exists(x => !x.IsPortrait))
{
// Mix of portrait and landscape, we must generate each page and merge them
using (var mergedDoc = new PdfDocument())
using var mergedDoc = new PdfDocument();
foreach (var xsl in xsls)
{
foreach (var xsl in xsls)
var pdfPages = await _pdfGeneratorClient.GeneratePdf(
$"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}"
.Replace("formdatapdf", $"formdatahtml/{xsl.PageNumber}"),
xsl.IsPortrait);
using var pageDoc = PdfReader.Open(pdfPages, PdfDocumentOpenMode.Import);
for (var i = 0; i < pageDoc.PageCount; i++)
{
var pdfPages = await _pdfGeneratorClient.GeneratePdf(
$"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}"
.Replace("formdatapdf", $"formdatahtml/{xsl.PageNumber}"),
xsl.IsPortrait);
using (var pageDoc = PdfReader.Open(pdfPages, PdfDocumentOpenMode.Import))
{
for (var i = 0; i < pageDoc.PageCount; i++)
{
pageDoc.Pages[i].Orientation = xsl.IsPortrait ? PdfSharp.PageOrientation.Portrait : PdfSharp.PageOrientation.Landscape;
mergedDoc.AddPage(pageDoc.Pages[i]);
}
}
pageDoc.Pages[i].Orientation = xsl.IsPortrait ? PdfSharp.PageOrientation.Portrait : PdfSharp.PageOrientation.Landscape;
mergedDoc.AddPage(pageDoc.Pages[i]);
}

MemoryStream mergedPdf = new MemoryStream();
mergedDoc.Save(mergedPdf);
return mergedPdf;
}

MemoryStream mergedPdf = new();
mergedDoc.Save(mergedPdf);
return mergedPdf;
}
else
{
Expand Down Expand Up @@ -287,7 +283,7 @@ public class SignatureView
/// Gets or sets whether this signing is done for all the items in the form
/// 1=Group signing is set, 2=Group signing not set, 3=Group signing defined at each form level
/// </summary>
////public int IsSigningAllRequired { get; set; }
public int IsSigningAllRequired { get; set; }

/// <summary>
/// Gets or sets The authentication level attached with that signature.
Expand Down
52 changes: 20 additions & 32 deletions src/Storage/Repository/PgA2Repository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@ namespace Altinn.Platform.Storage.Repository
/// <summary>
/// Handles a2 repository.
/// </summary>
public class PgA2Repository : IA2Repository
/// <remarks>
/// Initializes a new instance of the <see cref="PgA2Repository"/> class.
/// </remarks>
/// <param name="dataSource">The npgsql data source.</param>
/// <param name="telemetryClient">Telemetry client</param>
public class PgA2Repository(
NpgsqlDataSource dataSource,
TelemetryClient telemetryClient = null) : IA2Repository
{
private static readonly string _readXslSql = "select * from storage.reada2xsls (@_org, @_app, @_lformid, @_language, @_xsltype)";
private static readonly string _insertXslSql = "call storage.inserta2xsl (@_org, @_app, @_lformid, @_language, @_pagenumber, @_xsl, @_xsltype, @_isportrait)";
Expand All @@ -30,27 +37,8 @@ public class PgA2Repository : IA2Repository
private static readonly string _updateMigrationStateCompletedSql = "call storage.updatea2migrationstatecompleted (@_instanceguid)";
private static readonly string _deleteMigrationStateSql = "call storage.deletea2migrationstate (@_instanceguid)";

private readonly NpgsqlDataSource _dataSource;
private readonly TelemetryClient _telemetryClient;
private readonly ILogger<PgA2Repository> _logger;

/// <summary>
/// Initializes a new instance of the <see cref="PgA2Repository"/> class.
/// </summary>
/// <param name="generalSettings">the general settings</param>
/// <param name="dataSource">The npgsql data source.</param>
/// <param name="logger">Logger</param>
/// <param name="telemetryClient">Telemetry client</param>
public PgA2Repository(
IOptions<GeneralSettings> generalSettings,
NpgsqlDataSource dataSource,
ILogger<PgA2Repository> logger,
TelemetryClient telemetryClient = null)
{
_dataSource = dataSource;
_telemetryClient = telemetryClient;
_logger = logger;
}
private readonly NpgsqlDataSource _dataSource = dataSource;
private readonly TelemetryClient _telemetryClient = telemetryClient;

/// <inheritdoc/>
public async Task CreateXsl(string org, string app, int lformId, string language, int pageNumber, string xsl, int xslType, bool isPortrait)
Expand Down Expand Up @@ -120,7 +108,7 @@ public async Task CreateImage(string name, byte[] image)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
xsls.Add((reader.GetFieldValue<string>("xsl"), reader.GetFieldValue<bool>("isportrait")));
xsls.Add((await reader.GetFieldValueAsync<string>("xsl"), await reader.GetFieldValueAsync<bool>("isportrait")));
}

tracker.Track();
Expand All @@ -145,7 +133,7 @@ public async Task<byte[]> GetImage(string name)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
image = reader.GetFieldValue<byte[]>("image");
image = await reader.GetFieldValueAsync<byte[]>("image");
}

tracker.Track();
Expand All @@ -169,7 +157,7 @@ public async Task<string> GetCodelist(string name, string preferredLanguage)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
codelist = reader.GetFieldValue<string>("codelist");
codelist = await reader.GetFieldValueAsync<string>("codelist");
}

tracker.Track();
Expand Down Expand Up @@ -238,7 +226,7 @@ public async Task<string> GetMigrationInstanceId(int a2ArchiveReference)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
instanceId = reader.IsDBNull("instanceguid") ? null : reader.GetFieldValue<Guid>("instanceguid").ToString();
instanceId = await reader.IsDBNullAsync("instanceguid") ? null : (await reader.GetFieldValueAsync<Guid>("instanceguid")).ToString();
}

tracker.Track();
Expand All @@ -247,13 +235,13 @@ public async Task<string> GetMigrationInstanceId(int a2ArchiveReference)

private static List<string> GetOrderedLanguages(string language)
{
switch (language)
return language switch
{
case "nb": return new List<string> { "nb", "nn", "en" };
case "nn": return new List<string> { "nn", "nb", "en" };
case "en": return new List<string> { "en", "nb", "nn" };
default: return new List<string> { "nb", "nn", "en" };
}
"nb" => ["nb", "nn", "en"],
"nn" => ["nn", "nb", "en"],
"en" => ["en", "nb", "nn"],
_ => ["nb", "nn", "en"],
};
}
}
}
6 changes: 3 additions & 3 deletions src/Storage/Repository/PgApplicationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public async Task<List<Application>> FindAll()
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
applications.Add(reader.GetFieldValue<Application>("application"));
applications.Add(await reader.GetFieldValueAsync<Application>("application"));
}

tracker.Track();
Expand All @@ -88,7 +88,7 @@ public async Task<List<Application>> FindByOrg(string org)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
applications.Add(reader.GetFieldValue<Application>("application"));
applications.Add(await reader.GetFieldValueAsync<Application>("application"));
}

tracker.Track();
Expand All @@ -108,7 +108,7 @@ public async Task<Application> FindOne(string appId, string org)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
application = reader.GetFieldValue<Application>("application");
application = await reader.GetFieldValueAsync<Application>("application");
_memoryCache.Set(cacheKey, application, _cacheEntryOptionsMetadata);
}
else
Expand Down
6 changes: 3 additions & 3 deletions src/Storage/Repository/PgDataRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public async Task<DataElement> Create(DataElement dataElement, long instanceInte
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
dataElement = reader.GetFieldValue<DataElement>("updatedElement");
dataElement = await reader.GetFieldValueAsync<DataElement>("updatedElement");
}

tracker.Track();
Expand Down Expand Up @@ -104,7 +104,7 @@ public async Task<DataElement> Read(Guid instanceGuid, Guid dataElementId)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
dataElement = reader.GetFieldValue<DataElement>("element");
dataElement = await reader.GetFieldValueAsync<DataElement>("element");
}

tracker.Track();
Expand Down Expand Up @@ -168,7 +168,7 @@ public async Task<DataElement> Update(Guid instanceGuid, Guid dataElementId, Dic
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
element = reader.GetFieldValue<DataElement>("updatedElement");
element = await reader.GetFieldValueAsync<DataElement>("updatedElement");
}

tracker.Track();
Expand Down
4 changes: 2 additions & 2 deletions src/Storage/Repository/PgInstanceEventRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task<InstanceEvent> GetOneEvent(string instanceId, Guid eventGuid)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
instanceEvent = reader.GetFieldValue<InstanceEvent>("event");
instanceEvent = await reader.GetFieldValueAsync<InstanceEvent>("event");
}

tracker.Track();
Expand All @@ -88,7 +88,7 @@ public async Task<List<InstanceEvent>> ListInstanceEvents(
{
while (await reader.ReadAsync())
{
events.Add(reader.GetFieldValue<InstanceEvent>("event"));
events.Add(await reader.GetFieldValueAsync<InstanceEvent>("event"));
}
}

Expand Down
22 changes: 11 additions & 11 deletions src/Storage/Repository/PgInstanceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public async Task<List<Instance>> GetHardDeletedInstances()
{
while (await reader.ReadAsync())
{
Instance i = reader.GetFieldValue<Instance>("instance");
Instance i = await reader.GetFieldValueAsync<Instance>("instance");
if ((i.CompleteConfirmations != null && i.CompleteConfirmations.Exists(c => c.StakeholderId.ToLower().Equals(i.Org) && c.ConfirmedOn <= DateTime.UtcNow.AddDays(-7)))
|| !i.Status.IsArchived)
{
Expand All @@ -154,10 +154,10 @@ public async Task<List<DataElement>> GetHardDeletedDataElements()
bool currentInstanceAllowsDelete = false;
while (await reader.ReadAsync())
{
id = reader.GetFieldValue<long>("id");
id = await reader.GetFieldValueAsync<long>("id");
if (id != previousId)
{
Instance instance = reader.GetFieldValue<Instance>("instance");
Instance instance = await reader.GetFieldValueAsync<Instance>("instance");
currentInstanceAllowsDelete =
instance.CompleteConfirmations != null &&
instance.CompleteConfirmations.Exists(c => c.StakeholderId.Equals(instance.Org, StringComparison.OrdinalIgnoreCase) &&
Expand All @@ -167,7 +167,7 @@ public async Task<List<DataElement>> GetHardDeletedDataElements()

if (currentInstanceAllowsDelete)
{
elements.Add(reader.GetFieldValue<DataElement>("element"));
elements.Add(await reader.GetFieldValueAsync<DataElement>("element"));
}
}

Expand Down Expand Up @@ -278,15 +278,15 @@ private async Task<InstanceQueryResponse> GetInstancesInternal(
Instance instance = new(); // make sonarcloud happy
while (await reader.ReadAsync())
{
id = reader.GetFieldValue<long>("id");
id = await reader.GetFieldValueAsync<long>("id");
if (id != previousId)
{
if (previousId != -1)
{
ToExternal(instance);
}

instance = reader.GetFieldValue<Instance>("instance");
instance = await reader.GetFieldValueAsync<Instance>("instance");
lastChanged = instance.LastChanged ?? DateTime.MinValue;
queryResponse.Instances.Add(instance);
instance.Data = [];
Expand All @@ -295,7 +295,7 @@ private async Task<InstanceQueryResponse> GetInstancesInternal(

if (!reader.IsDBNull("element"))
{
instance.Data.Add(reader.GetFieldValue<DataElement>("element"));
instance.Data.Add(await reader.GetFieldValueAsync<DataElement>("element"));
}
}

Expand Down Expand Up @@ -337,13 +337,13 @@ private async Task<InstanceQueryResponse> GetInstancesInternal(
if (!instanceCreated)
{
instanceCreated = true;
instance = reader.GetFieldValue<Instance>("instance");
instanceInternalId = reader.GetFieldValue<long>("id");
instance = await reader.GetFieldValueAsync<Instance>("instance");
instanceInternalId = await reader.GetFieldValueAsync<long>("id");
}

if (includeElements && !reader.IsDBNull("element"))
{
instanceData.Add(reader.GetFieldValue<DataElement>("element"));
instanceData.Add(await reader.GetFieldValueAsync<DataElement>("element"));
}
}

Expand Down Expand Up @@ -387,7 +387,7 @@ public async Task<Instance> Update(Instance instance, List<string> updatePropert
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
instance = reader.GetFieldValue<Instance>("updatedInstance");
instance = await reader.GetFieldValueAsync<Instance>("updatedInstance");
}

instance.Data = dataElements;
Expand Down
4 changes: 2 additions & 2 deletions src/Storage/Repository/PgTextRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task<TextResource> Get(string org, string app, string language)
await using NpgsqlDataReader reader = await pgcom.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
textResource = PostProcess(org, app, language, reader.GetFieldValue<TextResource>("textResource"));
textResource = PostProcess(org, app, language, await reader.GetFieldValueAsync<TextResource>("textResource"));
}
else
{
Expand Down Expand Up @@ -129,7 +129,7 @@ public async Task<TextResource> Create(string org, string app, TextResource text
await using NpgsqlDataReader reader = await pgcomReadApp.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
applicationInternalId = reader.GetFieldValue<int>("id");
applicationInternalId = await reader.GetFieldValueAsync<int>("id");
}
else
{
Expand Down

0 comments on commit a96d26e

Please sign in to comment.