using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class MonsterPackageImportSummary { public int MonsterRecordCount { get; init; } public int MonsterSkillRecordCount { get; init; } public int DeletedMonsterBaseInfoCount { get; init; } public int DeletedMonsterSkillCount { get; init; } public int DeletedMonsterSkillInfoCount { get; init; } public int InsertedMonsterBaseInfoCount { get; init; } public int InsertedMonsterSkillCount { get; init; } public int InsertedMonsterSkillInfoCount { get; init; } } public static class MonsterPackageImporter { public static MonsterPackageImportSummary ValidateXml(string monsterXmlPath, string monsterSkillXmlPath) { List monsters = LoadMonsterBaseInfoRecords(monsterXmlPath); List skills = LoadMonsterSkillRecords(monsterSkillXmlPath); return new MonsterPackageImportSummary { MonsterRecordCount = monsters.Count, MonsterSkillRecordCount = skills.Count }; } public static MonsterPackageImportSummary ImportReplace(string connectionString, string monsterXmlPath, string monsterSkillXmlPath) { List monsters = LoadMonsterBaseInfoRecords(monsterXmlPath); List skills = LoadMonsterSkillRecords(monsterSkillXmlPath); if (monsters.Count == 0) { throw new InvalidOperationException("Monster.xml does not contain any Monster records."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedMonsterBaseInfoCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MonsterBaseInfo];"); int deletedMonsterSkillCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MonsterSkill];"); int deletedMonsterSkillInfoCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[MonsterSkillInfo];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[MonsterSkillInfo];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[MonsterSkill];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[MonsterBaseInfo];"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[MonsterBaseInfo] ON;"); using SqlCommand monsterCommand = new(@" INSERT INTO [Asset].[MonsterBaseInfo] ([Id], [Type], [Model], [Name], [Level], [ViewRange], [HuntRange], [ReactionType], [Attribute], [Element], [Family1], [Family2], [Family3], [ASValue], [ARValue], [ATValue], [BLValue], [CTValue], [DEValue], [DSValue], [EVValue], [HPValue], [HTValue], [MSValue], [WSValue], [Class]) VALUES (@Id, @Type, @Model, @Name, @Level, @ViewRange, @HuntRange, @ReactionType, @Attribute, @Element, @Family1, @Family2, @Family3, @ASValue, @ARValue, @ATValue, @BLValue, @CTValue, @DEValue, @DSValue, @EVValue, @HPValue, @HTValue, @MSValue, @WSValue, @Class);", connection, transaction); AddParameter(monsterCommand, "@Id"); AddParameter(monsterCommand, "@Type"); AddParameter(monsterCommand, "@Model"); AddParameter(monsterCommand, "@Name"); AddParameter(monsterCommand, "@Level"); AddParameter(monsterCommand, "@ViewRange"); AddParameter(monsterCommand, "@HuntRange"); AddParameter(monsterCommand, "@ReactionType"); AddParameter(monsterCommand, "@Attribute"); AddParameter(monsterCommand, "@Element"); AddParameter(monsterCommand, "@Family1"); AddParameter(monsterCommand, "@Family2"); AddParameter(monsterCommand, "@Family3"); AddParameter(monsterCommand, "@ASValue"); AddParameter(monsterCommand, "@ARValue"); AddParameter(monsterCommand, "@ATValue"); AddParameter(monsterCommand, "@BLValue"); AddParameter(monsterCommand, "@CTValue"); AddParameter(monsterCommand, "@DEValue"); AddParameter(monsterCommand, "@DSValue"); AddParameter(monsterCommand, "@EVValue"); AddParameter(monsterCommand, "@HPValue"); AddParameter(monsterCommand, "@HTValue"); AddParameter(monsterCommand, "@MSValue"); AddParameter(monsterCommand, "@WSValue"); AddParameter(monsterCommand, "@Class"); foreach (MonsterBaseInfoRecord record in monsters) { monsterCommand.Parameters["@Id"].Value = record.Id; monsterCommand.Parameters["@Type"].Value = record.Type; monsterCommand.Parameters["@Model"].Value = record.Model; monsterCommand.Parameters["@Name"].Value = record.Name; monsterCommand.Parameters["@Level"].Value = record.Level; monsterCommand.Parameters["@ViewRange"].Value = record.ViewRange; monsterCommand.Parameters["@HuntRange"].Value = record.HuntRange; monsterCommand.Parameters["@ReactionType"].Value = record.ReactionType; monsterCommand.Parameters["@Attribute"].Value = record.Attribute; monsterCommand.Parameters["@Element"].Value = record.Element; monsterCommand.Parameters["@Family1"].Value = record.Family1; monsterCommand.Parameters["@Family2"].Value = record.Family2; monsterCommand.Parameters["@Family3"].Value = record.Family3; monsterCommand.Parameters["@ASValue"].Value = record.ASValue; monsterCommand.Parameters["@ARValue"].Value = record.ARValue; monsterCommand.Parameters["@ATValue"].Value = record.ATValue; monsterCommand.Parameters["@BLValue"].Value = record.BLValue; monsterCommand.Parameters["@CTValue"].Value = record.CTValue; monsterCommand.Parameters["@DEValue"].Value = record.DEValue; monsterCommand.Parameters["@DSValue"].Value = record.DSValue; monsterCommand.Parameters["@EVValue"].Value = record.EVValue; monsterCommand.Parameters["@HPValue"].Value = record.HPValue; monsterCommand.Parameters["@HTValue"].Value = record.HTValue; monsterCommand.Parameters["@MSValue"].Value = record.MSValue; monsterCommand.Parameters["@WSValue"].Value = record.WSValue; monsterCommand.Parameters["@Class"].Value = record.Class; monsterCommand.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[MonsterBaseInfo] OFF;"); ExecuteNonQuery(connection, transaction, "DBCC CHECKIDENT(N'[Asset].[MonsterSkill]', RESEED, 0);"); using SqlCommand monsterSkillCommand = new(@" INSERT INTO [Asset].[MonsterSkill] ([Type], [SkillId]) VALUES (@Type, @SkillId);", connection, transaction); AddParameter(monsterSkillCommand, "@Type"); AddParameter(monsterSkillCommand, "@SkillId"); ExecuteNonQuery(connection, transaction, "DBCC CHECKIDENT(N'[Asset].[MonsterSkillInfo]', RESEED, 0);"); using SqlCommand monsterSkillInfoCommand = new(@" INSERT INTO [Asset].[MonsterSkillInfo] ([SkillId], [MinValue], [MaxValue], [CastingTime], [Cooldown], [TargetCount], [TargetMin], [TargetMax], [UseTerms], [RangeId], [AnimationDelay], [ActiveType], [SkillType], [NoticeTime], [Type]) VALUES (@SkillId, @MinValue, @MaxValue, @CastingTime, @Cooldown, @TargetCount, @TargetMin, @TargetMax, @UseTerms, @RangeId, @AnimationDelay, @ActiveType, @SkillType, @NoticeTime, @Type);", connection, transaction); AddParameter(monsterSkillInfoCommand, "@SkillId"); AddParameter(monsterSkillInfoCommand, "@MinValue"); AddParameter(monsterSkillInfoCommand, "@MaxValue"); AddParameter(monsterSkillInfoCommand, "@CastingTime"); AddParameter(monsterSkillInfoCommand, "@Cooldown"); AddParameter(monsterSkillInfoCommand, "@TargetCount"); AddParameter(monsterSkillInfoCommand, "@TargetMin"); AddParameter(monsterSkillInfoCommand, "@TargetMax"); AddParameter(monsterSkillInfoCommand, "@UseTerms"); AddParameter(monsterSkillInfoCommand, "@RangeId"); AddParameter(monsterSkillInfoCommand, "@AnimationDelay"); AddParameter(monsterSkillInfoCommand, "@ActiveType"); AddParameter(monsterSkillInfoCommand, "@SkillType"); AddParameter(monsterSkillInfoCommand, "@NoticeTime"); AddParameter(monsterSkillInfoCommand, "@Type"); foreach (MonsterSkillRecord record in skills) { monsterSkillCommand.Parameters["@Type"].Value = record.Type; monsterSkillCommand.Parameters["@SkillId"].Value = record.SkillId; monsterSkillCommand.ExecuteNonQuery(); monsterSkillInfoCommand.Parameters["@SkillId"].Value = record.SkillId; monsterSkillInfoCommand.Parameters["@MinValue"].Value = record.MinValue; monsterSkillInfoCommand.Parameters["@MaxValue"].Value = record.MaxValue; monsterSkillInfoCommand.Parameters["@CastingTime"].Value = record.CastingTime; monsterSkillInfoCommand.Parameters["@Cooldown"].Value = record.Cooldown; monsterSkillInfoCommand.Parameters["@TargetCount"].Value = record.TargetCount; monsterSkillInfoCommand.Parameters["@TargetMin"].Value = record.TargetMin; monsterSkillInfoCommand.Parameters["@TargetMax"].Value = record.TargetMax; monsterSkillInfoCommand.Parameters["@UseTerms"].Value = record.UseTerms; monsterSkillInfoCommand.Parameters["@RangeId"].Value = record.RangeId; monsterSkillInfoCommand.Parameters["@AnimationDelay"].Value = record.AnimationDelay; monsterSkillInfoCommand.Parameters["@ActiveType"].Value = record.ActiveType; monsterSkillInfoCommand.Parameters["@SkillType"].Value = record.SkillType; monsterSkillInfoCommand.Parameters["@NoticeTime"].Value = record.NoticeTime; monsterSkillInfoCommand.Parameters["@Type"].Value = record.Type; monsterSkillInfoCommand.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[MonsterBaseInfo]', RESEED, {monsters.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[MonsterSkill]', RESEED, {skills.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[MonsterSkillInfo]', RESEED, {skills.Count});"); transaction.Commit(); return new MonsterPackageImportSummary { MonsterRecordCount = monsters.Count, MonsterSkillRecordCount = skills.Count, DeletedMonsterBaseInfoCount = deletedMonsterBaseInfoCount, DeletedMonsterSkillCount = deletedMonsterSkillCount, DeletedMonsterSkillInfoCount = deletedMonsterSkillInfoCount, InsertedMonsterBaseInfoCount = monsters.Count, InsertedMonsterSkillCount = skills.Count, InsertedMonsterSkillInfoCount = skills.Count }; } catch { TryDisableIdentityInsert(connection, transaction, "[Asset].[MonsterBaseInfo]"); transaction.Rollback(); throw; } } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction, string tableName) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} 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 LoadMonsterBaseInfoRecords(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("Monster.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "MonsterList") { throw new InvalidOperationException("Monster.xml root node must be ."); } List records = new(); int rowIndex = 0; foreach (XElement monsterElement in root.Elements("Monster")) { rowIndex++; string recordContext = BuildMonsterRecordContext(monsterElement, rowIndex); int type = ReadRequiredInt(monsterElement, "MonsterID", recordContext); records.Add(new MonsterBaseInfoRecord { Id = type, Type = type, Model = ReadRequiredInt(monsterElement, "ModelID", recordContext), Name = ReadNameWithFallback(monsterElement, recordContext, type, 50), Level = ReadRequiredTinyInt(monsterElement, "Level", recordContext), ViewRange = ReadOptionalInt(monsterElement, "Sight"), HuntRange = ReadOptionalInt(monsterElement, "HuntRange"), ReactionType = 1, Attribute = 0, Element = 0, Family1 = 0, Family2 = 0, Family3 = 0, ASValue = ReadOptionalInt(monsterElement, "AttackSpeed"), ARValue = ReadOptionalInt(monsterElement, "AttackRange"), ATValue = ReadOptionalInt(monsterElement, "AttackPower"), BLValue = 0, CTValue = ReadOptionalInt(monsterElement, "CriticalRate"), DEValue = ReadOptionalInt(monsterElement, "DefPower"), DSValue = ReadOptionalInt(monsterElement, "DS"), EVValue = ReadOptionalInt(monsterElement, "Evasion"), HPValue = ReadOptionalInt(monsterElement, "HP"), HTValue = ReadOptionalInt(monsterElement, "HitRate"), MSValue = ReadOptionalInt(monsterElement, "MoveSpeed"), WSValue = ReadOptionalInt(monsterElement, "WalkSpeed"), Class = ReadOptionalInt(monsterElement, "Class") }); } return records; } private static List LoadMonsterSkillRecords(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("MonsterSkill.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "MonsterSkillList") { throw new InvalidOperationException("MonsterSkill.xml root node must be ."); } List records = new(); int rowIndex = 0; foreach (XElement skillElement in root.Elements("Skill")) { rowIndex++; string recordContext = BuildMonsterSkillRecordContext(skillElement, rowIndex); records.Add(new MonsterSkillRecord { SkillId = ReadRequiredInt(skillElement, "SkillIDX", recordContext), Type = ReadRequiredInt(skillElement, "MonsterID", recordContext), MinValue = ReadOptionalInt(skillElement, "EffectMin"), MaxValue = ReadOptionalInt(skillElement, "EffectMax"), CastingTime = ReadOptionalInt(skillElement, "CastTime"), Cooldown = ReadOptionalInt(skillElement, "CoolTime"), TargetCount = ReadOptionalTinyInt(skillElement, "TargetCount"), TargetMin = ReadOptionalTinyInt(skillElement, "TargetMinCount"), TargetMax = ReadOptionalTinyInt(skillElement, "TargetMaxCount"), UseTerms = ReadOptionalTinyInt(skillElement, "UseTerms"), RangeId = ReadOptionalInt(skillElement, "RangeIdx"), AnimationDelay = ReadOptionalDecimal(skillElement, "AniDelay"), ActiveType = ReadOptionalTinyInt(skillElement, "ActiveType"), SkillType = ReadOptionalInt(skillElement, "SkillType"), NoticeTime = ReadOptionalDecimal(skillElement, "NoticeTime") }); } return records; } private static string BuildMonsterRecordContext(XElement monsterElement, int rowIndex) { string type = monsterElement.Element("MonsterID")?.Value?.Trim(); string model = monsterElement.Element("ModelID")?.Value?.Trim(); string typePart = string.IsNullOrWhiteSpace(type) ? "?" : type; string modelPart = string.IsNullOrWhiteSpace(model) ? "?" : model; return $"Monster row {rowIndex} (MonsterID={typePart}, ModelID={modelPart})"; } private static string BuildMonsterSkillRecordContext(XElement skillElement, int rowIndex) { string skillId = skillElement.Element("SkillIDX")?.Value?.Trim(); string type = skillElement.Element("MonsterID")?.Value?.Trim(); string skillPart = string.IsNullOrWhiteSpace(skillId) ? "?" : skillId; string typePart = string.IsNullOrWhiteSpace(type) ? "?" : type; return $"MonsterSkill row {rowIndex} (SkillIDX={skillPart}, MonsterID={typePart})"; } 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 ReadOptionalInt(XElement parent, string elementName) { XElement? element = parent.Element(elementName); if (element == null || string.IsNullOrWhiteSpace(element.Value)) { return 0; } return int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) ? value : 0; } private static byte ReadRequiredTinyInt(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value < byte.MinValue || value > byte.MaxValue) { throw new InvalidOperationException($"{recordContext} field '{elementName}' exceeds byte range: '{value}'."); } return (byte)value; } private static byte ReadOptionalTinyInt(XElement parent, string elementName) { int value = ReadOptionalInt(parent, elementName); if (value < byte.MinValue) { return byte.MinValue; } if (value > byte.MaxValue) { return byte.MaxValue; } return (byte)value; } private static decimal ReadOptionalDecimal(XElement parent, string elementName) { XElement? element = parent.Element(elementName); if (element == null || string.IsNullOrWhiteSpace(element.Value)) { return 0m; } if (!decimal.TryParse(element.Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out decimal value)) { throw new InvalidOperationException($"Field '{elementName}' has invalid numeric value '{element.Value}'."); } return Math.Round(value, 2, MidpointRounding.AwayFromZero); } private static string ReadNameWithFallback(XElement parent, string recordContext, int monsterId, int maxLength) { XElement? element = parent.Element("Name"); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field 'Name'."); } string value = element.Value.Trim(); if (string.IsNullOrWhiteSpace(value)) { value = $"Monster_{monsterId}"; } if (value.Length > maxLength) { throw new InvalidOperationException($"{recordContext} field 'Name' exceeds {maxLength} characters."); } return value; } private sealed class MonsterBaseInfoRecord { public long Id { get; init; } public int Type { get; init; } public int Model { get; init; } public string Name { get; init; } = string.Empty; public byte Level { get; init; } public int ViewRange { get; init; } public int HuntRange { get; init; } public int ReactionType { get; init; } public int Attribute { get; init; } public int Element { get; init; } public int Family1 { get; init; } public int Family2 { get; init; } public int Family3 { get; init; } public int ASValue { get; init; } public int ARValue { get; init; } public int ATValue { get; init; } public int BLValue { get; init; } public int CTValue { get; init; } public int DEValue { get; init; } public int DSValue { get; init; } public int EVValue { get; init; } public int HPValue { get; init; } public int HTValue { get; init; } public int MSValue { get; init; } public int WSValue { get; init; } public int Class { get; init; } } private sealed class MonsterSkillRecord { public int SkillId { get; init; } public int Type { get; init; } public int MinValue { get; init; } public int MaxValue { get; init; } public int CastingTime { get; init; } public int Cooldown { get; init; } public byte TargetCount { get; init; } public byte TargetMin { get; init; } public byte TargetMax { get; init; } public byte UseTerms { get; init; } public int RangeId { get; init; } public decimal AnimationDelay { get; init; } public byte ActiveType { get; init; } public int SkillType { get; init; } public decimal NoticeTime { get; init; } } } }