baecf10fea
2.4 — ArtifactDiff: - TRN-2: secret-bearing values (data-connection primary/backup config, DB connection string, external-system auth, SMTP credentials, SMS token) are compared by SHA-256 and reported value-free as <present> -> <changed>, so a changed endpoint no longer reads Identical and is force-skipped. - TRN-6: the instance diff resolves each existing binding's DataConnectionId to its name and compares it (a rebind OPC1 -> OPC2 is Modified); State is no longer compared (the import never carries a live state). 2.5 — BundleImporter / ManagementActor / Central UI: - TRN-3: PreviewAsync takes an optional BundleNameMap (additive optional param); under a MapToExisting redirect the connection/instance diffs, connection auto-match and unresolved-connection blocker run against the mapped target. The CLI import path passes its explicit --map-site/--map-connection redirects to the preview before the blocker gate; the Central UI re-runs the preview under the Map-step choices at Confirm. Apply binds a CreateNew site/connection whose identifier/name already exists to that row instead of inserting a duplicate the unique index rejects. - TRN-7: connection, instance, instance-template and composition/base-template lookups match exact spelling first, then case-insensitively. - TRN-8: InstanceDto gains the additive AreaPath (root->leaf); the exporter fills it and the importer resolves/creates areas level by level under their real parent. A legacy leaf-only bundle with an ambiguous leaf resolves deterministically and adds an ImportResult warning. - TRN-9: Rename is rejected by ApplyAsync for Site, DataConnection, SmtpConfiguration and SmsConfiguration (ImportRenameSupport); the UI does not offer it there and the CLI rename policy falls back to Skip with a warning. Also moves a doc comment misplaced by the 2.6 commit. Reflection round-trip guard (RoundTripEquivalenceTests) re-run: green.
521 lines
27 KiB
C#
521 lines
27 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
|
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
|
using ZB.MOM.WW.ScadaBridge.Transport.Serialization;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
|
|
|
|
/// <summary>
|
|
/// WP2 tasks 2.4 + 2.5 against the real importer and an EF context:
|
|
/// TRN-2 (a changed secret-bearing value reads Modified, value-free), TRN-6 (instance diff
|
|
/// compares the bound connection, not State), TRN-3 (preview honours the name map; CreateNew
|
|
/// against an existing same-name row maps to it), TRN-7 (site-scoped and template-reference
|
|
/// lookups are case-insensitive), TRN-8 (areas resolve by full path), TRN-9 (Rename is
|
|
/// rejected for sites / data connections / SMTP / SMS).
|
|
/// </summary>
|
|
public sealed class ImportMappingAndIdentityTests : IDisposable
|
|
{
|
|
private readonly ServiceProvider _provider;
|
|
|
|
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
|
|
public ImportMappingAndIdentityTests()
|
|
{
|
|
var services = new ServiceCollection();
|
|
services.AddSingleton<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>(
|
|
new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider());
|
|
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
|
|
var dbName = $"ImportMappingAndIdentityTests_{Guid.NewGuid()}";
|
|
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
|
|
.UseInMemoryDatabase(dbName)
|
|
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
|
|
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
|
|
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
|
|
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
|
|
services.AddScoped<INotificationRepository, NotificationRepository>();
|
|
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
|
|
services.AddScoped<ISiteRepository, SiteRepository>();
|
|
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
|
|
services.AddScoped<IAuditService, AuditService>();
|
|
services.AddTransport();
|
|
_provider = services.BuildServiceProvider();
|
|
}
|
|
|
|
/// <summary>Releases the resources held by this instance.</summary>
|
|
public void Dispose() => _provider.Dispose();
|
|
|
|
// ── TRN-2 / TRN-6 (task 2.4) ─────────────────────────────────────────────
|
|
|
|
/// <summary>TRN-2: a target whose connection endpoint changed previews Modified, never echoing the config.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Preview_changed_connection_configuration_is_Modified_without_echo()
|
|
{
|
|
await SeedSiteAsync("plant-1", ("OPC1", "{\"endpoint\":\"opc.tcp://source-host:4840\"}"));
|
|
var sessionId = await ExportSitesAndLoadAsync();
|
|
await MutateAsync(ctx => ctx.DataConnections.Single().PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://target-host:4840\"}");
|
|
|
|
var preview = await PreviewAsync(sessionId);
|
|
|
|
var item = preview.Items.Single(i => i.EntityType == "DataConnection");
|
|
Assert.Equal(ConflictKind.Modified, item.Kind);
|
|
using var diff = System.Text.Json.JsonDocument.Parse(item.FieldDiffJson!);
|
|
var change = diff.RootElement.GetProperty("changes").EnumerateArray()
|
|
.Single(c => c.GetProperty("field").GetString() == "Secrets.PrimaryConfiguration");
|
|
Assert.Equal("<changed>", change.GetProperty("newValue").GetString());
|
|
Assert.DoesNotContain("source-host", item.FieldDiffJson);
|
|
Assert.DoesNotContain("target-host", item.FieldDiffJson);
|
|
}
|
|
|
|
/// <summary>TRN-6: rebinding an attribute to another connection previews Modified; a State-only change is Identical.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Preview_instance_diff_covers_bound_connection_and_ignores_state()
|
|
{
|
|
await SeedSiteAsync("plant-1", ("OPC1", "{}"), ("OPC2", "{}"));
|
|
await SeedInstanceAsync("plant-1", "Pump-01", boundTo: "OPC1");
|
|
var sessionId = await ExportSitesAndLoadAsync();
|
|
|
|
// State only: Identical.
|
|
await MutateAsync(ctx => ctx.Instances.Single().State = InstanceState.Disabled);
|
|
var stateOnly = await PreviewAsync(sessionId);
|
|
Assert.Equal(ConflictKind.Identical, stateOnly.Items.Single(i => i.EntityType == "Instance").Kind);
|
|
|
|
// Rebind OPC1 -> OPC2 on the target: Modified.
|
|
await MutateAsync(ctx =>
|
|
{
|
|
var opc2 = ctx.DataConnections.Single(c => c.Name == "OPC2");
|
|
ctx.InstanceConnectionBindings.Single().DataConnectionId = opc2.Id;
|
|
});
|
|
var rebound = await PreviewAsync(sessionId);
|
|
var item = rebound.Items.Single(i => i.EntityType == "Instance");
|
|
Assert.Equal(ConflictKind.Modified, item.Kind);
|
|
Assert.Contains("ConnectionBindings", item.FieldDiffJson);
|
|
}
|
|
|
|
// ── TRN-3 (task 2.5) ─────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// TRN-3 scenario A: an instance-only bundle for site-a bound to OPC1, imported with
|
|
/// site-a mapped to site-x (which has OPC1). The unmapped preview blocks; the mapped
|
|
/// preview does not, auto-matches the connection on the mapped site, and the apply binds it.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Preview_with_site_map_resolves_connection_on_the_mapped_site()
|
|
{
|
|
await SeedTemplateAsync("Pump");
|
|
await SeedSiteAsync("site-x", ("OPC1", "{}"));
|
|
var sessionId = await PackAndLoadAsync(Content(instances:
|
|
[
|
|
Instance("Pump-01", "site-a", bindings: [new InstanceConnectionBindingDto("Flow", "OPC1", "ns=2;s=Flow")]),
|
|
]));
|
|
|
|
var unmapped = await PreviewAsync(sessionId);
|
|
Assert.Contains(unmapped.Items, i => i.Kind == ConflictKind.Blocker && i.Name == "site-a/OPC1");
|
|
|
|
var map = new BundleNameMap(
|
|
[new SiteMapping("site-a", MappingAction.MapToExisting, "site-x")],
|
|
Array.Empty<ConnectionMapping>());
|
|
var mapped = await PreviewAsync(sessionId, map);
|
|
Assert.DoesNotContain(mapped.Items, i => i.Kind == ConflictKind.Blocker);
|
|
Assert.Equal("site-x", mapped.RequiredSiteMappings.Single().AutoMatchTargetIdentifier);
|
|
Assert.Equal("OPC1", mapped.RequiredConnectionMappings.Single().AutoMatchTargetName);
|
|
|
|
await ApplyAsync(sessionId,
|
|
[new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)],
|
|
map with
|
|
{
|
|
Connections = [new ConnectionMapping("site-a", "OPC1", MappingAction.MapToExisting, "OPC1")],
|
|
});
|
|
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var siteX = await ctx.Sites.SingleAsync(s => s.SiteIdentifier == "site-x");
|
|
var opc1 = await ctx.DataConnections.SingleAsync(c => c.SiteId == siteX.Id && c.Name == "OPC1");
|
|
var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync();
|
|
Assert.Equal(siteX.Id, instance.SiteId);
|
|
Assert.Equal(opc1.Id, instance.ConnectionBindings.Single().DataConnectionId);
|
|
}
|
|
|
|
/// <summary>
|
|
/// TRN-3 scenario B: CreateNew for a carried connection whose name already exists on the
|
|
/// mapped target site maps to the existing row instead of inserting a duplicate.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task CreateNew_connection_with_existing_name_on_mapped_site_maps_to_it()
|
|
{
|
|
await SeedSiteAsync("site-x", ("OPC1", "{\"endpoint\":\"target\"}"));
|
|
var sessionId = await PackAndLoadAsync(Content(connections:
|
|
[
|
|
new DataConnectionDto("site-a", "OPC1", "OpcUa", 3,
|
|
new SecretsBlock(new Dictionary<string, string> { ["PrimaryConfiguration"] = "{\"endpoint\":\"source\"}" })),
|
|
]));
|
|
|
|
await ApplyAsync(sessionId,
|
|
[new ImportResolution("DataConnection", "site-a/OPC1", ResolutionAction.Skip, null)],
|
|
new BundleNameMap(
|
|
[new SiteMapping("site-a", MappingAction.MapToExisting, "site-x")],
|
|
[new ConnectionMapping("site-a", "OPC1", MappingAction.CreateNew, null)]));
|
|
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var conn = await ctx.DataConnections.SingleAsync();
|
|
Assert.Equal("{\"endpoint\":\"target\"}", conn.PrimaryConfiguration);
|
|
}
|
|
|
|
// ── TRN-7 (task 2.5) ─────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// TRN-7: a bundle connection differing only in case matches the target row (preview is
|
|
/// not New, apply does not insert a duplicate the unique (SiteId, Name) index would reject),
|
|
/// and an instance binding naming it in a different case resolves to it. (The instance
|
|
/// UniqueName half of TRN-7 depends on the SQL Server collation returning the case
|
|
/// variant from the repository read, which the in-memory provider does not emulate; the
|
|
/// importer's own lookups over that read are case-insensitive.)
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Case_variant_connection_matches_existing_row()
|
|
{
|
|
await SeedTemplateAsync("Pump");
|
|
await SeedSiteAsync("plant-1", ("OPC1", "{}"));
|
|
var sessionId = await PackAndLoadAsync(Content(
|
|
sites: [new SiteDto("plant-1", "plant-1", null, null, null, null, null)],
|
|
connections: [new DataConnectionDto("plant-1", "Opc1", "OpcUa", 3,
|
|
new SecretsBlock(new Dictionary<string, string> { ["PrimaryConfiguration"] = "{}" }))],
|
|
instances: [Instance("Pump-01", "plant-1", bindings: [new InstanceConnectionBindingDto("Flow", "opc1", null)])]));
|
|
|
|
var preview = await PreviewAsync(sessionId);
|
|
Assert.Equal(ConflictKind.Identical, preview.Items.Single(i => i.EntityType == "DataConnection").Kind);
|
|
Assert.DoesNotContain(preview.Items, i => i.Kind == ConflictKind.Blocker);
|
|
|
|
await ApplyAsync(sessionId,
|
|
[
|
|
new ImportResolution("DataConnection", "plant-1/Opc1", ResolutionAction.Overwrite, null),
|
|
new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null),
|
|
],
|
|
BundleNameMap.Empty);
|
|
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var conn = await ctx.DataConnections.SingleAsync();
|
|
var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync();
|
|
Assert.Equal(conn.Id, instance.ConnectionBindings.Single().DataConnectionId);
|
|
}
|
|
|
|
/// <summary>
|
|
/// TRN-7: a child whose bundle base is 'PumpBase' resolves its inheritance edge against
|
|
/// the target's 'pumpbase' (the base itself is not re-imported) instead of nulling it.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Case_variant_base_template_keeps_child_inheritance_edge()
|
|
{
|
|
await MutateAsync(ctx => ctx.Templates.Add(new Template("PumpBase")));
|
|
await MutateAsync(ctx => ctx.Templates.Add(new Template("Child") { ParentTemplateId = ctx.Templates.Single(t => t.Name == "PumpBase").Id }));
|
|
var bundle = await ExportTemplatesAsync();
|
|
await MutateAsync(ctx => ctx.Templates.Single(t => t.Name == "PumpBase").Name = "pumpbase");
|
|
|
|
var sessionId = await LoadAsync(bundle);
|
|
await ApplyAsync(sessionId,
|
|
[
|
|
new ImportResolution("Template", "PumpBase", ResolutionAction.Skip, null),
|
|
new ImportResolution("Template", "Child", ResolutionAction.Overwrite, null),
|
|
],
|
|
BundleNameMap.Empty);
|
|
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var baseId = await ctx.Templates.Where(t => t.Name == "pumpbase").Select(t => t.Id).SingleAsync();
|
|
var child = await ctx.Templates.SingleAsync(t => t.Name == "Child");
|
|
Assert.Equal(baseId, child.ParentTemplateId);
|
|
}
|
|
|
|
// ── TRN-8 (task 2.5) ─────────────────────────────────────────────────────
|
|
|
|
/// <summary>TRN-8: an instance in Line2/Cell lands in Line2/Cell, not whichever 'Cell' comes back first.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Area_resolves_by_full_path_when_leaf_name_is_shared()
|
|
{
|
|
await SeedSiteAsync("plant-1", ("OPC1", "{}"));
|
|
var (line1Cell, line2Cell) = await SeedTwoCellsAsync("plant-1");
|
|
await SeedInstanceAsync("plant-1", "Pump-01", boundTo: "OPC1", areaId: line2Cell);
|
|
var sessionId = await ExportSitesAndLoadAsync();
|
|
// Target: move the instance to Line1/Cell, then Overwrite from the bundle.
|
|
await MutateAsync(ctx => ctx.Instances.Single().AreaId = line1Cell);
|
|
|
|
var preview = await PreviewAsync(sessionId);
|
|
var item = preview.Items.Single(i => i.EntityType == "Instance");
|
|
Assert.Equal(ConflictKind.Modified, item.Kind);
|
|
Assert.Contains("AreaPath", item.FieldDiffJson);
|
|
|
|
await ApplyAsync(sessionId,
|
|
[new ImportResolution("Instance", "Pump-01", ResolutionAction.Overwrite, null)],
|
|
BundleNameMap.Empty);
|
|
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
Assert.Equal(line2Cell, (await ctx.Instances.SingleAsync()).AreaId);
|
|
Assert.Equal(4, await ctx.Areas.CountAsync()); // Line1, Line2 and both Cells — nothing created
|
|
|
|
}
|
|
|
|
/// <summary>TRN-8: a missing nested area is created under its real parent, not at the site root.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Missing_nested_area_is_created_under_its_parent()
|
|
{
|
|
await SeedTemplateAsync("Pump");
|
|
await SeedSiteAsync("plant-1");
|
|
var sessionId = await PackAndLoadAsync(Content(instances:
|
|
[
|
|
Instance("Pump-01", "plant-1") with { AreaName = "Cell", AreaPath = ["Line2", "Cell"] },
|
|
]));
|
|
|
|
await ApplyAsync(sessionId, [new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)], BundleNameMap.Empty);
|
|
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var line2 = await ctx.Areas.SingleAsync(a => a.Name == "Line2");
|
|
var cell = await ctx.Areas.SingleAsync(a => a.Name == "Cell");
|
|
Assert.Null(line2.ParentAreaId);
|
|
Assert.Equal(line2.Id, cell.ParentAreaId);
|
|
Assert.Equal(cell.Id, (await ctx.Instances.SingleAsync()).AreaId);
|
|
}
|
|
|
|
/// <summary>TRN-8: a legacy (path-less) bundle with an ambiguous leaf name warns instead of guessing silently.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Legacy_ambiguous_leaf_area_name_warns()
|
|
{
|
|
await SeedTemplateAsync("Pump");
|
|
await SeedSiteAsync("plant-1");
|
|
await SeedTwoCellsAsync("plant-1");
|
|
var sessionId = await PackAndLoadAsync(Content(instances:
|
|
[
|
|
Instance("Pump-01", "plant-1") with { AreaName = "Cell" },
|
|
]));
|
|
|
|
var result = await ApplyAsync(sessionId, [new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)], BundleNameMap.Empty);
|
|
|
|
Assert.Contains(result.Warnings, w => w.Contains("area 'Cell' matches 2 areas"));
|
|
}
|
|
|
|
// ── TRN-9 (task 2.5) ─────────────────────────────────────────────────────
|
|
|
|
/// <summary>TRN-9: Rename is rejected for sites, data connections, SMTP and SMS configurations.</summary>
|
|
/// <param name="entityType">The resolution's entity type.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData("Site")]
|
|
[InlineData("DataConnection")]
|
|
[InlineData("SmtpConfiguration")]
|
|
[InlineData("SmsConfiguration")]
|
|
public async Task Rename_is_rejected_for_unsupported_entity_types(string entityType)
|
|
{
|
|
var sessionId = await PackAndLoadAsync(Content());
|
|
var ex = await Assert.ThrowsAsync<ArgumentException>(() => ApplyAsync(sessionId,
|
|
[new ImportResolution(entityType, "x", ResolutionAction.Rename, "y")], BundleNameMap.Empty));
|
|
Assert.Contains("Rename is not supported", ex.Message);
|
|
}
|
|
|
|
// ── helpers ──────────────────────────────────────────────────────────────
|
|
|
|
private async Task MutateAsync(Action<ScadaBridgeDbContext> mutate)
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
mutate(ctx);
|
|
await ctx.SaveChangesAsync();
|
|
}
|
|
|
|
private Task SeedTemplateAsync(string name) => MutateAsync(ctx =>
|
|
{
|
|
var t = new Template(name);
|
|
t.Attributes.Add(new TemplateAttribute("Flow") { Value = "0" });
|
|
ctx.Templates.Add(t);
|
|
});
|
|
|
|
private async Task SeedSiteAsync(string identifier, params (string Name, string Config)[] connections)
|
|
{
|
|
await MutateAsync(ctx => ctx.Sites.Add(new Site(identifier, identifier)));
|
|
await MutateAsync(ctx =>
|
|
{
|
|
var site = ctx.Sites.Single(s => s.SiteIdentifier == identifier);
|
|
foreach (var (name, config) in connections)
|
|
ctx.DataConnections.Add(new DataConnection(name, "OpcUa", site.Id) { PrimaryConfiguration = config, FailoverRetryCount = 3 });
|
|
});
|
|
}
|
|
|
|
private async Task SeedInstanceAsync(string siteIdentifier, string name, string boundTo, int? areaId = null)
|
|
{
|
|
if (!await AnyTemplateAsync()) await SeedTemplateAsync("Pump");
|
|
await MutateAsync(ctx =>
|
|
{
|
|
var site = ctx.Sites.Single(s => s.SiteIdentifier == siteIdentifier);
|
|
var conn = ctx.DataConnections.Single(c => c.SiteId == site.Id && c.Name == boundTo);
|
|
var instance = new Instance(name)
|
|
{
|
|
TemplateId = ctx.Templates.First().Id, SiteId = site.Id, State = InstanceState.Enabled, AreaId = areaId,
|
|
};
|
|
instance.ConnectionBindings.Add(new InstanceConnectionBinding("Flow")
|
|
{
|
|
DataConnectionId = conn.Id, DataSourceReferenceOverride = "ns=2;s=Flow",
|
|
});
|
|
ctx.Instances.Add(instance);
|
|
});
|
|
}
|
|
|
|
private async Task<bool> AnyTemplateAsync()
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
return await scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().Templates.AnyAsync();
|
|
}
|
|
|
|
private async Task<(int Line1Cell, int Line2Cell)> SeedTwoCellsAsync(string siteIdentifier)
|
|
{
|
|
int line1Cell = 0, line2Cell = 0;
|
|
await MutateAsync(ctx =>
|
|
{
|
|
var siteId = ctx.Sites.Single(s => s.SiteIdentifier == siteIdentifier).Id;
|
|
ctx.Areas.Add(new Area("Line1") { SiteId = siteId });
|
|
ctx.Areas.Add(new Area("Line2") { SiteId = siteId });
|
|
});
|
|
await MutateAsync(ctx =>
|
|
{
|
|
var line1 = ctx.Areas.Single(a => a.Name == "Line1");
|
|
var line2 = ctx.Areas.Single(a => a.Name == "Line2");
|
|
ctx.Areas.Add(new Area("Cell") { SiteId = line1.SiteId, ParentAreaId = line1.Id });
|
|
ctx.Areas.Add(new Area("Cell") { SiteId = line2.SiteId, ParentAreaId = line2.Id });
|
|
});
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var c = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var l1 = await c.Areas.SingleAsync(a => a.Name == "Line1");
|
|
var l2 = await c.Areas.SingleAsync(a => a.Name == "Line2");
|
|
line1Cell = (await c.Areas.SingleAsync(a => a.Name == "Cell" && a.ParentAreaId == l1.Id)).Id;
|
|
line2Cell = (await c.Areas.SingleAsync(a => a.Name == "Cell" && a.ParentAreaId == l2.Id)).Id;
|
|
return (line1Cell, line2Cell);
|
|
}
|
|
|
|
private static InstanceDto Instance(string name, string site, IReadOnlyList<InstanceConnectionBindingDto>? bindings = null) =>
|
|
new(name, "Pump", site, AreaName: null, InstanceState.NotDeployed,
|
|
Array.Empty<InstanceAttributeOverrideDto>(),
|
|
Array.Empty<InstanceAlarmOverrideDto>(),
|
|
Array.Empty<InstanceNativeAlarmSourceOverrideDto>(),
|
|
bindings ?? Array.Empty<InstanceConnectionBindingDto>());
|
|
|
|
private static BundleContentDto Content(
|
|
IReadOnlyList<SiteDto>? sites = null,
|
|
IReadOnlyList<DataConnectionDto>? connections = null,
|
|
IReadOnlyList<InstanceDto>? instances = null) =>
|
|
new(
|
|
TemplateFolders: Array.Empty<TemplateFolderDto>(),
|
|
Templates: Array.Empty<TemplateDto>(),
|
|
SharedScripts: Array.Empty<SharedScriptDto>(),
|
|
ExternalSystems: Array.Empty<ExternalSystemDto>(),
|
|
DatabaseConnections: Array.Empty<DatabaseConnectionDto>(),
|
|
NotificationLists: Array.Empty<NotificationListDto>(),
|
|
SmtpConfigs: Array.Empty<SmtpConfigDto>(),
|
|
ApiMethods: Array.Empty<ApiMethodDto>())
|
|
{
|
|
Sites = sites ?? Array.Empty<SiteDto>(),
|
|
DataConnections = connections ?? Array.Empty<DataConnectionDto>(),
|
|
Instances = instances ?? Array.Empty<InstanceDto>(),
|
|
};
|
|
|
|
private async Task<Guid> PackAndLoadAsync(BundleContentDto content)
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var manifestBuilder = scope.ServiceProvider.GetRequiredService<ManifestBuilder>();
|
|
var serializer = scope.ServiceProvider.GetRequiredService<BundleSerializer>();
|
|
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
|
var summary = new BundleSummary(
|
|
Templates: 0, TemplateFolders: 0, SharedScripts: 0, ExternalSystems: 0, DbConnections: 0,
|
|
NotificationLists: 0, SmtpConfigs: 0, ApiMethods: 0,
|
|
Sites: content.Sites.Count, DataConnections: content.DataConnections.Count, Instances: content.Instances.Count);
|
|
var manifest = manifestBuilder.Build(
|
|
sourceEnvironment: "dev", exportedBy: "alice", scadaBridgeVersion: "1.0.0", encryption: null,
|
|
summary: summary, contents: Array.Empty<ManifestContentEntry>(),
|
|
contentBytes: serializer.SerializeContentBytes(content));
|
|
await using var packed = serializer.Pack(content, manifest, passphrase: null, encryptor: null);
|
|
using var ms = new MemoryStream();
|
|
await packed.CopyToAsync(ms);
|
|
ms.Position = 0;
|
|
return (await importer.LoadAsync(ms, passphrase: null)).SessionId;
|
|
}
|
|
|
|
private async Task<Guid> ExportSitesAndLoadAsync()
|
|
{
|
|
byte[] bytes;
|
|
await using (var scope = _provider.CreateAsyncScope())
|
|
{
|
|
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var selection = new ExportSelection(
|
|
TemplateIds: Array.Empty<int>(), SharedScriptIds: Array.Empty<int>(),
|
|
ExternalSystemIds: Array.Empty<int>(), DatabaseConnectionIds: Array.Empty<int>(),
|
|
NotificationListIds: Array.Empty<int>(), SmtpConfigurationIds: Array.Empty<int>(),
|
|
ApiMethodIds: Array.Empty<int>(), IncludeDependencies: true,
|
|
SiteIds: await ctx.Sites.Select(s => s.Id).ToListAsync());
|
|
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
|
passphrase: null, cancellationToken: CancellationToken.None);
|
|
using var ms = new MemoryStream();
|
|
await stream.CopyToAsync(ms);
|
|
bytes = ms.ToArray();
|
|
}
|
|
return await LoadAsync(bytes);
|
|
}
|
|
|
|
private async Task<byte[]> ExportTemplatesAsync()
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
|
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
|
var selection = new ExportSelection(
|
|
TemplateIds: await ctx.Templates.Select(t => t.Id).ToListAsync(), SharedScriptIds: Array.Empty<int>(),
|
|
ExternalSystemIds: Array.Empty<int>(), DatabaseConnectionIds: Array.Empty<int>(),
|
|
NotificationListIds: Array.Empty<int>(), SmtpConfigurationIds: Array.Empty<int>(),
|
|
ApiMethodIds: Array.Empty<int>(), IncludeDependencies: false);
|
|
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
|
passphrase: null, cancellationToken: CancellationToken.None);
|
|
using var ms = new MemoryStream();
|
|
await stream.CopyToAsync(ms);
|
|
return ms.ToArray();
|
|
}
|
|
|
|
private async Task<Guid> LoadAsync(byte[] bundle)
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
using var ms = new MemoryStream(bundle, writable: false);
|
|
return (await scope.ServiceProvider.GetRequiredService<IBundleImporter>().LoadAsync(ms, passphrase: null)).SessionId;
|
|
}
|
|
|
|
private async Task<ImportPreview> PreviewAsync(Guid sessionId, BundleNameMap? map = null)
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
return await scope.ServiceProvider.GetRequiredService<IBundleImporter>().PreviewAsync(sessionId, CancellationToken.None, map);
|
|
}
|
|
|
|
private async Task<ImportResult> ApplyAsync(Guid sessionId, IReadOnlyList<ImportResolution> resolutions, BundleNameMap map)
|
|
{
|
|
await using var scope = _provider.CreateAsyncScope();
|
|
return await scope.ServiceProvider.GetRequiredService<IBundleImporter>()
|
|
.ApplyAsync(sessionId, resolutions, user: "bob", ct: CancellationToken.None, nameMap: map);
|
|
}
|
|
}
|