using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class AchievementAssetImportSummary { public int RecordCount { get; init; } public int HeaderRecordCount { get; init; } public int DeletedCount { get; init; } public int InsertedCount { get; init; } } public static class AchievementAssetImporter { public static AchievementAssetImportSummary ValidateXml(string achieveXmlPath, string achieveHeaderXmlPath) { List records = LoadRecords(achieveXmlPath); int headerRecordCount = CountHeaderRecords(achieveHeaderXmlPath); return new AchievementAssetImportSummary { RecordCount = records.Count, HeaderRecordCount = headerRecordCount }; } public static AchievementAssetImportSummary ImportReplace(string connectionString, string achieveXmlPath, string achieveHeaderXmlPath) { List records = LoadRecords(achieveXmlPath); int headerRecordCount = CountHeaderRecords(achieveHeaderXmlPath); if (records.Count == 0) { throw new InvalidOperationException("Achieve.xml does not contain any AchieveSINFO records."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[Achievement];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[Achievement];"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Achievement] ON;"); using SqlCommand insertCommand = new(@" INSERT INTO [Asset].[Achievement] ([Id], [QuestId], [Type], [BuffId]) VALUES (@Id, @QuestId, @Type, @BuffId);", connection, transaction); AddParameter(insertCommand, "@Id"); AddParameter(insertCommand, "@QuestId"); AddParameter(insertCommand, "@Type"); AddParameter(insertCommand, "@BuffId"); int identity = 1; foreach (AchievementAssetRecord record in records) { insertCommand.Parameters["@Id"].Value = identity++; insertCommand.Parameters["@QuestId"].Value = record.QuestId; insertCommand.Parameters["@Type"].Value = record.Type; insertCommand.Parameters["@BuffId"].Value = record.BuffId; insertCommand.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Achievement] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[Achievement]', RESEED, {records.Count});"); transaction.Commit(); return new AchievementAssetImportSummary { RecordCount = records.Count, HeaderRecordCount = headerRecordCount, DeletedCount = deletedCount, InsertedCount = records.Count }; } catch { TryDisableIdentityInsert(connection, transaction); transaction.Rollback(); throw; } } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction) { try { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Achievement] OFF;"); } catch { // Best-effort cleanup before rollback. } } private static int ExecuteScalarInt(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); object? result = command.ExecuteScalar(); return Convert.ToInt32(result, CultureInfo.InvariantCulture); } private static void ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); command.ExecuteNonQuery(); } private static void AddParameter(SqlCommand command, string name) { command.Parameters.Add(new SqlParameter(name, DBNull.Value)); } private static List LoadRecords(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("Achieve.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "AchieveSINFOs") { throw new InvalidOperationException("Achieve.xml root node must be ."); } List records = new(); int rowIndex = 0; foreach (XElement achieveElement in root.Elements("AchieveSINFO")) { rowIndex++; string recordContext = BuildRecordContext(achieveElement, rowIndex); records.Add(new AchievementAssetRecord { RecordContext = recordContext, QuestId = ReadRequiredShort(achieveElement, "s_nQuestID", recordContext), Type = ReadRequiredInt(achieveElement, "s_nType", recordContext), BuffId = ReadRequiredInt(achieveElement, "s_nBuffCode", recordContext) }); } return records; } private static int CountHeaderRecords(string xmlPath) { if (!File.Exists(xmlPath)) { return 0; } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; return root?.Elements("sINFO").Count() ?? 0; } private static string BuildRecordContext(XElement achieveElement, int rowIndex) { string questId = achieveElement.Element("s_nQuestID")?.Value?.Trim() ?? "?"; string name = achieveElement.Element("s_szName")?.Value?.Trim() ?? string.Empty; if (string.IsNullOrWhiteSpace(name)) { return $"Achieve row {rowIndex} (QuestId={questId})"; } return $"Achieve row {rowIndex} (QuestId={questId}, Name={name})"; } 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 short ReadRequiredShort(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value < short.MinValue || value > short.MaxValue) { throw new InvalidOperationException($"{recordContext} has out-of-range short value in '{elementName}': '{value}'."); } return (short)value; } private sealed class AchievementAssetRecord { public string RecordContext { get; init; } = string.Empty; public short QuestId { get; init; } public int Type { get; init; } public int BuffId { get; init; } } } }