LotSizingDataModel.Core 2.1.0
Core domain model, shared abstractions and XML-serializable entities.
Loading...
Searching...
No Matches
TransportXmlMigration.cs
Go to the documentation of this file.
1using System;
2using System.Globalization;
3using System.Linq;
4using System.Xml;
5using System.Xml.Linq;
7
9
10/// <summary>Lossless, in-memory migration of legacy nested transport lanes. Input files are never written.</summary>
11public static class TransportXmlMigration
12{
13 /// <summary>Loads XML through the caller's secure reader and returns a migrated copy.</summary>
14 public static XDocument ReadAndMigrate(XmlReader reader)
15 {
16 ArgumentNullException.ThrowIfNull(reader);
17 var document = XDocument.Load(reader);
18 if (document.Root is { } root)
20 foreach (var chain in document.Descendants().Where(e => e.Name.LocalName == "supplyChain"))
21 MigrateSupplyChain(chain);
22 return document;
23 }
24
25 private static void MigrateSupplyChain(XElement chain)
26 {
27 XNamespace ns = chain.Name.Namespace;
28 var version = (string?)chain.Attribute("transportFormatVersion");
29 if (version is not null && version != "1" && version != "2")
30 throw new InvalidOperationException($"Unsupported transport format version '{version}'.");
31 var resources = chain.Element(ns + "transportResources")?.Elements(ns + "transportResource").ToArray() ?? [];
32 var containers = resources.SelectMany(r => r.Elements(ns + "lanes")).ToArray();
33 bool central = chain.Element(ns + "transportLanes") is not null || chain.Element(ns + "transportAssignments") is not null;
34 if (chain.Element(ns + "transportLanes")?.Elements(ns + "transportLane").Any(l => l.Attribute("leadTime") is not null) == true)
35 throw new InvalidOperationException("Central lanes cannot carry delays; put the delay on each assignment.");
36 if (containers.Length == 0)
37 {
38 if (version == "1" && central)
39 throw new InvalidOperationException("Version 1 cannot contain central transport data.");
40 if (version == "1") chain.SetAttributeValue("transportFormatVersion", "2");
41 return;
42 }
43 if (central || version == "2")
44 throw new InvalidOperationException("Mixed legacy and central transport representations cannot be merged implicitly.");
45
46 var entries = resources.SelectMany(resource => resource.Elements(ns + "lanes")
47 .SelectMany(c => c.Elements()).Select(lane =>
48 {
49 if (lane.Name != ns + "transportLane" || lane.Attributes().Any(a => a.Name != "leadTime") ||
50 lane.Elements().Any(e => e.Name != ns + "origin" && e.Name != ns + "destination"))
51 throw new InvalidOperationException("Unrecognized legacy lane data; migration would lose information.");
52 var origin = ReadWarehouse(lane, ns + "origin");
53 var destination = ReadWarehouse(lane, ns + "destination");
54 if (origin.Key == destination.Key) throw new InvalidOperationException("A legacy lane connects a warehouse to itself.");
55 int delay = ReadInteger(lane, "leadTime");
56 int resourceId = ReadInteger(resource, "id");
57 if (delay < 0 || resourceId < 0) throw new InvalidOperationException("Negative legacy delay or resource identifier.");
58 return new { ResourceId = resourceId, Delay = delay, Origin = origin.Element, Destination = destination.Element,
59 Key = (origin.Key.Kind, origin.Key.Id, destination.Key.Kind, destination.Key.Id) };
60 })).ToArray();
61
62 var lanes = new XElement(ns + "transportLanes");
63 var assignments = new XElement(ns + "transportAssignments");
64 int id = 0;
65 // Numeric tuple ordering is culture-independent and independent of resource/input ordering.
66 foreach (var group in entries.GroupBy(e => e.Key).OrderBy(g => g.Key))
67 {
68 id = checked(id + 1);
69 var first = group.First();
70 lanes.Add(new XElement(ns + "transportLane", new XAttribute("id", id),
71 new XElement(first.Origin), new XElement(first.Destination)));
72 foreach (var pair in group.GroupBy(e => e.ResourceId).OrderBy(g => g.Key))
73 {
74 int[] delays = pair.Select(e => e.Delay).Distinct().ToArray();
75 if (delays.Length != 1)
76 throw new InvalidOperationException($"Conflicting legacy delays for lane {group.Key}, resource {pair.Key}.");
77 assignments.Add(new XElement(ns + "transportAssignment", new XAttribute("laneId", id),
78 new XAttribute("transportResourceId", pair.Key), new XAttribute("leadTime", delays[0])));
79 }
80 }
81 // Commit only after every pair has passed conflict detection.
82 foreach (var container in containers) container.Remove();
83 chain.Add(lanes, assignments);
84 chain.SetAttributeValue("transportFormatVersion", "2");
85 }
86
87 private static ((int Kind, int Id) Key, XElement Element) ReadWarehouse(XElement lane, XName name)
88 {
89 var element = lane.Elements(name).SingleOrDefault()
90 ?? throw new InvalidOperationException($"Missing legacy {name.LocalName}.");
91 string? kindText = (string?)element.Attribute("kind");
92 if (!Enum.TryParse<WarehouseReferenceKind>(kindText, ignoreCase: true, out var kind) || !Enum.IsDefined(kind))
93 throw new InvalidOperationException($"Invalid warehouse kind '{kindText}'.");
94 int id = ReadInteger(element, "id");
95 if (id < 0) throw new InvalidOperationException("Negative warehouse identifier.");
96 return (((int)kind, id), element);
97 }
98
99 private static int ReadInteger(XElement element, string name) =>
100 int.TryParse((string?)element.Attribute(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)
101 ? value : throw new InvalidOperationException($"Missing or invalid integer '{name}' in legacy transport data.");
102}
static void Migrate(XElement root)
Promotes optional legacy generator fleet data without writing to the source file.
Lossless, in-memory migration of legacy nested transport lanes. Input files are never written.
static XDocument ReadAndMigrate(XmlReader reader)
Loads XML through the caller's secure reader and returns a migrated copy.
WarehouseReferenceKind
Identifies the type of warehouse referenced by a relationship.