using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class MapAssetImportSummary { public int RecordCount { get; init; } public int DeletedCount { get; init; } public int InsertedCount { get; init; } } public static class MapAssetImporter { public static MapAssetImportSummary ValidateXml(string mapListXmlPath) { List records = LoadRecords(mapListXmlPath); return new MapAssetImportSummary { RecordCount = records.Count }; } public static MapAssetImportSummary ImportReplace(string connectionString, string mapListXmlPath) { List records = LoadRecords(mapListXmlPath); if (records.Count == 0) { throw new InvalidOperationException("MapList.xml does not contain any map rows."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[Map];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[Map];"); InsertRecords(connection, transaction, records); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[Map]', RESEED, {records.Count});"); transaction.Commit(); return new MapAssetImportSummary { RecordCount = records.Count, DeletedCount = deletedCount, InsertedCount = records.Count }; } catch { TryDisableIdentityInsert(connection, transaction, "[Asset].[Map]"); transaction.Rollback(); throw; } } private static List LoadRecords(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("MapList.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "MapList") { throw new InvalidOperationException("MapList.xml root node must be ."); } XElement? mapsElement = root.Element("Maps"); if (mapsElement == null) { throw new InvalidOperationException("MapList.xml is missing the node."); } List records = new(); HashSet mapIds = new(); int identity = 1; int rowIndex = 0; foreach (XElement mapElement in mapsElement.Elements("Map")) { rowIndex++; string rowContext = $"Map row {rowIndex}"; int mapId = ReadRequiredInt(mapElement, "s_dwMapID", rowContext); string name = ReadRequiredString(mapElement, "s_szMapDiscript", rowContext); string internalName = ReadRequiredString(mapElement, "s_cMapName", rowContext); int regionIndex = ReadRequiredInt(mapElement, "s_nMapRegionID", rowContext); if (!mapIds.Add(mapId)) { throw new InvalidOperationException($"{rowContext} has duplicate MapId '{mapId}'."); } if (string.IsNullOrWhiteSpace(name)) { name = internalName; } if (string.IsNullOrWhiteSpace(name)) { throw new InvalidOperationException($"{rowContext} has empty map names in both 's_szMapDiscript' and 's_cMapName'."); } if (name.Length > 200) { throw new InvalidOperationException($"{rowContext} has Name length {name.Length}, which exceeds Asset.Map.Name max length 200."); } if (regionIndex is < byte.MinValue or > byte.MaxValue) { throw new InvalidOperationException($"{rowContext} has out-of-range byte value in 's_nMapRegionID': '{regionIndex}'."); } records.Add(new MapRecord { Id = identity++, MapId = mapId, Name = name, RegionIndex = (byte)regionIndex, ResurrectionMapId = ReadRequiredInt(mapElement, "s_dwResurrectionMapID", rowContext), XgConsumeType = ReadRequiredInt(mapElement, "s_bXgConsumeType", rowContext), BattleTagUse = ReadRequiredInt(mapElement, "s_bBattleTagUse", rowContext), Type = 0 }); } return records; } private static void InsertRecords(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Map] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[Map] ([Id], [MapId], [Name], [RegionIndex], [ResurrectionMapID], [XgConsumeType], [BattleTagUse], [Type]) VALUES (@Id, @MapId, @Name, @RegionIndex, @ResurrectionMapID, @XgConsumeType, @BattleTagUse, @Type);", connection, transaction); command.Parameters.Add("@Id", System.Data.SqlDbType.BigInt); command.Parameters.Add("@MapId", System.Data.SqlDbType.Int); command.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 200); command.Parameters.Add("@RegionIndex", System.Data.SqlDbType.TinyInt); command.Parameters.Add("@ResurrectionMapID", System.Data.SqlDbType.Int); command.Parameters.Add("@XgConsumeType", System.Data.SqlDbType.Int); command.Parameters.Add("@BattleTagUse", System.Data.SqlDbType.Int); command.Parameters.Add("@Type", System.Data.SqlDbType.Int); foreach (MapRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@MapId"].Value = record.MapId; command.Parameters["@Name"].Value = record.Name; command.Parameters["@RegionIndex"].Value = record.RegionIndex; command.Parameters["@ResurrectionMapID"].Value = record.ResurrectionMapId; command.Parameters["@XgConsumeType"].Value = record.XgConsumeType; command.Parameters["@BattleTagUse"].Value = record.BattleTagUse; command.Parameters["@Type"].Value = record.Type; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Map] OFF;"); } private static int ReadRequiredInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value in '{elementName}': '{element.Value}'."); } return value; } private static string ReadRequiredString(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } return element.Value; } private static int ExecuteScalarInt(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); object? value = command.ExecuteScalar(); return Convert.ToInt32(value, CultureInfo.InvariantCulture); } private static void ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); command.ExecuteNonQuery(); } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction, string tableName) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} OFF;"); } catch { // Best-effort cleanup before the transaction rollback. } } private sealed class MapRecord { public long Id { get; init; } public int MapId { get; init; } public string Name { get; init; } = string.Empty; public byte RegionIndex { get; init; } public int ResurrectionMapId { get; init; } public int XgConsumeType { get; init; } public int BattleTagUse { get; init; } public int Type { get; init; } } } }