using System.Data; using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed record QuestAssetImportSummary { public int QuestCount { get; init; } public int ConditionCount { get; init; } public int GoalCount { get; init; } public int RewardCount { get; init; } public int RewardObjectCount { get; init; } public int SupplyCount { get; init; } public int EventCount { get; init; } public int UnsupportedRewardTypeCount { get; init; } public int CurrentQuestCount { get; init; } public int CurrentConditionCount { get; init; } public int CurrentGoalCount { get; init; } public int CurrentRewardCount { get; init; } public int CurrentRewardObjectCount { get; init; } public int CurrentSupplyCount { get; init; } public int CurrentEventCount { get; init; } public int DeletedQuestCount { get; init; } public int DeletedConditionCount { get; init; } public int DeletedGoalCount { get; init; } public int DeletedRewardCount { get; init; } public int DeletedRewardObjectCount { get; init; } public int DeletedSupplyCount { get; init; } public int DeletedEventCount { get; init; } public int InsertedQuestCount { get; init; } public int InsertedConditionCount { get; init; } public int InsertedGoalCount { get; init; } public int InsertedRewardCount { get; init; } public int InsertedRewardObjectCount { get; init; } public int InsertedSupplyCount { get; init; } public int InsertedEventCount { get; init; } } public static class QuestAssetImporter { private static readonly string[] IdentityTables = { "[Asset].[QuestRewardObject]", "[Asset].[QuestReward]", "[Asset].[QuestSupply]", "[Asset].[QuestEvent]", "[Asset].[QuestGoal]", "[Asset].[QuestCondition]", "[Asset].[Quest]" }; public static QuestAssetImportSummary ValidateXml(string questXmlPath) { QuestPackage package = LoadPackage(questXmlPath); return CreateSummary(package); } public static QuestAssetImportSummary AssessDatabase(string connectionString, string questXmlPath) { QuestPackage package = LoadPackage(questXmlPath); using SqlConnection connection = new(connectionString); connection.Open(); return CreateSummary(package) with { CurrentQuestCount = CountTable(connection, null, "[Asset].[Quest]"), CurrentConditionCount = CountTable(connection, null, "[Asset].[QuestCondition]"), CurrentGoalCount = CountTable(connection, null, "[Asset].[QuestGoal]"), CurrentRewardCount = CountTable(connection, null, "[Asset].[QuestReward]"), CurrentRewardObjectCount = CountTable(connection, null, "[Asset].[QuestRewardObject]"), CurrentSupplyCount = CountTable(connection, null, "[Asset].[QuestSupply]"), CurrentEventCount = CountTable(connection, null, "[Asset].[QuestEvent]") }; } public static QuestAssetImportSummary ImportReplace(string connectionString, string questXmlPath) { QuestPackage package = LoadPackage(questXmlPath); if (package.Quests.Count == 0) { throw new InvalidOperationException("Quest.xml does not contain any quest rows."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { QuestAssetImportSummary before = CreateSummary(package) with { CurrentQuestCount = CountTable(connection, transaction, "[Asset].[Quest]"), CurrentConditionCount = CountTable(connection, transaction, "[Asset].[QuestCondition]"), CurrentGoalCount = CountTable(connection, transaction, "[Asset].[QuestGoal]"), CurrentRewardCount = CountTable(connection, transaction, "[Asset].[QuestReward]"), CurrentRewardObjectCount = CountTable(connection, transaction, "[Asset].[QuestRewardObject]"), CurrentSupplyCount = CountTable(connection, transaction, "[Asset].[QuestSupply]"), CurrentEventCount = CountTable(connection, transaction, "[Asset].[QuestEvent]") }; DeleteExistingRows(connection, transaction); InsertQuests(connection, transaction, package.Quests); InsertConditions(connection, transaction, package.Conditions); InsertGoals(connection, transaction, package.Goals); InsertRewards(connection, transaction, package.Rewards); InsertRewardObjects(connection, transaction, package.RewardObjects); InsertSupplies(connection, transaction, package.Supplies); InsertEvents(connection, transaction, package.Events); Reseed(connection, transaction, "[Asset].[Quest]", package.Quests.Count); Reseed(connection, transaction, "[Asset].[QuestCondition]", package.Conditions.Count); Reseed(connection, transaction, "[Asset].[QuestGoal]", package.Goals.Count); Reseed(connection, transaction, "[Asset].[QuestReward]", package.Rewards.Count); Reseed(connection, transaction, "[Asset].[QuestRewardObject]", package.RewardObjects.Count); Reseed(connection, transaction, "[Asset].[QuestSupply]", package.Supplies.Count); Reseed(connection, transaction, "[Asset].[QuestEvent]", package.Events.Count); transaction.Commit(); return before with { DeletedQuestCount = before.CurrentQuestCount, DeletedConditionCount = before.CurrentConditionCount, DeletedGoalCount = before.CurrentGoalCount, DeletedRewardCount = before.CurrentRewardCount, DeletedRewardObjectCount = before.CurrentRewardObjectCount, DeletedSupplyCount = before.CurrentSupplyCount, DeletedEventCount = before.CurrentEventCount, InsertedQuestCount = package.Quests.Count, InsertedConditionCount = package.Conditions.Count, InsertedGoalCount = package.Goals.Count, InsertedRewardCount = package.Rewards.Count, InsertedRewardObjectCount = package.RewardObjects.Count, InsertedSupplyCount = package.Supplies.Count, InsertedEventCount = package.Events.Count }; } catch { TryDisableIdentityInsert(connection, transaction); transaction.Rollback(); throw; } } private static QuestAssetImportSummary CreateSummary(QuestPackage package) { return new QuestAssetImportSummary { QuestCount = package.Quests.Count, ConditionCount = package.Conditions.Count, GoalCount = package.Goals.Count, RewardCount = package.Rewards.Count, RewardObjectCount = package.RewardObjects.Count, SupplyCount = package.Supplies.Count, EventCount = package.Events.Count, UnsupportedRewardTypeCount = package.Rewards.Count(x => x.RewardType is < 0 or > 2) }; } private static QuestPackage LoadPackage(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("Quest.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "QuestTable") { throw new InvalidOperationException("Quest.xml root node must be ."); } QuestPackage package = new(); HashSet questIds = new(); long questIdentity = 1; long conditionIdentity = 1; long goalIdentity = 1; long rewardIdentity = 1; long rewardObjectIdentity = 1; long supplyIdentity = 1; long eventIdentity = 1; int rowIndex = 0; foreach (XElement questElement in root.Elements("Quest")) { rowIndex++; string context = BuildContext(questElement, rowIndex); int questId = ReadRequiredInt(questElement, "UniqID", context); if (questId <= 0) { throw new InvalidOperationException($"{context} has invalid UniqID '{questId}'."); } if (!questIds.Add(questId)) { throw new InvalidOperationException($"{context} has duplicate UniqID '{questId}'."); } int questType = ReadRequiredInt(questElement, "QuestType", context); if (questType is < 0 or > 9) { throw new InvalidOperationException($"{context} has out-of-range QuestType '{questType}'."); } QuestRecord quest = new() { Id = questIdentity++, QuestId = questId, QuestType = questType, TargetType = ReadRequiredInt(questElement, "QuestTarget", context), TargetValue = ReadRequiredInt(questElement, "QuestTargetValue1", context) }; package.Quests.Add(quest); XElement? suppliesElement = questElement.Element("ApplyRequites"); if (suppliesElement != null) { foreach (XElement supplyElement in suppliesElement.Elements("ApplyRequite")) { string supplyContext = $"{context} ApplyRequite {package.Supplies.Count + 1}"; _ = ReadRequiredInt(supplyElement, "Type", supplyContext); package.Supplies.Add(new QuestSupplyRecord { Id = supplyIdentity++, ItemId = ReadRequiredInt(supplyElement, "TypeID", supplyContext), Amount = ReadRequiredInt(supplyElement, "TypeCount", supplyContext), QuestId = quest.Id }); } } XElement? conditionsElement = questElement.Element("PreRequires"); if (conditionsElement != null) { foreach (XElement conditionElement in conditionsElement.Elements("PreRequire")) { string conditionContext = $"{context} PreRequire {package.Conditions.Count + 1}"; package.Conditions.Add(new QuestConditionRecord { Id = conditionIdentity++, ConditionType = ReadRequiredInt(conditionElement, "Type", conditionContext), ConditionId = ReadRequiredInt(conditionElement, "TypeID", conditionContext), ConditionCount = ReadRequiredInt(conditionElement, "TypeCount", conditionContext), QuestId = quest.Id }); } } XElement? goalsElement = questElement.Element("CompRequires"); if (goalsElement != null) { foreach (XElement goalElement in goalsElement.Elements("CompRequire")) { string goalContext = $"{context} CompRequire {package.Goals.Count + 1}"; int goalType = ReadRequiredInt(goalElement, "Type", goalContext); if (goalType is < 0 or > 10) { throw new InvalidOperationException($"{goalContext} has out-of-range GoalType '{goalType}'."); } package.Goals.Add(new QuestGoalRecord { Id = goalIdentity++, GoalType = goalType, GoalId = ReadRequiredInt(goalElement, "TypeID", goalContext), GoalAmount = ReadRequiredInt(goalElement, "TypeCount", goalContext), CurTypeCount = ReadRequiredInt(goalElement, "TargetID", goalContext), SubValue = ReadRequiredInt(goalElement, "SubValue1", goalContext), SubValueTwo = ReadRequiredInt(goalElement, "SubValue2", goalContext), QuestId = quest.Id }); } } XElement? rewardsElement = questElement.Element("Requites"); if (rewardsElement != null) { foreach (XElement rewardElement in rewardsElement.Elements("Requite")) { string rewardContext = $"{context} Requite {package.Rewards.Count + 1}"; int rewardType = ReadRequiredInt(rewardElement, "Type", rewardContext); int rewardValue = ReadRequiredInt(rewardElement, "TypeID", rewardContext); int rewardCount = ReadRequiredInt(rewardElement, "TypeCount", rewardContext); long currentRewardId = rewardIdentity++; package.Rewards.Add(new QuestRewardRecord { Id = currentRewardId, Reward = ReadRequiredInt(rewardElement, "Method", rewardContext), RewardType = rewardType, QuestId = quest.Id }); package.RewardObjects.Add(new QuestRewardObjectRecord { Id = rewardObjectIdentity++, Reward = rewardType is 0 or 1 ? rewardCount : rewardValue, Amount = rewardType is 0 or 1 ? rewardValue : rewardCount, QuestRewardId = currentRewardId }); } } XElement? eventsElement = questElement.Element("Events"); if (eventsElement != null) { foreach (XElement eventElement in eventsElement.Elements("EventValue")) { package.Events.Add(new QuestEventRecord { Id = eventIdentity++, EventId = ParseInt(eventElement, $"{context} EventValue {package.Events.Count + 1}"), QuestId = quest.Id }); } } } return package; } private static void DeleteExistingRows(SqlConnection connection, SqlTransaction transaction) { ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[QuestRewardObject];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[QuestReward];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[QuestSupply];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[QuestEvent];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[QuestGoal];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[QuestCondition];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[Quest];"); } private static void InsertQuests(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Quest] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[Quest] ([Id], [QuestId], [QuestType], [TargetType], [TargetValue]) VALUES (@Id, @QuestId, @QuestType, @TargetType, @TargetValue);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@QuestId"); AddInt(command, "@QuestType"); AddInt(command, "@TargetType"); AddInt(command, "@TargetValue"); foreach (QuestRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@QuestId"].Value = record.QuestId; command.Parameters["@QuestType"].Value = record.QuestType; command.Parameters["@TargetType"].Value = record.TargetType; command.Parameters["@TargetValue"].Value = record.TargetValue; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Quest] OFF;"); } private static void InsertConditions(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { if (records.Count == 0) { return; } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestCondition] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[QuestCondition] ([Id], [ConditionType], [ConditionId], [ConditionCount], [QuestId]) VALUES (@Id, @ConditionType, @ConditionId, @ConditionCount, @QuestId);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@ConditionType"); AddInt(command, "@ConditionId"); AddInt(command, "@ConditionCount"); AddBigInt(command, "@QuestId"); foreach (QuestConditionRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@ConditionType"].Value = record.ConditionType; command.Parameters["@ConditionId"].Value = record.ConditionId; command.Parameters["@ConditionCount"].Value = record.ConditionCount; command.Parameters["@QuestId"].Value = record.QuestId; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestCondition] OFF;"); } private static void InsertGoals(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { if (records.Count == 0) { return; } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestGoal] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[QuestGoal] ([Id], [GoalType], [GoalId], [GoalAmount], [CurTypeCount], [SubValue], [SubValueTwo], [QuestId]) VALUES (@Id, @GoalType, @GoalId, @GoalAmount, @CurTypeCount, @SubValue, @SubValueTwo, @QuestId);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@GoalType"); AddInt(command, "@GoalId"); AddInt(command, "@GoalAmount"); AddInt(command, "@CurTypeCount"); AddInt(command, "@SubValue"); AddInt(command, "@SubValueTwo"); AddBigInt(command, "@QuestId"); foreach (QuestGoalRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@GoalType"].Value = record.GoalType; command.Parameters["@GoalId"].Value = record.GoalId; command.Parameters["@GoalAmount"].Value = record.GoalAmount; command.Parameters["@CurTypeCount"].Value = record.CurTypeCount; command.Parameters["@SubValue"].Value = record.SubValue; command.Parameters["@SubValueTwo"].Value = record.SubValueTwo; command.Parameters["@QuestId"].Value = record.QuestId; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestGoal] OFF;"); } private static void InsertRewards(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { if (records.Count == 0) { return; } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestReward] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[QuestReward] ([Id], [Reward], [RewardType], [QuestId]) VALUES (@Id, @Reward, @RewardType, @QuestId);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@Reward"); AddInt(command, "@RewardType"); AddBigInt(command, "@QuestId"); foreach (QuestRewardRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@Reward"].Value = record.Reward; command.Parameters["@RewardType"].Value = record.RewardType; command.Parameters["@QuestId"].Value = record.QuestId; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestReward] OFF;"); } private static void InsertRewardObjects(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { if (records.Count == 0) { return; } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestRewardObject] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[QuestRewardObject] ([Id], [Reward], [Amount], [QuestRewardId]) VALUES (@Id, @Reward, @Amount, @QuestRewardId);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@Reward"); AddInt(command, "@Amount"); AddBigInt(command, "@QuestRewardId"); foreach (QuestRewardObjectRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@Reward"].Value = record.Reward; command.Parameters["@Amount"].Value = record.Amount; command.Parameters["@QuestRewardId"].Value = record.QuestRewardId; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestRewardObject] OFF;"); } private static void InsertSupplies(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { if (records.Count == 0) { return; } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestSupply] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[QuestSupply] ([Id], [ItemId], [Amount], [QuestId]) VALUES (@Id, @ItemId, @Amount, @QuestId);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@ItemId"); AddInt(command, "@Amount"); AddBigInt(command, "@QuestId"); foreach (QuestSupplyRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@ItemId"].Value = record.ItemId; command.Parameters["@Amount"].Value = record.Amount; command.Parameters["@QuestId"].Value = record.QuestId; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestSupply] OFF;"); } private static void InsertEvents(SqlConnection connection, SqlTransaction transaction, IReadOnlyList records) { if (records.Count == 0) { return; } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestEvent] ON;"); using SqlCommand command = new(@" INSERT INTO [Asset].[QuestEvent] ([Id], [EventId], [QuestId]) VALUES (@Id, @EventId, @QuestId);", connection, transaction); AddBigInt(command, "@Id"); AddInt(command, "@EventId"); AddBigInt(command, "@QuestId"); foreach (QuestEventRecord record in records) { command.Parameters["@Id"].Value = record.Id; command.Parameters["@EventId"].Value = record.EventId; command.Parameters["@QuestId"].Value = record.QuestId; command.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[QuestEvent] OFF;"); } private static string BuildContext(XElement questElement, int rowIndex) { string questId = questElement.Element("UniqID")?.Value?.Trim() ?? "?"; string title = questElement.Element("TitleText")?.Value?.Trim() ?? string.Empty; return string.IsNullOrWhiteSpace(title) ? $"Quest row {rowIndex} (UniqID={questId})" : $"Quest row {rowIndex} (UniqID={questId}, Title={title})"; } 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}'."); } return ParseInt(element, $"{recordContext} field '{elementName}'"); } private static int ParseInt(XElement element, string recordContext) { if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value: '{element.Value}'."); } return value; } private static int CountTable(SqlConnection connection, SqlTransaction? transaction, string tableName) { using SqlCommand command = new($"SELECT COUNT(*) FROM {tableName};", 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 Reseed(SqlConnection connection, SqlTransaction transaction, string tableName, int count) { ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'{tableName}', RESEED, {count});"); } private static void AddInt(SqlCommand command, string name) { command.Parameters.Add(name, SqlDbType.Int); } private static void AddBigInt(SqlCommand command, string name) { command.Parameters.Add(name, SqlDbType.BigInt); } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction) { foreach (string tableName in IdentityTables) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} OFF;"); } catch { // Best-effort cleanup before rollback. } } } private sealed class QuestPackage { public List Quests { get; } = new(); public List Conditions { get; } = new(); public List Goals { get; } = new(); public List Rewards { get; } = new(); public List RewardObjects { get; } = new(); public List Supplies { get; } = new(); public List Events { get; } = new(); } private sealed class QuestRecord { public long Id { get; init; } public int QuestId { get; init; } public int QuestType { get; init; } public int TargetType { get; init; } public int TargetValue { get; init; } } private sealed class QuestConditionRecord { public long Id { get; init; } public int ConditionType { get; init; } public int ConditionId { get; init; } public int ConditionCount { get; init; } public long QuestId { get; init; } } private sealed class QuestGoalRecord { public long Id { get; init; } public int GoalType { get; init; } public int GoalId { get; init; } public int GoalAmount { get; init; } public int CurTypeCount { get; init; } public int SubValue { get; init; } public int SubValueTwo { get; init; } public long QuestId { get; init; } } private sealed class QuestRewardRecord { public long Id { get; init; } public int Reward { get; init; } public int RewardType { get; init; } public long QuestId { get; init; } } private sealed class QuestRewardObjectRecord { public long Id { get; init; } public int Reward { get; init; } public int Amount { get; init; } public long QuestRewardId { get; init; } } private sealed class QuestSupplyRecord { public long Id { get; init; } public int ItemId { get; init; } public int Amount { get; init; } public long QuestId { get; init; } } private sealed class QuestEventRecord { public long Id { get; init; } public int EventId { get; init; } public long QuestId { get; init; } } } }