using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class EventAssetImportSummary { public int MonthlyRecordCount { get; init; } public int TimeRewardGroupCount { get; init; } public int IgnoredTimeRewardGroupCount { get; init; } public int TimeRewardRecordCount { get; init; } public int DeletedMonthlyCount { get; init; } public int InsertedMonthlyCount { get; init; } public int DeletedTimeRewardCount { get; init; } public int InsertedTimeRewardCount { get; init; } } public static class EventAssetImporter { private const int ServerTimeRewardGroupLimit = 4; public static EventAssetImportSummary ValidateXml(string monthlyEventXmlPath) { EventPackage package = LoadPackage(monthlyEventXmlPath); return new EventAssetImportSummary { MonthlyRecordCount = package.MonthlyRecords.Count, TimeRewardGroupCount = package.TimeRewardGroupCount, IgnoredTimeRewardGroupCount = package.IgnoredTimeRewardGroupCount, TimeRewardRecordCount = package.TimeRewardRecords.Count }; } public static EventAssetImportSummary ImportReplace(string connectionString, string monthlyEventXmlPath) { EventPackage package = LoadPackage(monthlyEventXmlPath); if (package.MonthlyRecords.Count == 0) { throw new InvalidOperationException("MonthlyEvent.xml does not contain any monthly reward rows."); } if (package.TimeRewardRecords.Count == 0) { throw new InvalidOperationException("Event.xml does not contain any server-supported time reward rows."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedMonthlyCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MonthlyEvent];"); int deletedTimeRewardCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[TimeEvent];"); ImportMonthlyEvents(connection, transaction, package.MonthlyRecords); ImportTimeRewards(connection, transaction, package.TimeRewardRecords); transaction.Commit(); return new EventAssetImportSummary { MonthlyRecordCount = package.MonthlyRecords.Count, TimeRewardGroupCount = package.TimeRewardGroupCount, IgnoredTimeRewardGroupCount = package.IgnoredTimeRewardGroupCount, TimeRewardRecordCount = package.TimeRewardRecords.Count, DeletedMonthlyCount = deletedMonthlyCount, InsertedMonthlyCount = package.MonthlyRecords.Count, DeletedTimeRewardCount = deletedTimeRewardCount, InsertedTimeRewardCount = package.TimeRewardRecords.Count }; } catch { TryDisableIdentityInsert(connection, transaction); transaction.Rollback(); throw; } } private static EventPackage LoadPackage(string monthlyEventXmlPath) { return new EventPackage { MonthlyRecords = LoadMonthlyRecords(monthlyEventXmlPath), TimeRewardRecords = LoadTimeRewardRecords( ResolveSiblingXmlPath(monthlyEventXmlPath, "Event.xml"), out int timeRewardGroupCount, out int ignoredTimeRewardGroupCount), TimeRewardGroupCount = timeRewardGroupCount, IgnoredTimeRewardGroupCount = ignoredTimeRewardGroupCount }; } private static List LoadMonthlyRecords(string xmlPath) { XElement root = LoadRequiredRoot(xmlPath, "MonthlyEvents"); 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? monthlyItemsElement = monthlyEvents[0].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) { records.Add(new MonthlyEventRecord { CurrentDay = currentDay, ItemId = itemId, ItemCount = itemCount }); } currentDay++; } return records; } private static List LoadTimeRewardRecords( string xmlPath, out int groupCount, out int ignoredGroupCount) { XElement root = LoadRequiredRoot(xmlPath, "Events"); List eventElements = root.Elements("Event") .OrderBy(x => ReadRequiredInt(x, "s_TableNo", "Event.xml Event block")) .ToList(); if (eventElements.Count == 0) { throw new InvalidOperationException("Event.xml does not contain any nodes."); } groupCount = eventElements.Count; ignoredGroupCount = Math.Max(0, eventElements.Count - ServerTimeRewardGroupLimit); List records = new(); for (int groupIndex = 0; groupIndex < Math.Min(ServerTimeRewardGroupLimit, eventElements.Count); groupIndex++) { XElement eventElement = eventElements[groupIndex]; int tableNo = ReadRequiredInt(eventElement, "s_TableNo", $"Event.xml reward group {groupIndex + 1}"); XElement? itemsElement = eventElement.Element("EventItems"); if (itemsElement == null) { throw new InvalidOperationException($"Event.xml reward group {tableNo} is missing the node."); } int rewardIndex = 1; foreach (XElement itemElement in itemsElement.Elements("EventItem")) { string recordContext = $"Event.xml reward group {tableNo}, item slot {rewardIndex}"; int itemId = ReadRequiredInt(itemElement, "ItemId", recordContext); int itemCount = ReadRequiredInt(itemElement, "ItemCount", recordContext); if (itemId != 0 && itemCount != 0) { records.Add(new TimeRewardRecord { CurrentReward = groupIndex, RewardIndex = rewardIndex, ItemId = itemId, ItemCount = itemCount }); } rewardIndex++; } } return records; } private static void ImportMonthlyEvents( SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { 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});"); } private static void ImportTimeRewards( SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[TimeEvent];"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[TimeEvent] ON;"); using SqlCommand insertCommand = new(@" INSERT INTO [Asset].[TimeEvent] ([Id], [CurrentReward], [ItemId], [ItemCount], [RewardIndex]) VALUES (@Id, @CurrentReward, @ItemId, @ItemCount, @RewardIndex);", connection, transaction); AddParameter(insertCommand, "@Id"); AddParameter(insertCommand, "@CurrentReward"); AddParameter(insertCommand, "@ItemId"); AddParameter(insertCommand, "@ItemCount"); AddParameter(insertCommand, "@RewardIndex"); int identity = 1; foreach (TimeRewardRecord record in records) { insertCommand.Parameters["@Id"].Value = identity++; insertCommand.Parameters["@CurrentReward"].Value = record.CurrentReward; insertCommand.Parameters["@ItemId"].Value = record.ItemId; insertCommand.Parameters["@ItemCount"].Value = record.ItemCount; insertCommand.Parameters["@RewardIndex"].Value = record.RewardIndex; insertCommand.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[TimeEvent] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[TimeEvent]', RESEED, {records.Count});"); } private static XElement LoadRequiredRoot(string xmlPath, string expectedRootName) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException($"{Path.GetFileName(xmlPath)} not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != expectedRootName) { throw new InvalidOperationException($"{Path.GetFileName(xmlPath)} root node must be <{expectedRootName}>."); } return root; } private static string ResolveSiblingXmlPath(string xmlPath, string siblingFileName) { string? directory = Path.GetDirectoryName(xmlPath); if (string.IsNullOrWhiteSpace(directory)) { throw new InvalidOperationException($"Could not resolve directory for {xmlPath}."); } return Path.Combine(directory, siblingFileName); } 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) { foreach (string tableName in new[] { "[Asset].[MonthlyEvent]", "[Asset].[TimeEvent]" }) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} OFF;"); } catch { // Best-effort cleanup before rollback. } } } private sealed class EventPackage { public List MonthlyRecords { get; init; } = new(); public List TimeRewardRecords { get; init; } = new(); public int TimeRewardGroupCount { get; init; } public int IgnoredTimeRewardGroupCount { get; init; } } private sealed class MonthlyEventRecord { public int CurrentDay { get; init; } public int ItemId { get; init; } public int ItemCount { get; init; } } private sealed class TimeRewardRecord { public int CurrentReward { get; init; } public int ItemId { get; init; } public int ItemCount { get; init; } public int RewardIndex { get; init; } } } }