public static bool GenericErrorHandler(ref int numError, object item) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Failed to read an item.", item.ToString()); numError--; if (numError < -10) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Failed to read too many items, the db will stop loading.", ErrorLevel.Critical); return(true); } return(false); }
public static void WriteViewIds(ServerDbs dbSource, AbstractDb <int> db) { if (ProjectConfiguration.SynchronizeWithClientDatabases && dbSource == ServerDbs.Items && ProjectConfiguration.HandleViewIds) { //return; int debugInfo = 0; _debugStatus = "OK"; var dataAccId = db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccId); var dataAccName = db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccName); if (dataAccId != null && dataAccName != null) { var itemDb1 = db.Get <int>(ServerDbs.Items); var itemDb2 = db.Get <int>(ServerDbs.Items2); var citemDb = db.Get <int>(ServerDbs.CItems); debugInfo++; try { itemDb1.Commands.Begin(); itemDb2.Commands.Begin(); citemDb.Commands.Begin(); debugInfo++; AccessoryTable table = new AccessoryTable(db, dataAccId, dataAccName); table.SetLuaTables(); table.SetTables(); table.SetDbs(); _debugStatus = "BackupManager"; BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncAccId, db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccId)); BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncAccName, db.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncAccName)); debugInfo++; _debugStatus = "WriteLuaFiles"; _writeLuaFiles(table.LuaAccIdParser, table.LuaAccNameParser, db); debugInfo++; } catch (Exception err) { ErrorHandler.HandleException("Couldn't save the accessory item files. Error code = " + debugInfo + ", state = " + _debugStatus, err, ErrorLevel.Low); DbIOErrorHandler.Handle(err, "Generic exception while trying to save the client accessory items, debug code = " + debugInfo, ErrorLevel.NotSpecified); DbIOErrorHandler.Focus(); } finally { itemDb1.Commands.End(); itemDb2.Commands.End(); citemDb.Commands.End(); } } } }
public bool ReportException(Exception item) { DbIOErrorHandler.HandleLoader(item, item.Message); NumberOfErrors--; if (NumberOfErrors < 0) { DbIOErrorHandler.Handle(item, "Failed to read too many items, the db will stop loading.", ErrorLevel.Critical); return(false); } return(true); }
public bool ReportException(string item) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), item); DbDebugHelper.OnExceptionThrown(DbSource, FilePath, _bdb); NumberOfErrors--; if (NumberOfErrors < 0) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Failed to read too many items, the db [" + DbSource + "] will stop loading.", ErrorLevel.Critical); DbDebugHelper.OnStoppedLoading(DbSource, FilePath, _bdb); return(false); } return(true); }
public bool Load(ServerDbs dbSource) { DbSource = dbSource; string path = DbPathLocator.DetectPath(DbSource); TextFileHelper.LatestFile = path; if (String.IsNullOrEmpty(path)) { if (_db.ThrowFileNotFoundException) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "File not found '" + DbSource + "'.", ErrorLevel.NotSpecified); } return(false); } FileType = DbPathLocator.GetFileType(path); FilePath = path; DbPathLocator.StoreFile(FilePath); DbDebugHelper.OnLoaded(DbSource, FilePath, _db); return(true); }
public override void SetValue(DbAttribute attribute, object value) { bool sameValue; try { sameValue = GetValue(attribute.Index).ToString() == value.ToString(); } catch { sameValue = false; } try { base.SetValue(attribute, value); } catch (Exception err) { DbIOErrorHandler.Handle(err, ("Failed to set or parse the value for [" + GetKey <TKey>() + "] at '" + attribute.DisplayName + "'. Value entered is : " + (value ?? "")).RemoveBreakLines(), ErrorLevel.NotSpecified); base.SetValue(attribute, attribute.Default); } if (!sameValue) { Modified = true; } }
public void ReportIdException(string exception, object item, ErrorLevel errorLevel = ErrorLevel.Warning) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), exception, item.ToString(), errorLevel); DbDebugHelper.OnExceptionThrown(DbSource, FilePath, _bdb); }
public static void WriteMobLuaFiles(AbstractDb <int> db) { // Ensures this is only written once if (ProjectConfiguration.SynchronizeWithClientDatabases && db.DbSource == ServerDbs.Mobs && ProjectConfiguration.SyncMobTables) { var metaTable = db.ProjectDatabase.GetMetaTable <int>(ServerDbs.Mobs); //var table = Attached["jobtbl_T"] as Dictionary<string, string>; // Load the tables DbDebugItem <int> debug = new DbDebugItem <int>(db); DbAttachLuaLoaderUpper(debug, "jobtbl", ProjectConfiguration.SyncMobId); var table = db.Attached["jobtbl_T"] as Dictionary <string, string>; if (table != null) { Dictionary <int, Npc> npcs = new Dictionary <int, Npc>(); var dataJobName = debug.AbsractDb.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncMobName); if (dataJobName == null) { return; } LuaParser parser = new LuaParser(dataJobName, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataJobName), EncodingService.DisplayEncoding); var jobNames = parser.Tables["JobNameTable"]; // Load the npcs from the lua files first foreach (var keyPair in table) { npcs[Int32.Parse(keyPair.Value)] = new Npc { NpcName = keyPair.Key }; } foreach (var keyPair in jobNames) { var key = keyPair.Key.Trim('[', ']'); var ingameSprite = keyPair.Value.Trim('\"'); int ival; if (!Int32.TryParse(key, out ival)) { key = key.Substring(7); var npcKeyPair = npcs.FirstOrDefault(p => p.Value.NpcName == key); if (npcKeyPair.Equals(default(KeyValuePair <int, Npc>))) { // Key not found // We ignore it } else { npcs[npcKeyPair.Key] = new Npc(npcKeyPair.Value) { IngameSprite = ingameSprite }; //npcKeyPair.Value = new ingameSprite; } continue; } npcs[ival] = new Npc { IngameSprite = ingameSprite }; } foreach (var tuple in metaTable.FastItems.OrderBy(p => p.Key)) { var ssprite = "JT_" + (tuple.GetValue <string>(ServerMobAttributes.SpriteName) ?? ""); var csprite = tuple.GetValue <string>(ServerMobAttributes.ClientSprite); if (ssprite != "JT_") { // not empty if (npcs.ContainsKey(tuple.Key)) { npcs[tuple.Key] = new Npc(npcs[tuple.Key]) { IngameSprite = csprite, NpcName = ssprite }; } else { Npc npc = new Npc { IngameSprite = csprite, NpcName = ssprite }; npcs[tuple.Key] = npc; } } } // Validation HashSet <string> duplicates = new HashSet <string>(); foreach (var npc in npcs) { if (!duplicates.Add(npc.Value.NpcName)) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Duplicate mob name (" + npc.Value.NpcName + ") for mobid " + npc.Key + " while saving npcidentity and jobname. The files have not been resaved."); DbIOErrorHandler.Focus(); return; } if (LatinOnly(npc.Value.NpcName) != npc.Value.NpcName) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "The mob name (" + npc.Value.NpcName + ") is invalid, only ASCII characters are allowed. Consider using '" + LatinOnly(npc.Value.NpcName) + "' as the name instead. The files have not been resaved."); DbIOErrorHandler.Focus(); return; } } // Converts back to a lua format { BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncMobId, db.ProjectDatabase.MetaGrf); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); parser.Tables.Clear(); var dico = new Dictionary <string, string>(); parser.Tables["jobtbl"] = dico; foreach (var npc in npcs.OrderBy(p => p.Key)) { dico[npc.Value.NpcName] = npc.Key.ToString(CultureInfo.InvariantCulture); } parser.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncMobId, File.ReadAllBytes(file)); } { BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncMobName, db.ProjectDatabase.MetaGrf); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); parser.Tables.Clear(); var dico = new Dictionary <string, string>(); parser.Tables["JobNameTable"] = dico; foreach (var npc in npcs.OrderBy(p => p.Key)) { var ingameSprite = LatinUpper((npc.Value.IngameSprite ?? "")); if (!String.IsNullOrEmpty(ingameSprite.GetExtension())) { ingameSprite = ingameSprite.ReplaceExtension(ingameSprite.GetExtension().ToLower()); } if (string.IsNullOrEmpty(ingameSprite)) { continue; } dico["[jobtbl." + npc.Value.NpcName + "]"] = "\"" + ingameSprite + "\""; } parser.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncMobName, File.ReadAllBytes(file)); } } } }
/// <summary> /// Converts a group from an ItemGroup to a Hercules entry /// </summary> /// <param name="gdb">The base db.</param> /// <param name="groupId">The group id.</param> /// <param name="aegisNames">The aegis names.</param> /// <param name="names">The names.</param> /// <returns>A string for an ItemGroup entry converted to Hercules's format</returns> public static string ToHerculesDbEntry(BaseDb gdb, int groupId, List <string> aegisNames, List <string> names) { StringBuilder builder = new StringBuilder(); var dbItems = gdb.GetMeta <int>(ServerDbs.Items); var dbGroups = gdb.Get <int>(ServerDbs.ItemGroups); if (groupId < 500) { var dbConstants = gdb.Get <string>(ServerDbs.Constants); string sId = groupId.ToString(CultureInfo.InvariantCulture); // The current db is from rAthena var tuple = dbConstants.FastItems.FirstOrDefault(p => p.GetValue <string>(1) == sId && p.GetKey <string>().StartsWith("IG_")); string constant = null; if (tuple != null) { constant = tuple.GetKey <string>().Substring(3); } else { var res = DbIOItemGroups.Constants.Where(p => p.Value == groupId).ToList(); if (res.Count > 0) { constant = res[0].Key; } } if (constant != null) { string originalConstantValue = constant; ReadableTuple <int> tupleItem; // Attempts to retrieve the item based on the script tupleItem = dbItems.FastItems.FirstOrDefault(p => p.GetValue <string>(ServerItemAttributes.Script).IndexOf("getrandgroupitem(IG_" + originalConstantValue + ")", StringComparison.OrdinalIgnoreCase) > -1); if (tupleItem == null) { // Attempts to retrieve the item based on a formatted constant name (with underscore) StringBuilder temp = new StringBuilder(); temp.Append(constant[0]); for (int i = 1; i < constant.Length; i++) { if (constant[i] == '_') { i++; if (i < constant.Length) { temp.Append(constant[i]); } } else if (char.IsUpper(constant[i])) { temp.Append('_'); temp.Append(constant[i]); } else { temp.Append(constant[i]); } } constant = temp.ToString(); // Attempts to retrieve the item with the Old prefix string oldConstant = "Old_" + constant; // Attempts to retrieve the item without the Old prefix tupleItem = dbItems.FastItems.FirstOrDefault(p => p.GetStringValue(ServerItemAttributes.AegisName.Index) == oldConstant); if (tupleItem == null) { tupleItem = dbItems.FastItems.FirstOrDefault(p => p.GetStringValue(ServerItemAttributes.AegisName.Index) == constant); } } // Retrieve the closest item based on the names in the ItemDb. // It uses the Levenshtein distance algorithm to find the clostest match. // This method 'always' returns a value, but a warning is prompted to the user in the error console. if (tupleItem == null) { List <string> values1 = aegisNames; List <string> values2 = names; string closestMatch1 = Methods.ClosestString(originalConstantValue, values1); string closestMatch2 = Methods.ClosestString(originalConstantValue, values2); int lev1 = Methods.LevenshteinDistance(originalConstantValue, closestMatch1); int lev2 = Methods.LevenshteinDistance(originalConstantValue, closestMatch2); tupleItem = dbItems.FastItems[lev1 < lev2 ? values1.IndexOf(closestMatch1) : values2.IndexOf(closestMatch2)]; string closestMatch = tupleItem.GetValue <string>(ServerItemAttributes.AegisName); if (Math.Min(lev1, lev2) != 0 && closestMatch.Replace("_", "") != constant) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "A suspicious conversion occurred for the item [" + originalConstantValue + "]. The group item name is [" + tupleItem.GetValue <string>(ServerItemAttributes.AegisName) + "]."); } } builder.AppendLine(tupleItem.GetValue <string>(ServerItemAttributes.AegisName) + ": ("); Dictionary <int, ReadableTuple <int> > table = (Dictionary <int, ReadableTuple <int> >)dbGroups.GetTuple(groupId).GetRawValue(ServerItemGroupAttributes.Table.Index); foreach (var pair in table) { tupleItem = dbItems.TryGetTuple(pair.Key); string name = tupleItem == null ? "ID" + pair.Key : tupleItem.GetValue <string>(ServerItemAttributes.AegisName); if (pair.Value.GetValue <string>(ServerItemGroupSubAttributes.Rate) == "1") { builder.Append("\t\""); builder.Append(name); builder.AppendLine("\","); } else { builder.Append("\t(\""); builder.Append(name); builder.Append("\","); builder.Append(pair.Value.GetValue <string>(ServerItemGroupSubAttributes.Rate)); builder.AppendLine("),"); } } builder.Append(")"); } else { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Failed to find the constant name with the id [" + sId + "]."); } } else { // The current db is from Hercules var tuple = dbItems.TryGetTuple(groupId); if (tuple != null) { // Check if the item is a package or a group! Dictionary <int, ReadableTuple <int> > table = (Dictionary <int, ReadableTuple <int> >)dbGroups.GetTuple(groupId).GetRawValue(ServerItemGroupAttributes.Table.Index); if (table.Values.Any(p => p.GetRawElements().Skip(3).Take(6).Count(q => (q ?? "").ToString() == "") > 0)) { // This is a package } else { // This is an item_group builder.AppendLine(tuple.GetValue <string>(ServerItemAttributes.AegisName) + ": ("); foreach (var pair in table) { tuple = dbItems.TryGetTuple(pair.Key); string name = tuple == null ? "ID" + pair.Key : tuple.GetValue <string>(ServerItemAttributes.AegisName); if (pair.Value.GetValue <string>(ServerItemGroupSubAttributes.Rate) == "1") { builder.Append("\t\""); builder.Append(name); builder.AppendLine("\","); } else { builder.Append("\t(\""); builder.Append(name); builder.Append("\","); builder.Append(pair.Value.GetValue <string>(ServerItemGroupSubAttributes.Rate)); builder.AppendLine("),"); } } builder.Append(")"); } } else { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Failed to retrieve the item ID associated with the group ID.", groupId.ToString(CultureInfo.InvariantCulture), ErrorLevel.Critical); } } return(builder.ToString()); }
public SdeEditor() : base("Server database editor", "cde.ico", SizeToContent.Manual, ResizeMode.CanResize) { SplashDialog loading = new SplashDialog(); loading.Show(); Loaded += delegate { loading.Terminate(); }; try { ApplicationShortcut.OverrideBindings(SdeAppConfiguration.Remapper); } catch (Exception err) { SdeAppConfiguration.Remapper.Clear(); ApplicationShortcut.OverrideBindings(SdeAppConfiguration.Remapper); ErrorHandler.HandleException("Failed to load the custom key bindings. The bindings will be reset to their default values.", err); } string configFile = _parseCommandLineArguments(); GrfPath.Delete(ProjectConfiguration.DefaultFileName); InitializeComponent(); Instance = this; ShowInTaskbar = true; _asyncOperation = new AsyncOperation(_progressBar); _clientDatabase = new SdeDatabase(_metaGrf); _loadMenu(); if (configFile == null) { ProjectConfiguration.ConfigAsker = new ConfigAsker(ProjectConfiguration.DefaultFileName); if (SdeAppConfiguration.AlwaysReopenLatestProject) { if (_recentFilesManager.Files.Count > 0 && File.Exists(_recentFilesManager.Files[0])) { ProjectConfiguration.ConfigAsker = new ConfigAsker(configFile = _recentFilesManager.Files[0]); } } } else if (File.Exists(configFile)) { ProjectConfiguration.ConfigAsker = new ConfigAsker(configFile); } _loadSettingsTab(); if (configFile != null) { ReloadSettings(configFile); } _loadGenericTab(); _clientDatabase.Commands.ModifiedStateChanged += new AbstractCommand <IGenericDbCommand> .AbstractCommandsEventHandler(_commands_ModifiedStateChanged); ApplicationShortcut.Link(ApplicationShortcut.Undo, () => _clientDatabase.Commands.Undo(), this); ApplicationShortcut.Link(ApplicationShortcut.UndoGlobal, () => _clientDatabase.Commands.Undo(), this); ApplicationShortcut.Link(ApplicationShortcut.Redo, () => _clientDatabase.Commands.Redo(), this); ApplicationShortcut.Link(ApplicationShortcut.RedoGlobal, () => _clientDatabase.Commands.Redo(), this); ApplicationShortcut.Link(ApplicationShortcut.Search, () => _execute(v => v.Search()), this); ApplicationShortcut.Link(ApplicationShortcut.Delete, () => _execute(v => v.DeleteItems()), this); ApplicationShortcut.Link(ApplicationShortcut.Rename, () => _execute(v => v.ChangeId()), this); ApplicationShortcut.Link(ApplicationShortcut.NavigationBackward, () => _tabEngine.Undo(), this); ApplicationShortcut.Link(ApplicationShortcut.NavigationBackward2, () => _tabEngine.Redo(), this); ApplicationShortcut.Link(ApplicationShortcut.NavigationForward, () => _tabEngine.Redo(), this); ApplicationShortcut.Link(ApplicationShortcut.Change, () => _execute(v => v.ChangeId()), this); ApplicationShortcut.Link(ApplicationShortcut.Restrict, () => _execute(v => v.ShowSelectedOnly()), this); ApplicationShortcut.Link(ApplicationShortcut.CopyTo, () => _execute(v => v.CopyItemTo()), this); ApplicationShortcut.Link(ApplicationShortcut.New, () => _execute(v => v.AddNewItem()), this); ApplicationShortcut.Link(ApplicationShortcut.Save, () => _menuItemDatabaseSave_Click(this, null), this); ApplicationShortcut.Link(ApplicationShortcut.Replace, () => { if (_menuItemReplaceAll.IsEnabled) { _menuItemReplaceAll_Click(this, null); } }, this); ApplicationShortcut.Link(ApplicationShortcut.FromString("Ctrl-Enter", "Select next entry"), () => _execute(v => v.SelectNext()), this); ApplicationShortcut.Link(ApplicationShortcut.FromString("Ctrl-Shift-Enter", "Select previous entry"), () => _execute(v => v.SelectPrevious()), this); Configuration.EnableDebuggerTrace = false; _tnbUndo.SetUndo(_tabEngine); _tnbRedo.SetRedo(_tabEngine); _tmbUndo.SetUndo(_clientDatabase.Commands); _tmbRedo.SetRedo(_clientDatabase.Commands); Extensions.GenerateListViewTemplate(_debugList, new ListViewDataTemplateHelper.GeneralColumnInfo[] { new ListViewDataTemplateHelper.GeneralColumnInfo { Header = "#", DisplayExpression = "ErrorNumber", SearchGetAccessor = "ErrorNumber", FixedWidth = 35, ToolTipBinding = "ErrorNumber", TextAlignment = TextAlignment.Right }, new ListViewDataTemplateHelper.ImageColumnInfo { Header = "", DisplayExpression = "DataImage", SearchGetAccessor = "Exception", FixedWidth = 20, MaxHeight = 24 }, new ListViewDataTemplateHelper.RangeColumnInfo { Header = "Exception", DisplayExpression = "Exception", SearchGetAccessor = "Exception", IsFill = true, TextAlignment = TextAlignment.Left, ToolTipBinding = "OriginalException", TextWrapping = TextWrapping.Wrap, MinWidth = 120 }, new ListViewDataTemplateHelper.GeneralColumnInfo { Header = "Id", DisplayExpression = "Id", SearchGetAccessor = "Id", FixedWidth = 90, TextAlignment = TextAlignment.Left, ToolTipBinding = "Id", TextWrapping = TextWrapping.Wrap }, new ListViewDataTemplateHelper.GeneralColumnInfo { Header = "File", DisplayExpression = "FileName", SearchGetAccessor = "FilePath", FixedWidth = 145, TextAlignment = TextAlignment.Left, ToolTipBinding = "FilePath", TextWrapping = TextWrapping.Wrap }, new ListViewDataTemplateHelper.GeneralColumnInfo { Header = "Line", DisplayExpression = "Line", SearchGetAccessor = "Line", FixedWidth = 40, TextAlignment = TextAlignment.Left, ToolTipBinding = "Line" }, }, null, new string[] { "Added", "Blue", "Default", "Black" }); ApplicationShortcut.Link(ApplicationShortcut.Copy, () => WpfUtils.CopyContent(_debugList), _debugList); _debugItems = new ObservableCollection <DebugItemView>(); _debugList.ItemsSource = _debugItems; DbIOErrorHandler.ClearListeners(); DbIOErrorHandler.AddListener(this); _clientDatabase.PreviewReloaded += delegate { this.BeginDispatch(delegate { foreach (TabItem tabItem in _mainTabControl.Items) { tabItem.IsEnabled = true; var tabItemHeader = tabItem.Header as DisplayLabel; if (tabItemHeader != null) { tabItemHeader.ResetEnabled(); } } }); }; _clientDatabase.Reloaded += delegate { _mainTabControl.Dispatch(p => p.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new List <object>(), _mainTabControl.SelectedItem == null ? new List <object>() : new List <object> { _mainTabControl.SelectedItem }))); ServerType serverType = DbPathLocator.GetServerType(); bool renewal = DbPathLocator.GetIsRenewal(); string header = String.Format("Current ({0} - {1})", serverType == ServerType.RAthena ? "rA" : "Herc", renewal ? "Renewal" : "Pre-Renewal"); this.BeginDispatch(delegate { _menuItemExportDbCurrent.IsEnabled = true; _menuItemExportDbCurrent.Header = header; _menuItemExportSqlCurrent.IsEnabled = true; _menuItemExportSqlCurrent.Header = header; }); }; SelectionChanged += _sdeEditor_SelectionChanged; }
public bool ReportIdException(FileParserException fpe, object item) { DbIOErrorHandler.Handle(fpe, fpe.Reason, (item ?? "#").ToString(), fpe.Line); DbDebugHelper.OnExceptionThrown(DbSource, fpe.File, _bdb); return(true); }
private static void _loadItemsGroupdDb(AbstractDb <int> db, ServerDbs serverDb, string file) { int numberOfErrors = 3; TextFileHelper.LatestFile = file; if (String.IsNullOrEmpty(file)) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "File not found " + ServerDbs.ItemGroups + ".", ErrorLevel.NotSpecified); return; } var itemDb1 = db.ProjectDatabase.GetDb <int>(ServerDbs.Items); var itemDb2 = db.ProjectDatabase.GetDb <int>(ServerDbs.Items2); if (!itemDb1.IsLoaded) { itemDb1.LoadDb(); } if (!itemDb2.IsLoaded) { itemDb2.LoadDb(); } var itemDb = new MetaTable <int>(ServerItemAttributes.AttributeList); itemDb.AddTable(itemDb1.Table); itemDb.AddTable(itemDb2.Table); itemDb.MergeOnce(); Dictionary <string, ReadableTuple <int> > bufferredTuples = new Dictionary <string, ReadableTuple <int> >(); foreach (var tuple in itemDb.FastItems) { bufferredTuples[tuple.GetStringValue(ServerItemAttributes.AegisName.Index)] = tuple; } var table = db.Table; if (db.Attached[serverDb] == null) { db.Attached[serverDb] = new Utilities.Extension.Tuple <ServerDbs, HashSet <int> >(serverDb, new HashSet <int>()); } HashSet <int> loadedIds = ((Utilities.Extension.Tuple <ServerDbs, HashSet <int> >)db.Attached[serverDb]).Item2; foreach (string[] elements in TextFileHelper.GetElementsByCommas(IOHelper.ReadAllBytes(file))) { try { int itemId; int iItemId; if (Int32.TryParse(elements[0], out iItemId)) { itemId = iItemId; } else { var constantDb = db.ProjectDatabase.GetDb <string>(ServerDbs.Constants); if (!constantDb.IsLoaded) { constantDb.LoadDb(); } var tuple = constantDb.Table.TryGetTuple(elements[0]); if (tuple == null) { if (DbPathLocator.GenericErrorHandler(ref numberOfErrors, elements[0])) { return; } continue; } itemId = tuple.GetValue <int>(1); } string orate = elements[2]; int nameId; int rate; if (Int32.TryParse(elements[1], out nameId)) { } else { var tuple = bufferredTuples[elements[1]]; if (tuple == null) { if (DbPathLocator.GenericErrorHandler(ref numberOfErrors, elements[0])) { return; } continue; } nameId = tuple.Key; } Int32.TryParse(orate, out rate); var id = (object)itemId; loadedIds.Add((int)id); if (!table.ContainsKey(itemId)) { ReadableTuple <int> tuple = new ReadableTuple <int>(itemId, db.AttributeList); tuple.SetRawValue(ServerItemGroupAttributes.Table, new Dictionary <int, ReadableTuple <int> >()); table.Add(itemId, tuple); } Dictionary <int, ReadableTuple <int> > dico = (Dictionary <int, ReadableTuple <int> >)table.GetRaw(itemId, ServerItemGroupAttributes.Table); ReadableTuple <int> newTuple = new ReadableTuple <int>(nameId, ServerItemGroupSubAttributes.AttributeList); List <DbAttribute> attributes = new List <DbAttribute>(ServerItemGroupSubAttributes.AttributeList.Attributes); for (int i = 2; i < elements.Length; i++) { newTuple.SetRawValue(attributes[i - 1], elements[i]); } newTuple.SetRawValue(ServerItemGroupSubAttributes.ParentGroup, itemId); dico[nameId] = newTuple; } catch { if (DbPathLocator.GenericErrorHandler(ref numberOfErrors, elements[0])) { return; } } } }
private static void _loadEntry(Table <int, ReadableTuple <int> > table, LuaKeyValue item) { int itemIndex = Int32.Parse(item.Key.Substring(1, item.Key.Length - 2)); LuaList itemProperties = item.Value as LuaList; LuaList contentProperties; StringBuilder resources; if (itemProperties != null) { foreach (LuaKeyValue itemProperty in itemProperties.Variables) { switch (itemProperty.Key) { case "UI_Type": table.SetRaw(itemIndex, ClientCheevoAttributes.UiType, ((LuaValue)itemProperty.Value).Value); break; case "group": table.SetRaw(itemIndex, ClientCheevoAttributes.GroupId, DbIOMethods.RemoveQuotes(((LuaValue)itemProperty.Value).Value)); break; case "major": table.SetRaw(itemIndex, ClientCheevoAttributes.Major, ((LuaValue)itemProperty.Value).Value); break; case "minor": table.SetRaw(itemIndex, ClientCheevoAttributes.Minor, ((LuaValue)itemProperty.Value).Value); break; case "title": table.SetRaw(itemIndex, ClientCheevoAttributes.Name, DbIOMethods.RemoveQuotes(((LuaValue)itemProperty.Value).Value)); break; case "reward": case "content": contentProperties = itemProperty.Value as LuaList; if (contentProperties == null) { continue; } try { foreach (LuaKeyValue contentProperty in contentProperties.Variables) { switch (contentProperty.Key) { case "summary": table.SetRaw(itemIndex, ClientCheevoAttributes.Summary, DbIOMethods.RemoveQuotes(((LuaValue)contentProperty.Value).Value)); break; case "details": table.SetRaw(itemIndex, ClientCheevoAttributes.Details, DbIOMethods.RemoveQuotes(((LuaValue)contentProperty.Value).Value)); break; case "title": table.SetRaw(itemIndex, ClientCheevoAttributes.RewardTitleId, ((LuaValue)contentProperty.Value).Value); break; case "buff": table.SetRaw(itemIndex, ClientCheevoAttributes.RewardBuff, ((LuaValue)contentProperty.Value).Value); break; case "item": table.SetRaw(itemIndex, ClientCheevoAttributes.RewardId, ((LuaValue)contentProperty.Value).Value); break; } } } catch (Exception err) { ErrorHandler.HandleException(err); } break; case "resource": resources = new StringBuilder(); contentProperties = itemProperty.Value as LuaList; if (contentProperties == null) { continue; } foreach (LuaKeyValue contentProperty in contentProperties.Variables) { try { int resId; if (!Int32.TryParse(contentProperty.Key.Substring(1, contentProperty.Key.Length - 2), out resId)) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), String.Format("ID: {0}, file: '{1}', exception: '{2}'", itemIndex.ToString(CultureInfo.InvariantCulture), TextFileHelper.LatestFile, "Invalid resource ID, found \"" + contentProperty.Key + "\", expected an integer."), ErrorLevel.Warning); continue; } LuaList resourceProperties = contentProperty.Value as LuaList; if (resourceProperties == null) { continue; } resources.Append(resId); foreach (LuaKeyValue resourceProperty in resourceProperties.Variables) { string value = ((LuaValue)resourceProperty.Value).Value; resources.Append("__%"); resources.Append(resourceProperty.Key); resources.Append("__%"); if (value.StartsWith("\"")) { resources.Append(DbIOMethods.RemoveQuotes(value)); } else { resources.Append(value); } } resources.Append("__&"); } catch (Exception err) { throw new Exception("Failed to read resource for ID " + itemIndex, err); } } table.SetRaw(itemIndex, ClientCheevoAttributes.Resources, resources.ToString()); break; case "score": table.SetRaw(itemIndex, ClientCheevoAttributes.Score, ((LuaValue)itemProperty.Value).Value); break; } } } }