using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class MonthlyEventImportSummary { public int RecordCount { get; init; } public int DeletedCount { get; init; } public int InsertedCount { get; init; } } public static class MonthlyEventAssetImporter { public static MonthlyEventImportSummary ValidateXml(string xmlPath) { List records = LoadRecords(xmlPath); return new MonthlyEventImportSummary { RecordCount = records.Count }; } public static MonthlyEventImportSummary ImportReplace(string connectionString, string xmlPath) { List records = LoadRecords(xmlPath); if (records.Count == 0) { throw new InvalidOperationException("MonthlyEvent.xml does not contain any monthly reward rows."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MonthlyEvent];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[MonthlyEvent];"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[MonthlyEvent] ON;"); using SqlCommand insertCommand = new(@" INSERT INTO [Asset].[MonthlyEvent] ([Id], [CurrentDay], [ItemId], [ItemCount]) VALUES (@Id, @CurrentDay, @ItemId, @ItemCount);", connection, transaction); AddParameter(insertCommand, "@Id"); AddParameter(insertCommand, "@CurrentDay"); AddParameter(insertCommand, "@ItemId"); AddParameter(insertCommand, "@ItemCount"); int identity = 1; foreach (MonthlyEventRecord record in records) { insertCommand.Parameters["@Id"].Value = identity++; insertCommand.Parameters["@CurrentDay"].Value = record.CurrentDay; insertCommand.Parameters["@ItemId"].Value = record.ItemId; insertCommand.Parameters["@ItemCount"].Value = record.ItemCount; insertCommand.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[MonthlyEvent] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[MonthlyEvent]', RESEED, {records.Count});"); transaction.Commit(); return new MonthlyEventImportSummary { RecordCount = records.Count, DeletedCount = deletedCount, InsertedCount = records.Count }; } catch { TryDisableIdentityInsert(connection, transaction); transaction.Rollback(); throw; } } private static List LoadRecords(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("MonthlyEvent.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "MonthlyEvents") { throw new InvalidOperationException("MonthlyEvent.xml root node must be ."); } List monthlyEvents = root.Elements("MonthlyEvent").ToList(); if (monthlyEvents.Count == 0) { throw new InvalidOperationException("MonthlyEvent.xml does not contain any nodes."); } if (monthlyEvents.Count > 1) { throw new InvalidOperationException("Current server MonthlyEvent schema expects a single monthly reward sequence, but MonthlyEvent.xml contains multiple blocks."); } XElement monthlyEvent = monthlyEvents[0]; XElement? monthlyItemsElement = monthlyEvent.Element("MonthlyItems"); if (monthlyItemsElement == null) { throw new InvalidOperationException("MonthlyEvent.xml is missing the node."); } List records = new(); int currentDay = 1; foreach (XElement itemElement in monthlyItemsElement.Elements("MonthlyItem")) { string recordContext = $"MonthlyEvent day {currentDay}"; int itemId = ReadRequiredInt(itemElement, "ItemId", recordContext); int itemCount = ReadRequiredInt(itemElement, "ItemCount", recordContext); if (itemId == 0 || itemCount == 0) { currentDay++; continue; } records.Add(new MonthlyEventRecord { CurrentDay = currentDay, ItemId = itemId, ItemCount = itemCount }); currentDay++; } return records; } 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 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 void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction) { try { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[MonthlyEvent] OFF;"); } catch { // Best-effort cleanup before rollback. } } private sealed class MonthlyEventRecord { public int CurrentDay { get; init; } public int ItemId { get; init; } public int ItemCount { get; init; } } } }