/// <summary> /// Converts a sql file to json file /// </summary> public static bool sql2json(Session session, Weenie weenie, string sql_folder, string sql_filename) { if (!LifestonedConverter.TryConvertACEWeenieToLSDJSON(weenie, out var json, out var json_weenie)) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {sql_filename} to json"); return(false); } var json_folder = sql_folder.Replace("sql", "json"); var json_filename = sql_filename.Replace(".sql", ".json"); var di = new DirectoryInfo(json_folder); if (!di.Exists) { di.Create(); } if (File.Exists(json_folder + json_filename) && LifestonedLoader.AppendMetadata(json_folder + json_filename, json_weenie)) { json = JsonConvert.SerializeObject(json_weenie, LifestonedConverter.SerializerSettings); } File.WriteAllText(json_folder + json_filename, json); CommandHandlerHelper.WriteOutputInfo(session, $"Converted {sql_filename} to {json_filename}"); return(true); }
public CommandHandler(Controller controller, CommandHandlerHelper cmdHelper, AntilStorageHelper storageHelper) { this.controller = controller; this.cmdHelper = cmdHelper; this.storageHelper = storageHelper; ch = new ConsoleHelper(); }
/// <summary> /// Converts SQL to JSON, imports to database, clears the weenie cache /// </summary> private static void HandleImportSQL(Session session, string sql_folder, string sql_file) { if (!uint.TryParse(Regex.Match(sql_file, @"\d+").Value, out var wcid)) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find wcid from {sql_file}"); return; } // import sql to db ImportSQL(sql_folder + sql_file); CommandHandlerHelper.WriteOutputInfo(session, $"Imported {sql_file}"); // clear this weenie out of the cache DatabaseManager.World.ClearCachedWeenie(wcid); // load weenie from database var weenie = DatabaseManager.World.GetCachedWeenie(wcid); if (weenie == null) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't load weenie {wcid} from db"); return; } sql2json(session, weenie, sql_folder, sql_file); }
public static void HandleClearCache(Session session, params string[] parameters) { var mode = CacheType.All; if (parameters.Length > 0) { if (parameters[0].Contains("weenie", StringComparison.OrdinalIgnoreCase)) { mode = CacheType.Weenie; } if (parameters[0].Contains("spell", StringComparison.OrdinalIgnoreCase)) { mode = CacheType.Spell; } } if (mode.HasFlag(CacheType.Weenie)) { CommandHandlerHelper.WriteOutputInfo(session, "Clearing weenie cache"); DatabaseManager.World.ClearWeenieCache(); } if (mode.HasFlag(CacheType.Spell)) { CommandHandlerHelper.WriteOutputInfo(session, "Clearing spell cache"); DatabaseManager.World.ClearSpellCache(); WorldObject.ClearSpellCache(); } }
/// <summary> /// Converts JSON to SQL, imports to database, and clears the weenie cache /// </summary> private static void HandleImportJson(Session session, string json_folder, string json_file, WeenieSQLWriter converter) { if (!uint.TryParse(Regex.Match(json_file, @"\d+").Value, out var wcid)) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find wcid from {json_file}"); return; } // convert json -> sql var sqlFile = json2sql(session, json_folder, json_file, converter); if (sqlFile == null) { return; } // import sql to db var sql_folder = json_folder.Replace("json", "sql"); ImportSQL(sql_folder + sqlFile); CommandHandlerHelper.WriteOutputInfo(session, $"Imported {sqlFile}"); // clear this weenie out of the cache DatabaseManager.World.ClearCachedWeenie(wcid); }
/// <summary> /// Converts a json file to sql file /// </summary> public static string json2sql(Session session, string folder, string json_filename, WeenieSQLWriter converter) { var json_file = folder + json_filename; var success = LifestonedLoader.TryLoadWeenie(json_file, out var weenie); if (!success) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to load {json_file}"); return(null); } // output to sql success = LifestonedConverter.TryConvert(weenie, out var output); if (!success) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {json_file}"); return(null); } var sqlFolder = folder.Replace("json", "sql"); var di = new DirectoryInfo(sqlFolder); if (!di.Exists) { di.Create(); } var sqlFilename = ""; try { if (output.LastModified == DateTime.MinValue) { output.LastModified = DateTime.UtcNow; } sqlFilename = converter.GetDefaultFileName(output); var sqlFile = new StreamWriter(sqlFolder + sqlFilename); converter.CreateSQLDELETEStatement(output, sqlFile); sqlFile.WriteLine(); converter.CreateSQLINSERTStatement(output, sqlFile); sqlFile.Close(); } catch (Exception e) { Console.WriteLine(e); CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {json_file}"); return(null); } CommandHandlerHelper.WriteOutputInfo(session, $"Converted {json_filename} to {sqlFilename}"); return(sqlFilename); }
public async Task <ICommandResponse> Handle(AtualizarSaldoExtratoCommand command, CancellationToken cancellationToken) { return(await CommandHandlerHelper.ExecuteToResponse(() => { var extrato = extratoService.RetornarExtrato(command.ExtratoId).Result; var evento = new ExtratoSaldoAtualizadoIntegrationEvent(command.ExtratoId, extrato.Saldo); eventBus.PublishEvent(evento); })); }
public static void HandleExportSql(Session session, params string[] parameters) { DirectoryInfo di = VerifyContentFolder(session, false); var sep = Path.DirectorySeparatorChar; if (!uint.TryParse(parameters[0], out var wcid)) { CommandHandlerHelper.WriteOutputInfo(session, $"{parameters[0]} not a valid wcid"); return; } var weenie = DatabaseManager.World.GetCachedWeenie(wcid); if (weenie == null) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find weenie {wcid}"); return; } var sql_folder = $"{di.FullName}{sep}sql{sep}weenies{sep}"; di = new DirectoryInfo(sql_folder); if (!di.Exists) { di.Create(); } var converter = new WeenieSQLWriter(); converter.WeenieNames = DatabaseManager.World.GetAllWeenieNames(); converter.SpellNames = DatabaseManager.World.GetAllSpellNames(); converter.TreasureDeath = DatabaseManager.World.GetAllTreasureDeath(); converter.TreasureWielded = DatabaseManager.World.GetAllTreasureWielded(); var sql_filename = converter.GetDefaultFileName(weenie); var writer = new StreamWriter(sql_folder + sql_filename); try { converter.CreateSQLDELETEStatement(weenie, writer); writer.WriteLine(); converter.CreateSQLINSERTStatement(weenie, writer); writer.Close(); } catch (Exception e) { Console.WriteLine(e); CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {weenie.ClassId} - {weenie.ClassName}"); return; } CommandHandlerHelper.WriteOutputInfo(session, $"Exported {sql_folder}{sql_filename}"); }
public void Handle(CommandHandlerHelper helper) { try { string script = helper.Command.Args["script"].ToString(); object response = helper.Client.JSEngine.Evaluate(helper.Request, script); object convertedResponse = ResponseConverterManager.Convert(response); helper.Reply(enums.ResponseType.Response, convertedResponse); } catch (Exception e) { helper.Reply(enums.ResponseType.Error, e); } }
public static void ImportSQLWeenieWrapped(Session session, string param, string param2) { DirectoryInfo di = VerifyContentFolder(session); if (!di.Exists) { return; } var sep = Path.DirectorySeparatorChar; var prefix = param + " "; var sql_folder = $"{di.FullName}{sep}sql{sep}weenies{sep}"; if (param.Equals("folder", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(param2)) { if (param2.Contains("..")) { CommandHandlerHelper.WriteOutputInfo(session, $"Path may not contain the sequence '..'"); return; } sql_folder = $"{sql_folder}{param2}{sep}"; prefix = ""; } else if (param.Equals("all", StringComparison.OrdinalIgnoreCase)) { prefix = ""; } di = new DirectoryInfo(sql_folder); if (!di.Exists) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find folder: {di.FullName}"); return; } var files = di.Exists ? di.GetFiles($"{prefix}*.sql", SearchOption.AllDirectories) : null; if (files == null || files.Length == 0) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find {sql_folder}{prefix}*.sql"); return; } foreach (var file in files) { ImportSQLWeenie(session, Path.GetDirectoryName(file.FullName) + Path.DirectorySeparatorChar, file.Name); } }
public void Verify_that_each_command_has_atleast_one_command_handler() { var commands = CommandHandlerHelper.GetCommands(); var commandHandlers = CommandHandlerHelper.GetCommandHandlers(); var stringBuilder = new StringBuilder(); foreach (var command in commands.Where(command => !commandHandlers.ContainsKey(command))) { stringBuilder.AppendLine(string.Format("No command handler found for command '{0}'", command.FullName)); continue; } if (stringBuilder.Length > 0) { throw new Exception(string.Format("\n\nCommand handler exceptions:\n{0}\n", stringBuilder)); } }
public static void HandleExportJson(Session session, params string[] parameters) { DirectoryInfo di = VerifyContentFolder(session, false); var sep = Path.DirectorySeparatorChar; if (!uint.TryParse(parameters[0], out var wcid)) { CommandHandlerHelper.WriteOutputInfo(session, $"{parameters[0]} not a valid wcid"); return; } var weenie = DatabaseManager.World.GetCachedWeenie(wcid); if (weenie == null) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find weenie {wcid}"); return; } if (!LifestonedConverter.TryConvertACEWeenieToLSDJSON(weenie, out var json, out var json_weenie)) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {weenie.ClassId} - {weenie.ClassName} to json"); return; } var json_folder = $"{di.FullName}{sep}json{sep}weenies{sep}"; di = new DirectoryInfo(json_folder); if (!di.Exists) { di.Create(); } var json_filename = $"{weenie.ClassId} - {weenie.WeeniePropertiesString.FirstOrDefault(i => i.Type == (int)PropertyString.Name)?.Value}.json"; if (File.Exists(json_folder + json_filename) && LifestonedLoader.AppendMetadata(json_folder + json_filename, json_weenie)) { json = JsonConvert.SerializeObject(json_weenie, LifestonedConverter.SerializerSettings); } File.WriteAllText(json_folder + json_filename, json); CommandHandlerHelper.WriteOutputInfo(session, $"Exported {json_folder}{json_filename}"); }
public static void HandleImportJson(Session session, params string[] parameters) { DirectoryInfo di = VerifyContentFolder(session); if (!di.Exists) { return; } var sep = Path.DirectorySeparatorChar; var json_folder = $"{di.FullName}{sep}json{sep}weenies{sep}"; var wcid = parameters[0]; var prefix = wcid + " - "; if (wcid.Equals("all", StringComparison.OrdinalIgnoreCase)) { prefix = ""; } di = new DirectoryInfo(json_folder); var files = di.Exists ? di.GetFiles($"{prefix}*.json") : null; if (files == null || files.Length == 0) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find {json_folder}{prefix}*.json"); return; } var converter = new WeenieSQLWriter(); converter.WeenieNames = DatabaseManager.World.GetAllWeenieNames(); converter.SpellNames = DatabaseManager.World.GetAllSpellNames(); converter.TreasureDeath = DatabaseManager.World.GetAllTreasureDeath(); converter.TreasureWielded = DatabaseManager.World.GetAllTreasureWielded(); foreach (var file in files) { HandleImportJson(session, json_folder, file.Name, converter); } }
protected override void DoCommand(IOrderGroup order, CommandParameters cp) { Mediachase.Ibn.Web.UI.CHelper.RequireDataBind(); var purchaseOrder = order as PurchaseOrder; var workflowResults = OrderGroupWorkflowManager.RunWorkflow(purchaseOrder, "SaveChangesWorkflow", false, //false, new Dictionary <string, object> { { "PreventProcessPayment", !string.IsNullOrEmpty(order.Properties["QuoteStatus"] as string) && (order.Properties["QuoteStatus"].ToString() == Constant.Quote.RequestQuotation || order.Properties["QuoteStatus"].ToString() == Constant.Quote.RequestQuotationFinished) } }); if (workflowResults.Status != WorkflowStatus.Completed) { var msg = "Unknow error"; if (workflowResults.Exception != null) { msg = workflowResults.Exception.Message; } ErrorManager.GenerateError(msg); } else { WriteOrderChangeNotes(purchaseOrder); SavePurchaseOrderChanges(purchaseOrder); OrderHelper.ExitPurchaseOrderFromEditMode(purchaseOrder.OrderGroupId); } var warnings = OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(workflowResults); if (warnings.Any()) { CommandHandlerHelper.ShowStatusMessage(string.Join(", ", warnings), CommandManager); } }
/// <summary> /// Converts a sql file to json file /// </summary> public static bool sql2json(Session session, Weenie weenie, string sql_folder, string sql_filename) { if (!LifestonedConverter.TryConvertACEWeenieToLSDJSON(weenie, out var json, out var json_weenie)) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {sql_filename} to json"); return(false); } var json_folder = sql_folder.Replace("sql", "json"); var json_filename = sql_filename.Replace(".sql", ".json"); var match = Regex.Match(json_filename, @"^(\d+)"); if (match.Success) { var wcid = match.Groups[1].Value; if (!json_filename.StartsWith(wcid + " -")) { json_filename = wcid + " -" + json_filename.Substring(wcid.Length); } } var di = new DirectoryInfo(json_folder); if (!di.Exists) { di.Create(); } if (File.Exists(json_folder + json_filename) && LifestonedLoader.AppendMetadata(json_folder + json_filename, json_weenie)) { json = JsonConvert.SerializeObject(json_weenie, LifestonedConverter.SerializerSettings); } File.WriteAllText(json_folder + json_filename, json); CommandHandlerHelper.WriteOutputInfo(session, $"Converted {sql_filename} to {json_filename}"); return(true); }
/// <summary> /// Returns the absolute content folder path, and verifies it exists /// </summary> private static DirectoryInfo VerifyContentFolder(Session session, bool showError = true) { var content_folder = PropertyManager.GetString("content_folder").Item; var sep = Path.DirectorySeparatorChar; // handle relative path if (content_folder.StartsWith(".")) { var cwd = Directory.GetCurrentDirectory() + sep; content_folder = cwd + content_folder; } var di = new DirectoryInfo(content_folder); if (!di.Exists && showError) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find content folder: {di.FullName}"); CommandHandlerHelper.WriteOutputInfo(session, "To set your content folder, /modifystring content_folder <path>"); } return(di); }
public static void HandleImportSQL(Session session, params string[] parameters) { DirectoryInfo di = VerifyContentFolder(session); if (!di.Exists) { return; } var sep = Path.DirectorySeparatorChar; var sql_folder = $"{di.FullName}{sep}sql{sep}weenies{sep}"; var wcid = parameters[0]; var prefix = wcid + " "; if (wcid.Equals("all", StringComparison.OrdinalIgnoreCase)) { prefix = ""; } di = new DirectoryInfo(sql_folder); var files = di.Exists ? di.GetFiles($"{prefix}*.sql") : null; if (files == null || files.Length == 0) { CommandHandlerHelper.WriteOutputInfo(session, $"Couldn't find {sql_folder}{prefix}*.sql"); return; } foreach (var file in files) { HandleImportSQL(session, sql_folder, file.Name); } }
public static bool CanHandleByName(CommandHandlerHelper helper, ICommandHandler handler) { return(helper.Command.Name.ToLower() == handler.GetName().ToLower()); }
public Task <ICommandResponse> Handle(EfetuarQuebraPontosExtratoCommand command, CancellationToken cancellationToken) { return(CommandHandlerHelper.ExecuteToResponse(() => extratoService.EfetuarQuebraPontos(command.ExtratoId, command.Pontos))); }
public Task <ICommandResponse> Handle(AlterarNomeParticipanteCommand command, CancellationToken cancellationToken) { return(CommandHandlerHelper.ExecuteToResponse(() => participanteService.AlterarNome(command.ParticipanteId, command.Nome))); }
public static void RemoveInstance(Session session, bool confirmed = false) { var wo = CommandHandlerHelper.GetLastAppraisedObject(session); if (wo == null) { return; } var landblock = (ushort)wo.Location.Landblock; var instances = DatabaseManager.World.GetCachedInstancesByLandblock(landblock); var instance = instances.FirstOrDefault(i => i.Guid == wo.Guid.Full); if (instance == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't find landblock_instance for {wo.WeenieClassId} - {wo.Name} (0x{wo.Guid})", ChatMessageType.Broadcast)); return; } var numChilds = instance.LandblockInstanceLink.Count; if (numChilds > 0 && !confirmed) { // get total numChilds iteratively numChilds = 0; foreach (var link in instance.LandblockInstanceLink) { numChilds += GetNumChilds(session, link, instances); } // require confirmation for parent objects var msg = $"Are you sure you want to delete this parent object, and {numChilds} child object{(numChilds != 1 ? "s" : "")}?"; session.Player.ConfirmationManager.EnqueueSend(new Confirmation_Custom(session.Player.Guid, () => RemoveInstance(session, true)), msg); return; } if (instance.IsLinkChild) { LandblockInstanceLink link = null; foreach (var parent in instances.Where(i => i.LandblockInstanceLink.Count > 0)) { link = parent.LandblockInstanceLink.FirstOrDefault(i => i.ChildGuid == instance.Guid); if (link != null) { parent.LandblockInstanceLink.Remove(link); break; } } if (link == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't find parent link for child {wo.WeenieClassId} - {wo.Name} (0x{wo.Guid})", ChatMessageType.Broadcast)); return; } } wo.DeleteObject(); foreach (var link in instance.LandblockInstanceLink) { RemoveChild(session, link, instances); } instances.Remove(instance); SyncInstances(session, landblock, instances); session.Network.EnqueueSend(new GameMessageSystemChat($"Removed {(instance.IsLinkChild ? "child " : "")}{wo.WeenieClassId} - {wo.Name} (0x{wo.Guid}) from landblock instances", ChatMessageType.Broadcast)); }
public async Task <ICommandResponse> Handle(CriarParticipanteCommand command, CancellationToken cancellationToken) { return(await CommandHandlerHelper.ExecuteToResponse( () => participanteService.AdicionarParticipante(command.Id, command.Nome, command.Email))); }
/// <summary> /// Converts a json file to sql file /// </summary> public static string json2sql(Session session, string folder, string json_filename, WeenieSQLWriter converter) { var json_file = folder + json_filename; // read json into lsd weenie var success = LifestonedLoader.TryLoadWeenie(json_file, out var weenie); if (!success) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to load {json_file}"); return(null); } // convert to ace weenie success = LifestonedConverter.TryConvert(weenie, out var output); if (!success) { CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {json_file}"); return(null); } // output to sql var sqlFolder = folder.Replace("json", "sql"); var di = new DirectoryInfo(sqlFolder); if (!di.Exists) { di.Create(); } var sqlFilename = ""; try { if (output.LastModified == DateTime.MinValue) { output.LastModified = DateTime.UtcNow; } sqlFilename = converter.GetDefaultFileName(output); var sqlFile = new StreamWriter(sqlFolder + sqlFilename); converter.CreateSQLDELETEStatement(output, sqlFile); sqlFile.WriteLine(); converter.CreateSQLINSERTStatement(output, sqlFile); var metadata = new Adapter.GDLE.Models.Metadata(weenie); if (metadata.HasInfo) { var jsonEx = JsonConvert.SerializeObject(metadata, LifestonedConverter.SerializerSettings); sqlFile.WriteLine($"\n/* Lifestoned Changelog:\n{jsonEx}\n*/"); } sqlFile.Close(); } catch (Exception e) { Console.WriteLine(e); CommandHandlerHelper.WriteOutputInfo(session, $"Failed to convert {json_file}"); return(null); } CommandHandlerHelper.WriteOutputInfo(session, $"Converted {json_filename} to {sqlFilename}"); return(sqlFilename); }
public Cd(CommandHandlerHelper cmdHelper, AntilStorageHelper storageHelper) { this.cmdHelper = cmdHelper; this.storageHelper = storageHelper; }
public void HandleRequest(Request request) { CommandHandlerHelper helper = new CommandHandlerHelper(request.Client, request); this.CommandManager.Handle(helper); }
private void Run(Session session, int biotasPerTest) { CommandHandlerHelper.WriteOutputInfo(session, $"Starting Shard Database Performance Tests.\nBiotas per test: {biotasPerTest}\nThis may take several minutes to complete...\nCurrent database queue count: {DatabaseManager.Shard.QueueCount}"); // Get the current queue wait time bool responseReceived = false; DatabaseManager.Shard.GetCurrentQueueWaitTime(result => { CommandHandlerHelper.WriteOutputInfo(session, $"Current database queue wait time: {result.TotalMilliseconds:N0} ms"); responseReceived = true; }); while (!responseReceived) { Thread.Sleep(1); } // Generate Individual WorldObjects var biotas = new Collection <(Biota biota, ReaderWriterLockSlim rwLock)>(); for (int i = 0; i < biotasPerTest; i++) { var worldObject = WorldObjectFactory.CreateNewWorldObject(testWeenies[i % testWeenies.Count]); biotas.Add((worldObject.Biota, worldObject.BiotaDatabaseLock)); } // Add biotasPerTest biotas individually long trueResults = 0; long falseResults = 0; var startTime = DateTime.UtcNow; var initialQueueWaitTime = TimeSpan.Zero; var totalQueryExecutionTime = TimeSpan.Zero; foreach (var biota in biotas) { DatabaseManager.Shard.SaveBiota(biota.biota, biota.rwLock, result => { if (result) { Interlocked.Increment(ref trueResults); } else { Interlocked.Increment(ref falseResults); } }, (queueWaitTime, queryExecutionTime) => { if (initialQueueWaitTime == TimeSpan.Zero) { initialQueueWaitTime = queueWaitTime; } totalQueryExecutionTime += queryExecutionTime; }); } while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < biotas.Count) { Thread.Sleep(1); } var endTime = DateTime.UtcNow; ReportResult(session, "individual add", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults); // Update biotasPerTest biotas individually if (session == null || SessionIsStillInWorld(session)) { ModifyBiotas(biotas); trueResults = 0; falseResults = 0; startTime = DateTime.UtcNow; initialQueueWaitTime = TimeSpan.Zero; totalQueryExecutionTime = TimeSpan.Zero; foreach (var biota in biotas) { DatabaseManager.Shard.SaveBiota(biota.biota, biota.rwLock, result => { if (result) { Interlocked.Increment(ref trueResults); } else { Interlocked.Increment(ref falseResults); } }, (queueWaitTime, queryExecutionTime) => { if (initialQueueWaitTime == TimeSpan.Zero) { initialQueueWaitTime = queueWaitTime; } totalQueryExecutionTime += queryExecutionTime; }); } while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < biotas.Count) { Thread.Sleep(1); } endTime = DateTime.UtcNow; ReportResult(session, "individual save", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults); } // Delete biotasPerTest biotas individually trueResults = 0; falseResults = 0; startTime = DateTime.UtcNow; initialQueueWaitTime = TimeSpan.Zero; totalQueryExecutionTime = TimeSpan.Zero; foreach (var biota in biotas) { DatabaseManager.Shard.RemoveBiota(biota.biota, biota.rwLock, result => { if (result) { Interlocked.Increment(ref trueResults); } else { Interlocked.Increment(ref falseResults); } }, (queueWaitTime, queryExecutionTime) => { if (initialQueueWaitTime == TimeSpan.Zero) { initialQueueWaitTime = queueWaitTime; } totalQueryExecutionTime += queryExecutionTime; }); } while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < biotas.Count) { Thread.Sleep(1); } endTime = DateTime.UtcNow; ReportResult(session, "individual remove", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults); if (session != null && !SessionIsStillInWorld(session)) { return; } // Generate Bulk WorldObjects biotas.Clear(); for (int i = 0; i < biotasPerTest; i++) { var worldObject = WorldObjectFactory.CreateNewWorldObject(testWeenies[i % testWeenies.Count]); biotas.Add((worldObject.Biota, worldObject.BiotaDatabaseLock)); } // Add biotasPerTest biotas in bulk trueResults = 0; falseResults = 0; startTime = DateTime.UtcNow; initialQueueWaitTime = TimeSpan.Zero; totalQueryExecutionTime = TimeSpan.Zero; DatabaseManager.Shard.SaveBiotasInParallel(biotas, result => { if (result) { Interlocked.Increment(ref trueResults); } else { Interlocked.Increment(ref falseResults); } }, (queueWaitTime, queryExecutionTime) => { if (initialQueueWaitTime == TimeSpan.Zero) { initialQueueWaitTime = queueWaitTime; } totalQueryExecutionTime += queryExecutionTime; }); while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < 1) { Thread.Sleep(1); } endTime = DateTime.UtcNow; ReportResult(session, "bulk add", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults); // Update biotasPerTest biotas in bulk if (session == null || SessionIsStillInWorld(session)) { ModifyBiotas(biotas); trueResults = 0; falseResults = 0; startTime = DateTime.UtcNow; initialQueueWaitTime = TimeSpan.Zero; totalQueryExecutionTime = TimeSpan.Zero; DatabaseManager.Shard.SaveBiotasInParallel(biotas, result => { if (result) { Interlocked.Increment(ref trueResults); } else { Interlocked.Increment(ref falseResults); } }, (queueWaitTime, queryExecutionTime) => { if (initialQueueWaitTime == TimeSpan.Zero) { initialQueueWaitTime = queueWaitTime; } totalQueryExecutionTime += queryExecutionTime; }); while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < 1) { Thread.Sleep(1); } endTime = DateTime.UtcNow; ReportResult(session, "bulk save", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults); } // Delete biotasPerTest biotas in bulk trueResults = 0; falseResults = 0; startTime = DateTime.UtcNow; initialQueueWaitTime = TimeSpan.Zero; totalQueryExecutionTime = TimeSpan.Zero; DatabaseManager.Shard.RemoveBiotasInParallel(biotas, result => { if (result) { Interlocked.Increment(ref trueResults); } else { Interlocked.Increment(ref falseResults); } }, (queueWaitTime, queryExecutionTime) => { if (initialQueueWaitTime == TimeSpan.Zero) { initialQueueWaitTime = queueWaitTime; } totalQueryExecutionTime += queryExecutionTime; }); while (Interlocked.Read(ref trueResults) + Interlocked.Read(ref falseResults) < 1) { Thread.Sleep(1); } endTime = DateTime.UtcNow; ReportResult(session, "bulk remove", biotasPerTest, (endTime - startTime), initialQueueWaitTime, totalQueryExecutionTime, trueResults, falseResults); if (session != null && !SessionIsStillInWorld(session)) { return; } CommandHandlerHelper.WriteOutputInfo(session, "Database Performance Tests Completed"); }
public TestHttp(CommandHandlerHelper cmdHelper) { this.cmdHelper = cmdHelper; }
public static void HandleCreateInst(Session session, params string[] parameters) { var loc = new Position(session.Player.Location); var param = parameters[0]; Weenie weenie = null; uint?parentGuid = null; var landblock = session.Player.CurrentLandblock.Id.Landblock; var firstStaticGuid = 0x70000000 | (uint)landblock << 12; if (parameters.Length > 1) { var allParams = string.Join(" ", parameters); var match = Regex.Match(allParams, @"-p ([\S]+) -c ([\S]+)", RegexOptions.IgnoreCase); if (match.Success) { var parentGuidStr = match.Groups[1].Value; param = match.Groups[2].Value; if (parentGuidStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { parentGuidStr = parentGuidStr.Substring(2); } if (!uint.TryParse(parentGuidStr, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var _parentGuid)) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't parse parent guid {match.Groups[1].Value}", ChatMessageType.Broadcast)); return; } parentGuid = _parentGuid; if (parentGuid <= 0xFFF) { parentGuid = firstStaticGuid | parentGuid; } } else if (parameters[1].StartsWith("-c", StringComparison.OrdinalIgnoreCase)) { // get parent from last appraised object var parent = CommandHandlerHelper.GetLastAppraisedObject(session); if (parent == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't find parent object", ChatMessageType.Broadcast)); return; } parentGuid = parent.Guid.Full; } } if (uint.TryParse(param, out var wcid)) { weenie = DatabaseManager.World.GetCachedWeenie(wcid); // wcid } else { weenie = DatabaseManager.World.GetCachedWeenie(param); // classname } if (weenie == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't find weenie {param}", ChatMessageType.Broadcast)); return; } // clear any cached instances for this landblock DatabaseManager.World.ClearCachedInstancesByLandblock(landblock); var instances = DatabaseManager.World.GetCachedInstancesByLandblock(landblock); // for link mode, ensure parent guid instance exists WorldObject parentObj = null; LandblockInstance parentInstance = null; if (parentGuid != null) { parentInstance = instances.FirstOrDefault(i => i.Guid == parentGuid); if (parentInstance == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't find landblock instance for parent guid 0x{parentGuid:X8}", ChatMessageType.Broadcast)); return; } parentObj = session.Player.CurrentLandblock.GetObject(parentGuid.Value); if (parentObj == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Couldn't find parent object 0x{parentGuid:X8}", ChatMessageType.Broadcast)); return; } } var nextStaticGuid = GetNextStaticGuid(landblock, instances); var maxStaticGuid = firstStaticGuid | 0xFFF; // manually specify a start guid? if (parameters.Length == 2) { if (uint.TryParse(parameters[1].Replace("0x", ""), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var startGuid)) { if (startGuid <= 0xFFF) { startGuid = firstStaticGuid | startGuid; } if (startGuid < firstStaticGuid || startGuid > maxStaticGuid) { session.Network.EnqueueSend(new GameMessageSystemChat($"Landblock instance guid {startGuid:X8} must be between {firstStaticGuid:X8} and {maxStaticGuid:X8}", ChatMessageType.Broadcast)); return; } var existing = instances.FirstOrDefault(i => i.Guid == startGuid); if (existing != null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Landblock instance guid {startGuid:X8} already exists", ChatMessageType.Broadcast)); return; } nextStaticGuid = startGuid; } } if (nextStaticGuid >= maxStaticGuid) { session.Network.EnqueueSend(new GameMessageSystemChat($"Landblock {landblock:X4} has reached the maximum # of static guids", ChatMessageType.Broadcast)); return; } // create and spawn object var wo = WorldObjectFactory.CreateWorldObject(weenie, new ObjectGuid(nextStaticGuid)); if (wo == null) { session.Network.EnqueueSend(new GameMessageSystemChat($"Failed to create new object for {weenie.ClassId} - {weenie.ClassName}", ChatMessageType.Broadcast)); return; } if (!wo.Stuck) { session.Network.EnqueueSend(new GameMessageSystemChat($"{weenie.ClassId} - {weenie.ClassName} is missing PropertyBool.Stuck, cannot spawn as landblock instance", ChatMessageType.Broadcast)); return; } // spawn as ethereal temporarily, to spawn directly on player position wo.Ethereal = true; wo.Location = new Position(loc); // even on flat ground, objects can sometimes fail to spawn at the player's current Z // Position.Z has some weird thresholds when moving around, but i guess the same logic doesn't apply when trying to spawn in... wo.Location.PositionZ += 0.05f; var isLinkChild = parentInstance != null; session.Network.EnqueueSend(new GameMessageSystemChat($"Creating new landblock instance {(isLinkChild ? "child object " : "")}@ {loc.ToLOCString()}\n{wo.WeenieClassId} - {wo.Name} ({nextStaticGuid:X8})", ChatMessageType.Broadcast)); if (!wo.EnterWorld()) { session.Network.EnqueueSend(new GameMessageSystemChat("Failed to spawn new object at this location", ChatMessageType.Broadcast)); return; } // create new landblock instance var instance = CreateLandblockInstance(wo, isLinkChild); instances.Add(instance); if (isLinkChild) { var link = new LandblockInstanceLink(); link.ParentGuid = parentGuid.Value; link.ChildGuid = wo.Guid.Full; link.LastModified = DateTime.Now; parentInstance.LandblockInstanceLink.Add(link); parentObj.LinkedInstances.Add(instance); // ActivateLinks? parentObj.SetLinkProperties(wo); parentObj.ChildLinks.Add(wo); wo.ParentLink = parentObj; } SyncInstances(session, landblock, instances); }
public void Handle(CommandHandlerHelper helper) { helper.Reply(enums.ResponseType.Response, "Pong"); }
public bool CanHandle(CommandHandlerHelper helper) { return(HandlerUtils.CanHandleByName(helper, this)); }