/// <summary> /// The constructor that has to be overwritten in the derived model classes /// </summary> /// <param name="TreeView">The TreeViewAdv control this model is used for</param> /// <param name="DisabledNames">the list of the nodes that shouldn't be shown</param> /// <param name="GrtList">The GRT list this model is representing</param> public DifferenceByNameGrtTreeModel(TreeViewAdv TreeView, List<String> DisabledNames, MySQL.Grt.TreeModelWrapper GrtTree, bool DynamicContextMenu) : base(TreeView, GrtTree, DynamicContextMenu) { model = GrtTree; treeControl = TreeView; disabledNames = DisabledNames; }
/// <summary> /// Конструктор класса Map /// </summary> /// <param name="sql"></param> public Map(MySQL sql) { this.sql = sql; id_room = -1; id_book = -1; day_calendar = DateTime.MinValue; }
public Client(MySQL sql) { id_client = 0; client = ""; e_mail = ""; phone = ""; address = ""; info = ""; this.sql = sql; }
public Connector create() { MySQL conn = new MySQL(); conn.Settings_Database = database; conn.Settings_Host = host; conn.Settings_Port = port; conn.Settings_User = username; conn.Settings_Pass = password; conn.Connect(); return conn; }
// End Other public SpellIconDBC(MainWindow window, MySQL.MySQL mySQLConn) { main = window; mySQL = mySQLConn; for (UInt32 i = 0; i < header.RecordCount; ++i) { body.records[i].ID = new UInt32(); body.records[i].Name = new UInt32(); } }
/// <summary> /// The constructor that has to be overwritten in the derived model classes /// </summary> /// <param name="TreeView">The TreeViewAdv control this model is used for</param> /// <param name="GrtList">The GRT list this model is representing</param> /// <param name="DynamicContextMenu">Use context menu definition provided by backend</param> protected GrtListModel(TreeViewAdv tree, MySQL.Grt.ListModelWrapper GrtList, bool DynamicContextMenu) : this() { grtList = GrtList; treeView = tree; if (DynamicContextMenu) { tree.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(); tree.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening); } }
/// <summary> /// The constructor that has to be overwritten in the derived model classes /// </summary> /// <param name="TreeView">The TreeViewAdv control this model is used for</param> /// <param name="GrtTree">The GRT tree this model is representing</param> /// <param name="DynamicContextMenu">Use context menu definition provided by backend</param> protected GrtTreeModel(TreeViewAdv TreeView, MySQL.Grt.TreeModelWrapper GrtTree, bool DynamicContextMenu) : this() { model = GrtTree; treeControl = TreeView; treeControl.Expanding += new EventHandler<TreeViewAdvEventArgs>(TreeViewExpanding); treeControl.Collapsing += new EventHandler<TreeViewAdvEventArgs>(TreeViewCollapsing); if (DynamicContextMenu) { treeControl.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(); treeControl.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening); } }
public Recargar() { mysql = new MySQL(); }
public static void LoginPlayer(Client player, string username, string password) { var userExist = MySQL.QueryResult( $"SELECT Username FROM Accounts WHERE Username='******' AND Password='******'"); if (userExist != null) { connection = new MySqlConnection(myConnectionString); command = connection.CreateCommand(); command.CommandText = "SELECT * FROM Accounts WHERE Username='******' AND Password='******'"; connection.Open(); Reader = command.ExecuteReader(); while (Reader.Read()) { int ID = Reader.GetInt32("ID"); string Username = Reader.GetString("Username"); int CharacterAmount = Reader.GetInt32("CharacterAmount"); player.setData("AccountID", ID); player.setData("AccountUsername", Username); player.setData("AccountPassword", password); player.setData("AccountCharacterAmount", CharacterAmount); } connection.Close(); LoadCharacters(player); int id1 = Convert.ToInt32(player.getData("Char1ID")); int id2 = Convert.ToInt32(player.getData("Char2ID")); int id3 = Convert.ToInt32(player.getData("Char3ID")); int id4 = Convert.ToInt32(player.getData("Char4ID")); int numcharacters = player.getData("AccountCharacterAmount"); string user = player.getData("AccountUsername"); string firstname1 = player.getData("Char1FirstName"); string lastname1 = player.getData("Char1LastName"); int gender1 = Convert.ToInt32(player.getData("Char1Gender")); string firstname2 = player.getData("Char2FirstName"); string lastname2 = player.getData("Char2LastName"); int gender2 = Convert.ToInt32(player.getData("Char2Gender")); string firstname3 = player.getData("Char3FirstName"); string lastname3 = player.getData("Char3LastName"); int gender3 = Convert.ToInt32(player.getData("Char3Gender")); string firstname4 = player.getData("Char4FirstName"); string lastname4 = player.getData("Char4LastName"); int gender4 = Convert.ToInt32(player.getData("Char4Gender")); string empty = "Empty"; string slot = "Slot"; if (numcharacters == 0) { API.shared.triggerClientEvent(player, "Menu_CharacterSelection", numcharacters, id1, user, empty, slot, empty, numcharacters, id2, user, empty, slot, empty, numcharacters, id3, user, empty, slot, empty, numcharacters, id4, user, empty, slot, empty); } else if (numcharacters == 1) { API.shared.triggerClientEvent(player, "Menu_CharacterSelection", numcharacters, id1, user, firstname1, lastname1, gender1, numcharacters, id2, user, empty, slot, empty, numcharacters, id3, user, empty, slot, empty, numcharacters, id4, user, empty, slot, empty); } else if (numcharacters == 2) { API.shared.triggerClientEvent(player, "Menu_CharacterSelection", numcharacters, id1, user, firstname1, lastname1, gender1, numcharacters, id2, user, firstname2, lastname2, gender2, numcharacters, id3, user, empty, slot, empty, numcharacters, id4, user, empty, slot, empty); } else if (numcharacters == 3) { API.shared.triggerClientEvent(player, "Menu_CharacterSelection", numcharacters, id1, user, firstname1, lastname1, gender1, numcharacters, id2, user, firstname2, lastname2, gender2, numcharacters, id3, user, firstname3, lastname3, gender3, numcharacters, id4, user, empty, slot, empty); } else if (numcharacters == 4) { API.shared.triggerClientEvent(player, "Menu_CharacterSelection", numcharacters, id1, user, firstname1, lastname1, gender1, numcharacters, id2, user, firstname2, lastname2, gender2, numcharacters, id3, user, firstname3, lastname3, gender3, numcharacters, id4, user, firstname4, lastname4, gender4); } player.freeze(true); connection.Close(); } else { API.shared.triggerClientEvent(player, "AccountLogin"); } }
public static Connector connectorCreate(bool persist) { MySQL conn = new MySQL(); conn.Settings_Host = connHost; conn.Settings_Port = connPort; conn.Settings_Database = connDatabase; conn.Settings_User = connUsername; conn.Settings_Pass = connPassword; conn.Settings_Connection_String += "Charset=utf8;"; if (persist) { conn.Settings_Timeout_Connection = 864000; // 10 days conn.Settings_Timeout_Command = 3600; // 1 hour } conn.Logging_Enabled = true; conn.Connect(); return conn; }
private void dtGrid_CellClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; if (e.ColumnIndex == dtGrid.Columns["Select"].Index && e.RowIndex >= 0) { if (selectedIDs.Contains(dtGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString())) { selectedIDs.Remove(dtGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString()); } else { selectedIDs.Add(dtGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString()); } } if (e.ColumnIndex == dtGrid.Columns["View"].Index && e.RowIndex >= 0) { using (NewCase form = new NewCase(dtGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString())) { DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { //LoadData(); } } } if (e.ColumnIndex == dtGrid.Columns["Order Intake"].Index && e.RowIndex >= 0) { using (OrderIntakeForm form = new OrderIntakeForm(dtGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString())) { DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { //LoadData(); } } } try { if (e.ColumnIndex == dtGrid.Columns["Delete"].Index && e.RowIndex >= 0) { if (MessageBox.Show("YES or No?", "Are you sure you want to delete this Order? ", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { string Query = "DELETE from orders WHERE id ='" + dtGrid.Rows[e.RowIndex].Cells["ID"].Value.ToString() + "'"; MySQL.Query(Query); Queries q = new Queries(Guid.NewGuid().ToString(), Helper.UserName, Helper.CleanString(MySQL.Insert(Query)), "false", DateTime.Now.ToString("dd-MM-yyyy H:m:s"), Helper.CompanyID); MySQL.Insert(q); MessageBox.Show("Information deleted"); LoadData(); } } } catch { } }
/// <summary> /// Конструктор класса резервации /// </summary> /// <param name="sql">подключение к БД</param> public Book(MySQL sql) { id_book = 0; this.sql = sql; }
private void Page_Load(object sender, System.EventArgs e) { // Session["CustomerID"] = "10000"; // Session["CompanyID"] = "__S09"; this.txtTeachers.Attributes["onchange"] = "javascript:SetField();"; this.txtStudents.Attributes["onchange"] = "javascript:SetStudentField();"; if (Session["CustomerID"] == null) { Response.Redirect("Default.aspx"); } else { // this.AddKeepAlive(); oMySql = new MySQL(ConnectionType.NonUnique); oCustomer = new Customer(Session["CompanyID"].ToString(), oMySql); oCustomer.Find(Session["CustomerID"].ToString()); oTeacher = new Teacher(oCustomer.CompanyID, oCustomer.ID, oMySql); oStudent = new Student(oCustomer.CompanyID, oCustomer.ID, oMySql); oOrder = new Order(oCustomer.CompanyID, oMySql); txtName.Text = oCustomer.Name; if (txtAction.Value.ToString() == "Edit") { if (oOrder.Find(Convert.ToInt32(txtValue.Value.ToString()))) { txtTeacherID.Value = oOrder.TeacherID.ToString(); txtStudentID.Value = oOrder.StudentID.ToString(); } } LoadTeachers(); if (Page.IsPostBack || txtAction.Value.ToString() == "Edit") { if (IsPostBack && Request.Form["__EVENTTARGET"].ToString() == "txtTeachers") { txtStudentID.Value = ""; } LoadStudents(); LoadOrder(); txtAction.Value = ""; } if (IsPostBack) { if (Request.Form["__EVENTTARGET"].ToString() == "txtTeachers") { if (txtTeachers.Items[0].Value.ToString() == "-1") { txtTeachers.Items.RemoveAt(0); } } if (Request.Form["__EVENTTARGET"].ToString() == "txtStudents") { DeleteFirstItem(); } } if (!IsPostBack) { txtDate.Value = DateTime.Today; } } }
// End DBCs public SpellFocusObject(MainWindow window, MySQL.MySQL mySQLConn) { main = window; mySQL = mySQLConn; for (UInt32 i = 0; i < header.RecordCount; ++i) { body.records[i].ID = new UInt32(); body.records[i].Name = new UInt32[16]; body.records[i].Flags = new UInt32(); } if (!File.Exists("DBC/SpellFocusObject.dbc")) { main.HandleErrorMessage("SpellFocusObject.dbc was not found!"); return; } FileStream fileStream = new FileStream("DBC/SpellFocusObject.dbc", FileMode.Open); int count = Marshal.SizeOf(typeof(DBC_Header)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); header = (DBC_Header)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBC_Header)); handle.Free(); body.records = new SpellFocusObject_DBC_Record[header.RecordCount]; for (UInt32 i = 0; i < header.RecordCount; ++i) { count = Marshal.SizeOf(typeof(SpellFocusObject_DBC_Record)); readBuffer = new byte[count]; reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); body.records[i] = (SpellFocusObject_DBC_Record)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(SpellFocusObject_DBC_Record)); handle.Free(); } body.StringBlock = Encoding.UTF8.GetString(reader.ReadBytes(header.StringBlockSize)); reader.Close(); fileStream.Close(); body.lookup = new List<SpellFocusObjectLookup>(); int boxIndex = 1; main.RequiresSpellFocus.Items.Add("None"); SpellFocusObjectLookup t; t.ID = 0; t.offset = 0; t.stringHash = "None".GetHashCode(); t.comboBoxIndex = 0; body.lookup.Add(t); for (UInt32 i = 0; i < header.RecordCount; ++i) { int offset = (int)body.records[i].Name[0]; if (offset == 0) { continue; } int returnValue = offset; string toAdd = ""; while (body.StringBlock[offset] != '\0') { toAdd += body.StringBlock[offset++]; } SpellFocusObjectLookup temp; temp.ID = (int)body.records[i].ID; temp.offset = returnValue; temp.stringHash = toAdd.GetHashCode(); temp.comboBoxIndex = boxIndex; main.RequiresSpellFocus.Items.Add(toAdd); body.lookup.Add(temp); boxIndex++; } }
public static bool InitDB() { try { if (ServerSettings.DatabaseType.Trim().ToUpper() == "SQLSERVER") { if (!SQLServer.DatabaseAlreadyExists()) { logger.Error("Database: {0} does not exist", ServerSettings.DatabaseName); SQLServer.CreateDatabase(); Thread.Sleep(3000); } JMMService.CloseSessionFactory(); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing; ISessionFactory temp = JMMService.SessionFactory; ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema; SQLServer.CreateInitialSchema(); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema; SQLServer.UpdateSchema(); PopulateInitialData(); DatabaseHelper.CreateInitialCustomTags(); return(true); } else if (ServerSettings.DatabaseType.Trim().ToUpper() == "SQLITE") { ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateDatabase; SQLite.CreateDatabase(); JMMService.CloseSessionFactory(); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing; ISessionFactory temp = JMMService.SessionFactory; ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema; SQLite.CreateInitialSchema(); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema; SQLite.UpdateSchema(); PopulateInitialData(); DatabaseHelper.CreateInitialCustomTags(); return(true); } else if (ServerSettings.DatabaseType.Trim().ToUpper() == "MYSQL") { logger.Trace("Database - Creating Database..."); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateDatabase; MySQL.CreateDatabase(); logger.Trace("Initializing Session Factory..."); JMMService.CloseSessionFactory(); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_Initializing; ISessionFactory temp = JMMService.SessionFactory; logger.Trace("Database - Creating Initial Schema..."); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_CreateSchema; MySQL.CreateInitialSchema(); logger.Trace("Database - Applying Schema Patches..."); ServerState.Instance.CurrentSetupStatus = JMMServer.Properties.Resources.Database_ApplySchema; MySQL.UpdateSchema(); //MySQL.UpdateSchema_Fix(); PopulateInitialData(); DatabaseHelper.CreateInitialCustomTags(); return(true); } return(false); } catch (Exception ex) { logger.ErrorException("Could not init database: " + ex.ToString(), ex); return(false); } }
protected GrtListModel(TreeViewAdv ListView, MySQL.Grt.ListModelWrapper GrtList, NodeIcon NodeIcon, bool DynamicContextMenu) : this(ListView, GrtList, DynamicContextMenu) { nodeIcon = NodeIcon; // Ensure that the VirtualMode is enabled nodeIcon.VirtualMode = true; // Assign virtual value events for displaying and processing the edited value content nodeIcon.ValueNeeded += new EventHandler<NodeControlValueEventArgs>(IconNeeded); }
public SimpleGrtListModel(TreeViewAdv tree, MySQL.Grt.ListModelWrapper grtList, NodeIcon nodeIcon, bool dynamicContextMenu) : base(tree, grtList, nodeIcon, dynamicContextMenu) { this.grtList = grtList; treeView = tree; }
// End DBCs public AreaGroup(MainWindow window, MySQL.MySQL mySQLConn) { main = window; mySQL = mySQLConn; for (UInt32 i = 0; i < header.RecordCount; ++i) { body.records[i].ID = new UInt32(); body.records[i].AreaID = new UInt32[6]; body.records[i].NextGroup = new UInt32(); } if (!File.Exists("DBC/AreaGroup.dbc")) { main.HandleErrorMessage("AreaGroup.dbc was not found!"); return; } FileStream fileStream = new FileStream("DBC/AreaGroup.dbc", FileMode.Open); int count = Marshal.SizeOf(typeof(DBC_Header)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); header = (DBC_Header)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBC_Header)); handle.Free(); body.records = new AreaGroup_DBC_Record[header.RecordCount]; for (UInt32 i = 0; i < header.RecordCount; ++i) { count = Marshal.SizeOf(typeof(AreaGroup_DBC_Record)); readBuffer = new byte[count]; reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); body.records[i] = (AreaGroup_DBC_Record)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(AreaGroup_DBC_Record)); handle.Free(); } reader.Close(); fileStream.Close(); body.lookup = new List<AreaGroupLookup>(); int boxIndex = 1; main.AreaGroup.Items.Add(0); AreaGroupLookup t; t.ID = 0; t.comboBoxIndex = 0; body.lookup.Add(t); for (UInt32 i = 0; i < header.RecordCount; ++i) { int id = (int)body.records[i].ID; AreaGroupLookup temp; temp.ID = id; temp.comboBoxIndex = boxIndex; main.AreaGroup.Items.Add(id); body.lookup.Add(temp); boxIndex++; } }
public SimpleGrtTreeModel(TreeViewAdv TreeView, MySQL.Grt.TreeModelWrapper GrtTree, NodeStateIcon nodeIcon, bool DynamicContextMenu) : base(TreeView, GrtTree, nodeIcon, DynamicContextMenu) { model = GrtTree; treeControl = TreeView; }
/// <summary> /// Used to retrieve and validate the database settings to be used by the installer process; this section is skipped /// if the database settings are specified in the web.config already. /// </summary> /// <param name="request"></param> /// <param name="response"></param> /// <param name="content"></param> public static void pageSetup(ref UberCMS.Misc.PageElements pageElements, HttpRequest request, HttpResponse response, ref StringBuilder content) { #if INSTALLED response.Redirect(pageElements["BASE_URL"]); #else // Check the database is not already installed if (dbSettings != null) // -- Skip to the installer page response.Redirect(pageElements["URL"] + "/install"); string error = null; // Check for postback string dbHost = request.Form["db_host"]; string dbDatabase = request.Form["db_database"]; string dbUsername = request.Form["db_username"]; string dbPassword = request.Form["db_password"]; string dbPort = request.Form["db_port"]; string mailHost = request.Form["mail_host"]; string mailPort = request.Form["mail_port"]; string mailUsername = request.Form["mail_username"]; string mailPassword = request.Form["mail_password"]; string mailAddress = request.Form["mail_address"]; string privacyIndexing = request.Form["privacy_indexing"]; if (dbHost != null && dbDatabase != null && dbUsername != null && dbPassword != null && dbPort != null && mailHost != null && mailPort != null && mailUsername != null && mailPassword != null && mailAddress != null) { // Validate database settings try { MySQL conn = new MySQL(); conn.Settings_Host = dbHost; conn.Settings_Port = int.Parse(dbPort); conn.Settings_User = dbUsername; conn.Settings_Pass = dbPassword; conn.Connect(); // Create the database if it doesn't exist conn.Query_Execute("CREATE DATABASE IF NOT EXISTS `" + Utils.Escape(dbDatabase) + "`"); } catch (Exception ex) { error = "MySQL settings failed - check for typo's - raw error: `" + ex.Message + "`, `" + ex.GetBaseException().Message + "`!"; } if (error == null) { // Test the e-mail settings if non-empty if (mailHost.Length != 0 && mailPort.Length != 0 && mailUsername.Length != 0 && mailAddress.Length != 0) { // Validate e-mail settings int mailPortParsed; if (mailHost.Length == 0) error = "E-mail host cannot be empty!"; else if (mailPort.Length == 0) error = "E-mail port cannot be empty!"; else if (!int.TryParse(mailPort, out mailPortParsed) || mailPortParsed < 1 || mailPortParsed > UInt16.MaxValue) error = "Invalid mail port!"; else if (mailUsername.Length == 0) error = "E-mail username cannot be empty!"; else if (mailAddress.Length == 0) error = "E-mail address cannot be empty!"; else { try { SmtpClient client = new SmtpClient(); client.Host = mailHost; client.Port = mailPortParsed; client.Credentials = new System.Net.NetworkCredential(mailUsername, mailPassword); client.Send("*****@*****.**", mailAddress, "Test message", "Test message to test CMS settings."); } catch (Exception ex) { error = "E-mail settings failed - check for typo's - raw error: `" + ex.Message + "`, `" + ex.GetBaseException().Message + "`!"; } } } if (error == null) { error = "success"; try { // Write the settings - they work! // -- CMS.config (db & mail) try { StringBuilder cmsConfig = new StringBuilder(); XmlWriter writer = XmlWriter.Create(cmsConfig); // Start document writer.WriteStartDocument(); writer.WriteStartElement("settings"); // Database writer.WriteStartElement("db"); writer.WriteStartElement("host"); writer.WriteCData(dbHost); writer.WriteEndElement(); writer.WriteStartElement("port"); writer.WriteCData(dbPort); writer.WriteEndElement(); writer.WriteStartElement("database"); writer.WriteCData(dbDatabase); writer.WriteEndElement(); writer.WriteStartElement("username"); writer.WriteCData(dbUsername); writer.WriteEndElement(); writer.WriteStartElement("password"); writer.WriteCData(dbPassword); writer.WriteEndElement(); writer.WriteEndElement(); // E-mail writer.WriteStartElement("mail"); writer.WriteStartElement("host"); writer.WriteCData(mailHost); writer.WriteEndElement(); writer.WriteStartElement("port"); writer.WriteCData(mailPort); writer.WriteEndElement(); writer.WriteStartElement("username"); writer.WriteCData(mailUsername); writer.WriteEndElement(); writer.WriteStartElement("password"); writer.WriteCData(mailPassword); writer.WriteEndElement(); writer.WriteStartElement("address"); writer.WriteCData(mailAddress); writer.WriteEndElement(); writer.WriteEndElement(); // End document writer.WriteEndElement(); writer.WriteEndDocument(); // Flush and write to file writer.Flush(); writer.Close(); File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\CMS.config", cmsConfig.ToString()); } catch(Exception ex2) { throw new Exception("Failed to create CMS.config - " + ex2.Message + "!"); } // -- Robots/search engine indexing try { if (privacyIndexing != null) File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\robots.txt", "Disallow: /"); } catch { throw new Exception("Failed to create robots file for privacy protection against search engine indexing."); } // Redirect to the installer page response.Redirect(pageElements["URL"] + "/install"); } catch (Exception ex) { error = ex.Message; } } } } // Output page content.Append( templates[TEMPLATES_KEY]["general_settings"] .Replace("%ERROR%", error != null ? templates[TEMPLATES_KEY]["error"].Replace("%ERROR%", HttpUtility.HtmlEncode(error)) : string.Empty) .Replace("%DB_HOST%", HttpUtility.HtmlEncode(dbHost ?? "localhost")) .Replace("%DB_PORT%", HttpUtility.HtmlEncode(dbPort ?? "3306")) .Replace("%DB_USERNAME%", HttpUtility.HtmlEncode(dbUsername ?? "root")) .Replace("%DB_PASSWORD%", HttpUtility.HtmlEncode(dbPassword ?? string.Empty)) .Replace("%DB_DATABASE%", HttpUtility.HtmlEncode(dbDatabase ?? "ubercms")) .Replace("%MAIL_HOST%", HttpUtility.HtmlEncode(mailHost)) .Replace("%MAIL_PORT%", HttpUtility.HtmlEncode(mailPort)) .Replace("%MAIL_USERNAME%", HttpUtility.HtmlEncode(mailUsername)) .Replace("%MAIL_PASSWORD%", HttpUtility.HtmlEncode(mailPassword)) .Replace("%MAIL_ADDRESS%", HttpUtility.HtmlEncode(mailAddress)) .Replace("%PRIVACY_INDEXING%", privacyIndexing != null ? " checked" : string.Empty) ); pageElements["TITLE"] = "General Settings"; #endif }
void Start() { mysql = GetComponent <MySQL>(); }
void editorTabControl_TabClosing(object sender, MySQL.Controls.TabClosingEventArgs e) { Logger.LogDebug("WQE.net", 1, "About to close tab: " + e.page.Text + "\n"); // Any docked app view (plugin)? if (e.page.Tag is AppViewDockContent) e.canClose = (e.page.Tag as AppViewDockContent).CanCloseDocument(); else { // One of the object editors. ITabDocument tabDocument = mainContentTabControl.ActiveDocument; if (tabDocument is IWorkbenchDocument) e.canClose = (tabDocument as IWorkbenchDocument).CanCloseDocument(); } Logger.LogDebug("WQE.net", 1, "Can close tab: " + e.canClose + "\n"); }
private void button4_Click(object sender, EventArgs e) { string Query = "UPDATE company SET sync ='false'"; MySQL.Query(Query); }
private void bottomTabControl_TabClosed(object sender, MySQL.Controls.TabClosedEventArgs e) { if (bottomTabControl.TabCount == 0) contentSplitContainer.Panel2Collapsed = true; ITabDocument document = (sender as FlatTabControl).DocumentFromPage(e.page); CloseTabDocument(document); }
public override async Task Process() { if (Message.StartsWith("/")) { switch (Message.Split(' ')[0]) { case "/help": { await Resources.Gateway.Send(new GlobalChatLineMessage(Device) { Message = "Available commands:\n\n/help\n -> List of all commands.\n/rename\n -> Change your name again.\n/replay\n -> Watch a random replay.\n/prebase [level]\n -> Load a premade base from level 1 to 6.\n/reset\n -> Reset your village and start from beginning.\n/wall [level]\n -> Set the level of all walls.", Name = "DebugManager", ExpLevel = 100, League = 16, AccountId = 0 }); break; } case "/prebase": { var lvl = Convert.ToInt32(Message.Split(' ')[1]); if (lvl > 0 && lvl < 7) { Device.Player.LogicGameObjectManager.Json = Resources.Levels.Prebases[lvl - 1]; Device.Player.HeroManager.Clear(); Device.Player.Units.Troops.Clear(); Device.Player.Units.Spells.Clear(); await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); await Resources.Gateway.Send(new GlobalChatLineMessage(Device) { Message = $"Base {lvl} has been set.", Name = "DebugManager", ExpLevel = 100, League = 16 }); } break; } case "/reset": { Device.Player.LogicGameObjectManager.Json = Resources.Levels.StartingHome; Device.Player.Achievements.Clear(); Device.Player.HeroManager.Clear(); Device.Player.Shield.RemoveShield(); Device.Player.Units.Spells.Clear(); Device.Player.Units.Troops.Clear(); await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); await Resources.Gateway.Send(new GlobalChatLineMessage(Device) { Message = "Village has been set to default.", Name = "DebugManager", ExpLevel = 100, League = 16 }); break; } case "/rename": { Device.Player.TutorialSteps = 10; Device.Player.ExpLevel = 1; await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); break; } case "/replay": { var replay = await MySQL.GetRandomReplay(); if (replay != null) { await Resources.Gateway.Send(new HomeBattleReplayDataMessage(Device) { Replay = replay }); } else { await Resources.Gateway.Send(new HomeBattleReplayFailedMessage(Device)); } break; } case "/wall": { var lvl = Convert.ToInt32(Message.Split(' ')[1]); if (lvl > 0 && lvl < 12) { foreach (var building in Device.Player.LogicGameObjectManager.Buildings) { if (building.Data != 1000010) { continue; } building.Level = lvl - 1; } await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); await Resources.Gateway.Send(new GlobalChatLineMessage(Device) { Message = $"Wall level set to {lvl}.", Name = "DebugManager", ExpLevel = 100, League = 16 }); } break; } default: { await Resources.Gateway.Send(new GlobalChatLineMessage(Device) { Message = "Invalid Command. Type '/help' for a list of all commands.", Name = "DebugManager", ExpLevel = 100, League = 16 }); break; } } } else if ((DateTime.Now - Device.Player.LastChatMessage).TotalSeconds >= 1.0) { if (!string.IsNullOrEmpty(Message)) { await Resources.ChatManager.Process(new GlobalChatEntry { Message = Message, SenderName = Device.Player.Name, SenderId = Device.Player.AccountId, SenderExpLevel = Device.Player.ExpLevel, SenderLeague = LogicUtils.GetLeagueByScore(Device.Player.Score) }); Device.Player.LastChatMessage = DateTime.Now; } } }
public Calendar(MySQL sql) { this.sql = sql; }
static void Main(string[] args) { try { IFileSystem iFileSystem = new FileSystem(); INetwork iDownloader = new Downloader(); ILogger iLogger = new Logger("/home/brush/wrf/log.txt"); IProcessLauncher iProcess = new ProcessLauncher(); IEnvironment iEnvironment = new WrfSharp.Runner.Implementations.Environment(); ProcessLock lockFile = ProcessLock.TryLock(); if (lockFile != null) { using (lockFile) { string connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString; IDatabase iDatabase = MySQL.OpenConnection(connectionString); iLogger.Log("Testing DB connectivity..."); if (!iDatabase.TestConnection()) { iLogger.LogLine("....Connection failed. Check connection string."); } else { iLogger.LogLine("....Connection succeeded."); } List <PhysicsConfigurationProcessed> physicsConfigs = LoadPhysicsConfigurationsFromConfiguration(); iLogger.LogLine($"Loading configuration..."); WrfConfiguration config = LoadConfigurationFromAppSettings(iLogger); iLogger.LogLine("...done"); string stateText = "Prepping"; _timer = new Timer(delegate(object state) { iDatabase.Checkin(stateText, DateTime.Now); }, null, 0, 1000 * 60); if (args.Length > 0 && args[0].ToLower() == "nodownload") { iLogger.LogLine("Downloading of new data skipped..."); } else { PrepStage(iFileSystem, iDownloader, iLogger, iProcess, config); } Random rand = new Random(); physicsConfigs = physicsConfigs.OrderBy(m => rand.Next()).ToList(); // infinity if -1 if (config.MaximumNumberOfRuns == -1) { config.MaximumNumberOfRuns = int.MaxValue; } stateText = "Computing"; for (int c = 0; c < config.MaximumNumberOfRuns && c < physicsConfigs.Count; c++) { PhysicsConfigurationProcessed physicsConfig = physicsConfigs[c]; ComputeStage(iFileSystem, iLogger, iProcess, iEnvironment, iDatabase, config, physicsConfig); } iDatabase.Checkin("Done", DateTime.Now); } } else { //iLogger.LogLine("WrfSharp appears to be running already, or port 666 is in use."); } } catch (Exception ex) { File.AppendAllText("crash.txt", ex.ToString()); } }
public override void RefreshGUI(MySQL.Workbench.RefreshType refresh, String str, IntPtr ptr) { }
public Login() { connect = new MySQL(); }
/// <summary> /// The constructor that has to be overwritten in the derived model classes /// </summary> /// <param name="TreeView">The TreeViewAdv control this model is used for</param> /// <param name="GrtTree">The GRT tree this model is representing</param> /// <param name="StateIcon">The NodeStateIcon Node Control that displays the icon</param> /// <param name="DynamicContextMenu">Use context menu definition provided by backend</param> protected GrtTreeModel(TreeViewAdv TreeView, MySQL.Grt.TreeModelWrapper GrtTree, Aga.Controls.Tree.NodeControls.NodeStateIcon NodeStateIcon, bool DynamicContextMenu) : this(TreeView, GrtTree, DynamicContextMenu) { nodeStateIcon = NodeStateIcon; if (nodeStateIcon != null) { // Ensure that the VirtualMode is enabled nodeStateIcon.VirtualMode = true; // Assign virtual value events for displaying and processing the edited value content nodeStateIcon.ValueNeeded += new EventHandler<NodeControlValueEventArgs>(StateIconNeeded); } }
private void Page_Load(object sender, System.EventArgs e) { // this.warpGrid.AddLinkedRequestTrigger("butAddItem"); if (Session["CustomerID"] == null) { Response.Redirect("Default.aspx"); } else { this.AddKeepAlive(); Global.oMySql.Close(ConnectionType.Unique); oMySql = new MySQL(ConnectionType.NonUnique); oCustomer = new Customer(Session["CompanyID"].ToString()); oCustomer.oMySql = oMySql; oCustomer.Find(Session["CustomerID"].ToString()); oCustomerCS = new Customer.CustomerCS(oCustomer.CompanyID); oCustomerCS.oMySql = oMySql; oCustomerCS.Find(oCustomer.ID); oBrochure = new Brochure(oCustomer.CompanyID); oBrochure.oMySql = oMySql; if (!this.IsPostBack) { if (oCustomerCS.Goal == 0) { txtGoal.Text = "10"; } else { txtGoal.Text = oCustomerCS.Goal.ToString(); } if (oCustomerCS.EarlyBirdDate == Global.DNull) { txtEarlyBirdDate.Value = oCustomer.StartDate.AddDays(7); } else { txtEarlyBirdDate.Value = oCustomerCS.EarlyBirdDate.ToString("MM/dd/yyyy"); } } txtName.Text = oCustomer.Name; txtAddress.Text = oCustomer.Address + " " + oCustomer.City + " " + oCustomer.State + ", " + oCustomer.ZipCode; txtChairperson.Text = oCustomer.Chairperson; txteMail.Text = oCustomer.eMail; txtFax.Text = oCustomer.FaxNumber != ""? string.Format("{0:(###)-###-####}", double.Parse(oCustomer.FaxNumber)):""; txtPhone.Text = oCustomer.PhoneNumber != ""?string.Format("{0:(###)-###-####}", double.Parse(oCustomer.PhoneNumber)):""; oBrochure.Find(oCustomer.BrochureID); txtBrochure.Text = oCustomer.BrochureID + " - " + oBrochure.Description; txtProfit.Text = oCustomer.ProfitPercent.ToString(); txtStartDate.Text = (oCustomer.StartDate == Global.DNull)?"":oCustomer.StartDate.ToString("MM/dd/yyyy"); txtEndDate.Text = (oCustomer.EndDate == Global.DNull) ? "" : oCustomer.EndDate.ToString("MM/dd/yyyy"); txtPickUpDate.Text = (oCustomer.PickUpDate == Global.DNull) ? "" : oCustomer.PickUpDate.ToString("MM/dd/yyyy"); txtDeliveryDate.Text = (oCustomer.DeliveryDate == Global.DNull) ? "" : oCustomer.DeliveryDate.ToString("MM/dd/yyyy"); txtParentPickUpDate.Text = (oCustomer.ParentPickUpDate == Global.DNull) ? "" : oCustomer.ParentPickUpDate.ToString("MM/dd/yyyy"); // txtItemsDelivery.Text = oCustomer.NoItems.ToString(); oMySql.Dispose(); } }
// End DBCs public SpellRange(MainWindow window, MySQL.MySQL mySQLConn) { main = window; mySQL = mySQLConn; for (UInt32 i = 0; i < header.RecordCount; ++i) { body.records[i].ID = new UInt32(); body.records[i].MinimumRangeHostile = new float(); body.records[i].MinimumRangeFriend = new float(); body.records[i].MaximumRangeHostile = new float(); body.records[i].MaximumRangeFriend = new float(); body.records[i].Type = new Int32(); body.records[i].Name = new UInt32[16]; body.records[i].NameFlags = new UInt32(); body.records[i].ShortName = new UInt32[16]; body.records[i].ShortNameFlags = new UInt32(); } if (!File.Exists("DBC/SpellRange.dbc")) { main.HandleErrorMessage("SpellRange.dbc was not found!"); return; } FileStream fileStream = new FileStream("DBC/SpellRange.dbc", FileMode.Open); int count = Marshal.SizeOf(typeof(DBC_Header)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); header = (DBC_Header)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBC_Header)); handle.Free(); body.records = new SpellRange_DBC_Record[header.RecordCount]; for (UInt32 i = 0; i < header.RecordCount; ++i) { count = Marshal.SizeOf(typeof(SpellRange_DBC_Record)); readBuffer = new byte[count]; reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); body.records[i] = (SpellRange_DBC_Record)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(SpellRange_DBC_Record)); handle.Free(); } body.StringBlock = Encoding.UTF8.GetString(reader.ReadBytes(header.StringBlockSize)); reader.Close(); fileStream.Close(); body.lookup = new List<SpellRangeLookup>(); int boxIndex = 0; for (UInt32 i = 0; i < header.RecordCount; ++i) { int offset = (int)body.records[i].Name[0]; int MinimumRangeHostile = (int)body.records[i].MinimumRangeHostile; int MaximumRangeHostile = (int)body.records[i].MaximumRangeHostile; int MinimumRangeFriend = (int)body.records[i].MinimumRangeFriend; int MaximumRangeFriend = (int)body.records[i].MaximumRangeFriend; if (offset == 0) { continue; } int returnValue = offset; string toAdd = ""; while (body.StringBlock[offset] != 0) { toAdd += body.StringBlock[offset++]; } SpellRangeLookup temp; temp.ID = (int)body.records[i].ID; temp.comboBoxIndex = boxIndex; main.Range.Items.Add(toAdd + "\t\t - " + "Hostile: " + MinimumRangeHostile + " - " + MaximumRangeHostile + "\t Friend: " + MinimumRangeFriend + " - " + MaximumRangeFriend); body.lookup.Add(temp); boxIndex++; } }
public void ContextUpdate() { //Attempt to connect to database if (Model.CheckSingleProperty("SQL")) { string db_type = ""; Model.GetSingleProperty("SQL", out db_type); switch (db_type) { case "MySQL": if (!Model.CheckSingleProperty("SelectedDatabase")) { try { MySQL mySql; //Connect to SQL server string server, username, password; server = Model.GetSingleProperty("server", out server); username = Model.GetSingleProperty("username", out username); password = Model.GetSingleProperty("password", out password); mySql = new MySQL(server, username, password); //get SQL tables information List <object> databases = new List <object>(mySql.GetDatabases()); Model.AddMultiProperty("databases", databases); //Update form with new information Form f = new form_SelectDatabase(Model, this); f.Show(); } catch (Exception) { throw; } } else { try { MySQL mySql; //Connect to SQL server string server, username, password, database; server = Model.GetSingleProperty("server", out server); username = Model.GetSingleProperty("username", out username); password = Model.GetSingleProperty("password", out password); database = Model.GetSingleProperty("SelectedDatabase", out database); mySql = new MySQL(server, username, password, database); //update database with database name mySql.updateDatabase(); //get SQL information List <object> storedProcedures = new List <object>(mySql.GetProcedures()); Model.AddMultiProperty("storedProcedures", storedProcedures); List <object> functions = new List <object>(mySql.GetFunctions()); Model.AddMultiProperty("functions", functions); List <object> views = new List <object>(mySql.GetViews()); Model.AddMultiProperty("views", views); //Update Titles string title; Model.GetSingleProperty("SelectedDatabase", out title); lbl_CurrentDB.Text = title; //Update form with new information Form f = new form_Root(Model); f.TopLevel = false; f.Parent = tabRoot; f.Show(); } catch (Exception) { throw; } } break; case "TSQL": if (Model.CheckSingleProperty("SelectedDatabase")) { //Connect to DB and get all data SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder("Data Source = (local); Integrated Security = True"); TSQL TSQL = new TSQL(builder); //Update Titles string title; Model.GetSingleProperty("SelectedDatabase", out title); lbl_CurrentDB.Text = title; TSQL.SetSchema(title); List <object> storedProcedures = new List <object>(TSQL.GetProcedures()); Model.AddMultiProperty("storedProcedures", storedProcedures); List <object> functions = new List <object>(TSQL.GetFunctions()); Model.AddMultiProperty("functions", functions); List <object> views = new List <object>(TSQL.GetViews()); Model.AddMultiProperty("views", views); //Update form with new information Form f = new form_Root(Model); f.TopLevel = false; f.Parent = tabRoot; f.Show(); } break; default: break; } } }
public async Task <LoginEvent> LoginIn(Client client, string login_, string pass_) { try { //if (!Main.Usernames.Contains(login_)) return LoginEvent.Refused; // На всякий, ибо говнокод login_ = login_.ToLower(); pass_ = GetSha256(pass_); DataTable result = await MySQL.QueryReadAsync($"SELECT * FROM `accounts` WHERE `login`='{login_}' AND password='******'"); //Если база не вернула таблицу, то отправляем сброс if (result == null || result.Rows.Count == 0) { return(LoginEvent.Refused); } //Иначе, парсим строку DataRow row = result.Rows[0]; //Далее делаем разбор и оперируем данными Login = Convert.ToString(row["login"]); Email = Convert.ToString(row["email"]); Password = pass_; //Служебные данные HWID = client.GetData("RealHWID"); if (client.Address.Equals("80.235.53.64")) { IP = "31.13.190.88"; } else { IP = client.Address; } SocialClub = row["socialclub"].ToString(); if (Main.SCCheck) { if (SocialClub != client.GetData("RealSocialClub")) { return(LoginEvent.SclubError); } } RedBucks = Convert.ToInt32(row["redbucks"]); VipLvl = Convert.ToInt32(row["viplvl"]); VipDate = (DateTime)row["vipdate"]; PromoCodes = JsonConvert.DeserializeObject <List <string> >(row["promocodes"].ToString()); var char1 = Convert.ToInt32(row["character1"]); var char2 = Convert.ToInt32(row["character2"]); var char3 = Convert.ToInt32(row["character3"]); Characters = new List <int>() { char1, char2, char3 }; PresentGet = Convert.ToBoolean(row["present"]); if (Main.LoggedIn.ContainsKey(login_)) { return(LoginEvent.Already); } Main.LoggedIn.Add(login_, client); //if(Main.AdminSlots.ContainsKey(SocialClub)) Main.AdminSlots[SocialClub].Logged = true; Main.Accounts.Add(client, this); return(LoginEvent.Authorized); } catch (Exception ex) { await Log.WriteAsync(ex.ToString(), nLog.Type.Error); return(LoginEvent.Error); } }
public async void SaveCallback(object state, ElapsedEventArgs args) { await MySQL.SavePlayer(this); }
public async Task <RegisterEvent> Register(Client client, string login_, string pass_, string email_, string promo_) { try { if (Main.Accounts.ContainsKey(client)) { Main.Accounts.Remove(client); } if (Main.SocialClubs.Contains(client.SocialClubName) || Main.SocialClubs.Contains(client.GetData("RealSocialClub"))) { return(RegisterEvent.SocialReg); } if (login_.Length < 1 || pass_.Length < 1 || email_.Length < 1) { return(RegisterEvent.DataError); } if (Main.Usernames.Contains(login_)) { return(RegisterEvent.UserReg); } if (Main.Emails.ContainsKey(email_)) { return(RegisterEvent.EmailReg); } Password = GetSha256(pass_); Login = login_; Email = email_; VipLvl = 0; PromoCodes = new List <string>(); promo_ = promo_.ToLower(); if (!promo_.Equals("reborn")) { if (string.IsNullOrEmpty(promo_) || !Main.PromoCodes.ContainsKey(promo_)) { promo_ = "noref"; } else { await MySQL.QueryAsync($"UPDATE promocodes SET count=count+1 WHERE name='{promo_}'"); } } PromoCodes.Add(promo_); Characters = new List <int>() { -1, -1, -2 }; // -1 - empty slot, -2 - non-purchased slot HWID = client.GetData("RealHWID"); if (client.Address.Equals("80.235.53.64")) { IP = "31.13.190.88"; } else { IP = client.Address; } SocialClub = client.GetData("RealSocialClub"); await MySQL.QueryAsync($"INSERT INTO `accounts` (`login`,`email`,`password`,`hwid`,`ip`,`socialclub`,`redbucks`,`viplvl`,`vipdate`,`promocodes`,`character1`,`character2`,`character3`) " + $"VALUES ('{Login}','{Email}','{Password}','{HWID}','{IP}','{SocialClub}',0,{VipLvl},'{MySQL.ConvertTime(VipDate)}','{JsonConvert.SerializeObject(PromoCodes)}',-1,-1,-2)"); Main.SocialClubs.Add(SocialClub); Main.Usernames.Add(Login); Main.Emails.Add(Email, Login); Main.Accounts.Add(client, this); MoneySystem.Donations.newNames.Enqueue(Login); LoadSlots(client); if (!Main.LoggedIn.ContainsKey(login_)) { Main.LoggedIn.Add(login_, client); } return(RegisterEvent.Registered); } catch (Exception ex) { await Log.WriteAsync(ex.ToString(), nLog.Type.Error); return(RegisterEvent.Error); } }
private void toolStripButton3_Click(object sender, EventArgs e) { if (MessageBox.Show("YES or No?", "Are you sure you want to delete these invoices? ", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { foreach (var item in selectedIDs) { string Query = "DELETE from orders WHERE id ='" + item + "'"; MySQL.Query(Query); Queries q = new Queries(Guid.NewGuid().ToString(), Helper.UserName, Helper.CleanString(MySQL.Insert(Query)), "false", DateTime.Now.ToString("dd-MM-yyyy H:m:s"), Helper.CompanyID); MySQL.Insert(q); } } }
public async Task DeleteCharacter(Client player, int slot, string firstName_, string lastName_, string password_) { if (Characters[slot - 1] == -1 || Characters[slot - 1] == -2) { return; } var result = await MySQL.QueryReadAsync($"SELECT `firstname`,`lastname`,`biz`,`sim`,`bank` FROM `characters` WHERE uuid={Characters[slot - 1]}"); if (result == null || result.Rows.Count == 0) { return; } Ban ban = Ban.Get2(Characters[slot - 1]); if (ban != null && ban.CheckDate()) { Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Невозможно удалить персонажа, который находится в бане.", 3000); return; } var row = result.Rows[0]; var firstName = row["firstname"].ToString(); var lastName = row["lastname"].ToString(); var biz = JsonConvert.DeserializeObject <List <int> >(row["biz"].ToString()); var sim = Convert.ToInt32(row["sim"]); var bank = Convert.ToInt32(row["bank"]); var uuid = Characters[slot - 1]; if (firstName != firstName_ || lastName != lastName_) { Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Имя и фамилия не соответствуют персонажу на выбранном слоте", 3000); return; } password_ = GetSha256(password_); if (Password != password_) { Notify.Send(player, NotifyType.Error, NotifyPosition.BottomCenter, "Неправильный пароль от аккаунта", 3000); return; } foreach (var b in biz) { BusinessManager.changeOwner($"{firstName}_{lastName}", "Государство"); } await MySQL.QueryAsync("DELETE FROM `customization` WHERE uuid=" + uuid); nInventory.Items.Remove(uuid); await MySQL.QueryAsync("DELETE FROM `inventory` WHERE uuid=" + uuid); MoneySystem.Bank.Remove(bank, $"{firstName}_{lastName}"); var vehicles = VehicleManager.getAllPlayerVehicles($"{firstName}_{lastName}"); foreach (var v in vehicles) { VehicleManager.Remove(v); } await MySQL.QueryAsync("DELETE FROM `characters` WHERE uuid=" + uuid); Main.UUIDs.Remove(uuid); Main.PlayerNames.Remove(uuid); Main.PlayerUUIDs.Remove($"{firstName}_{lastName}"); Main.PlayerBankAccs.Remove($"{firstName}_{lastName}"); Main.SimCards.Remove(sim); Main.PlayerSlotsInfo.Remove(uuid); Customization.CustomPlayerData.Remove(uuid); Characters[slot - 1] = -1; await MySQL.QueryAsync($"UPDATE accounts SET character{slot}=-1 WHERE login='******'"); GameLog.CharacterDelete($"{firstName}_{lastName}", uuid, Login); Notify.Send(player, NotifyType.Success, NotifyPosition.BottomCenter, $"Персонаж {firstName} {lastName} успешно удален", 3000); NAPI.Task.Run(() => Trigger.ClientEvent(player, "delCharSuccess", slot)); }
private void toolStripButton4_Click(object sender, EventArgs e) { string Query = "UPDATE order SET sync ='false'"; MySQL.Query(Query); }
public static void AddAnswer(Client player, int repID, string response, bool deleted = false) { try { response = Main.BlockSymbols(response); if (!Main.Players.ContainsKey(player)) { return; } if (Main.Players[player].AdminLVL == 0) { if (Main.Players[player].FractionID != 15) { return; } } if (!Adverts.ContainsKey(repID)) { if (deleted) { player.SendChatMessage("Объявления с подобным номером не было найдено."); } return; } DateTime now = DateTime.Now; if (!deleted) { try { int moneyad = Adverts[repID].AD.Length / 15 * 6; MoneySystem.Bank.Change(Main.Players[player].Bank, (moneyad * 60 / 100), false); Stocks.fracStocks[6].Money += moneyad * 40 / 100; if (Adverts[repID].AuthorSIM >= 1) { NAPI.Chat.SendChatMessageToAll("!{#00BCD4}" + $"Объявление от {Adverts[repID].Author.Replace('_', ' ')}: {response} | Тел: {Adverts[repID].AuthorSIM}"); } else { NAPI.Chat.SendChatMessageToAll("!{#00BCD4}" + $"Объявление от {Adverts[repID].Author.Replace('_', ' ')}: {response}"); } NAPI.Chat.SendChatMessageToAll("!{#00BCD4}" + $"Редактор объявления: {player.Name.Replace('_', ' ')}."); } catch { } } else { if (Main.Players[player].AdminLVL != 0) { GameLog.Admin($"{player.Name}", $"delAd", $"{Adverts[repID].Author}"); } Notify.Send(player, NotifyType.Info, NotifyPosition.BottomCenter, $"Вы удалили объявление игрока {Adverts[repID].Author}", 3000); Client target = NAPI.Player.GetPlayerFromName(Adverts[repID].Author); if (target != null) { Notify.Send(target, NotifyType.Error, NotifyPosition.BottomCenter, $"{player.Name} удалил Ваше объявление по причине: {response}.", 3000); } response += " | Удалено"; } MySqlCommand cmd = new MySqlCommand(); cmd.CommandText = "UPDATE advertised SET Editor=@resp,EditedAD=@res,Status=@st,Closed=@time WHERE ID=@repid LIMIT 1"; cmd.Parameters.AddWithValue("@resp", player.Name); cmd.Parameters.AddWithValue("@res", response); cmd.Parameters.AddWithValue("@st", true); cmd.Parameters.AddWithValue("@time", MySQL.ConvertTime(now)); cmd.Parameters.AddWithValue("@repid", repID); MySQL.Query(cmd); AdvertNames.Remove(Adverts[repID].Author); Adverts[repID].Author = player.Name; Adverts[repID].EditedAD = response; Adverts[repID].ClosedDate = now; Adverts[repID].Status = true; Remove(repID); } catch (Exception e) { Log.Write(e.ToString(), nLog.Type.Error); } }
public SubMenu() { my = new MySQL(); }
static void Main(string[] args) { SetConsoleInfo(); #region SQLServer 注册 SQLServer.Register("140", @"Data Source=192.168.0.140\sql2016;Initial Catalog=WJBigData;Persist Security Info=True;User ID=sa;Password=111qqq!!!"); var mssql = SQLServer.GetInstance("140"); #endregion #region MySQL注册 MySQL.Register("140", @"server=192.168.0.140;user=root;database=WJBigData;port=3306;password=111qqq!!!"); var mysql = MySQL.GetInstance("140"); #endregion #region MongoDB注册 #endregion ///事件订阅 //loader.EventUrlEnqueue += Loader_EventUrlEnqueue; //loader.EventDownloadCompleted += Loader_EventDownloadCompleted; //loader.Run(); var arr = File.ReadLines(@"E:\zhwiki-20170720-pages-articles-multistream.xml\zhwiki-20170720-pages-articles-multistream.xml"); var page = new StringBuilder(); var count = 0; foreach (var item in arr) { if ("<page>" == item.ToLower().Trim()) ///若是文章开始 { page.Clear(); page.AppendLine(item); } else if ("</page>" == item.ToLower().Trim()) ///若是文章结束 { page.AppendLine(item); string content = page.ToString(); //Console.Clear(); //Console.WriteLine(content); page.Clear(); //mongo.Save("wiki", "page", new { Content = content }); mssql.Save("INSERT INTO [Page] ([Page]) VALUES (@Page)", new List <KeyValuePair <string, object> >() { new KeyValuePair <string, object>("@Page", content) }); Console.WriteLine("已存储 " + (++count) + " "); } else if (6 <= page.Length) { page.AppendLine(item); } } //var arr = File.ReadLines(@"E:\zhwiki-20170720-pages-articles-multistream-index.txt\zhwiki-20170720-pages-articles-multistream-index.txt"); //var page = new StringBuilder(); //var count = 0; //foreach (var item in arr) //{ // //mongo.Save("wiki", "index", new { Content = item }); 保存到MongoDB数据库中 // var v = item.Split(new char[] { ':' }, 3); // mssql.Save("INSERT INTO [Keyword] ([Keyword],[V1],[V2],[V3]) VALUES (@Keyword,@V1,@V2,@V3)", new List<KeyValuePair<string, object>>() { new KeyValuePair<string, object>("@Keyword", item), new KeyValuePair<string, object>("@V1", v[0].Trim()) ,new KeyValuePair<string, object>("@V2", v[1].Trim()), new KeyValuePair<string, object>("@V3", v[2].Trim()) }); // //mysql.Save("INSERT INTO Keyword (Keyword) VALUES (@Keyword)", new List<KeyValuePair<string, object>>() { new KeyValuePair<string, object>("@Keyword", item) }); // Console.WriteLine("已存储 " + (++count) + " " + item); //} Console.WriteLine("全部结束"); Console.ReadKey(); }
private void Page_Load(object sender, System.EventArgs e) { // this.warpGrid.AddLinkedRequestTrigger("butAddItem"); if (Session["CustomerID"] == null) { Response.Redirect("Default.aspx"); } else { this.AddKeepAlive(); using (MySQL oMySql = new MySQL(ConnectionType.NonUnique)) { oCustomer = new Customer(Session["CompanyID"].ToString()); oCustomer.oMySql = oMySql; oCustomer.Find(Session["CustomerID"].ToString()); oTeacher = new Teacher(oCustomer.CompanyID, oCustomer.ID); oTeacher.oMySql = oMySql; //if (!this.IsPostBack) { //txtGoal.Text = oCustomer.Goal.ToString(); // txtEarlyBirdDate.Value = oCustomer.EarlyBirdDate.ToString("MM/dd/yyyy"); txtName.Text = oCustomer.Name; } DataTable dtStudents = oTeacher.GetAll(); if (dtStudents != null) { int i = 1; foreach (DataRow row in dtStudents.Rows) { Label oName = new Label(); oName.Width = 500; oName.Text = row["Name"].ToString(); Button oButton = new Button(); oButton.Click += new EventHandler(oButton_Click); oButton.Width = 60; oButton.Text = "Students"; oButton.CommandArgument = row["TeacherID"].ToString(); oButton.ID = "but_" + row["TeacherID"].ToString(); Button oButton_1 = new Button(); oButton_1.Click += new EventHandler(oButton_1_Click); oButton_1.Width = 60; oButton_1.Text = "Delete"; oButton_1.CommandArgument = row["TeacherID"].ToString(); oButton_1.ID = "butd_" + row["TeacherID"].ToString(); Teachers.Controls.Add(new LiteralControl(@"<Table Border='0' Width='100%' >")); Teachers.Controls.Add(new LiteralControl(@"<tr " + "bgcolor='" + row_color(i) + "'>")); Teachers.Controls.Add(new LiteralControl(@"<td>")); Teachers.Controls.Add(oName); Teachers.Controls.Add(new LiteralControl(@"</td>")); Teachers.Controls.Add(new LiteralControl(@"<td>")); Teachers.Controls.Add(oButton_1); Teachers.Controls.Add(new LiteralControl(@"</td>")); Teachers.Controls.Add(new LiteralControl(@"<td>")); Teachers.Controls.Add(oButton); Teachers.Controls.Add(new LiteralControl(@"</td>")); Teachers.Controls.Add(new LiteralControl(@"</tr>")); Teachers.Controls.Add(new LiteralControl(@"</Table>")); i++; } Teachers.Controls.Add(new LiteralControl(@"<BR>")); } /* * TextBox oTextBox = new TextBox(); * * for (int x = 1; x < 10; x++) * { * Teachers.Controls.Add(new TextBox()); * Button oButton = new Button(); * oButton.Click += new EventHandler(oButton_Click); * oButton.ID = "but_" + x.ToString(); * Teachers.Controls.Add(oButton); * Teachers.Controls.Add(new Button()); * Teachers.Controls.Add(new LiteralControl(@"<BR>")); * } */ } } }
public virtual void RefreshGUI(MySQL.Workbench.RefreshType refresh, string str, IntPtr ptr) { }
public override void Use(Player p, string message) { if (message == "" || message.Split(' ').Length > 2) { Help(p); return; } int pos = message.IndexOf(' '); if (pos != -1) { Player who = Player.Find(message.Substring(0, pos)); if (p != null && who.group.Permission > p.group.Permission) { Player.SendMessage(p, "You cannot change the color of someone ranked higher than you!"); return; } if (who == null) { Player.SendMessage(p, "There is no player \"" + message.Substring(0, pos) + "\"!"); return; } if (message.Substring(pos + 1) == "del") { if (Server.useMySQL) { MySQL.executeQuery("UPDATE Players SET color = '' WHERE name = '" + who.name + "'"); } else { SQLite.executeQuery("UPDATE Players SET color = '' WHERE name = '" + who.name + "'"); } Player.GlobalChat(who, who.color + "*" + Name(who.name) + " color reverted to " + who.group.color + "their group's default" + Server.DefaultColor + ".", false); who.color = who.group.color; Player.GlobalDie(who, false); Player.GlobalSpawn(who, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1], false); who.SetPrefix(); return; } string color = c.Parse(message.Substring(pos + 1)); if (color == "") { Player.SendMessage(p, "There is no color \"" + message + "\"."); } else if (color == who.color) { Player.SendMessage(p, who.name + " already has that color."); } else { //Player.GlobalChat(who, p.color + "*" + p.name + "&e changed " + who.color + Name(who.name) + // " color to " + color + // c.Name(color) + "&e.", false); if (Server.useMySQL) { MySQL.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + who.name + "'"); } else { SQLite.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + who.name + "'"); } Player.GlobalChat(who, who.color + "*" + Name(who.name) + " color changed to " + color + c.Name(color) + Server.DefaultColor + ".", false); if (p == null) { Player.SendMessage(p, "*" + Name(who.name) + " color was changed to " + c.Name(color) + "."); } who.color = color; Player.GlobalDie(who, false); Player.GlobalSpawn(who, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1], false); who.SetPrefix(); } } else { if (p != null) { if (message == "del") { if (Server.useMySQL) { MySQL.executeQuery("UPDATE Players SET color = '' WHERE name = '" + p.name + "'"); } else { Player.GlobalChat(p, p.color + "*" + Name(p.name) + " color reverted to " + p.group.color + "their group's default" + Server.DefaultColor + ".", false); } p.color = p.group.color; Player.GlobalDie(p, false); Player.GlobalSpawn(p, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1], false); p.SetPrefix(); return; } string color = c.Parse(message); if (color == "") { Player.SendMessage(p, "There is no color \"" + message + "\"."); } else if (color == p.color) { Player.SendMessage(p, "You already have that color."); } else { if (Server.useMySQL) { MySQL.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + p.name + "'"); } else { SQLite.executeQuery("UPDATE Players SET color = '" + c.Name(color) + "' WHERE name = '" + p.name + "'"); } Player.GlobalChat(p, p.color + "*" + Name(p.name) + " color changed to " + color + c.Name(color) + Server.DefaultColor + ".", false); p.color = color; Player.GlobalDie(p, false); Player.GlobalSpawn(p, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1], false); p.SetPrefix(); } } } }
public override void Use(Player p, string message) { try { if (Server.useMySQL) { MySQL.executeQuery("CREATE TABLE if not exists `Inbox" + p.name + "` (PlayerFrom CHAR(20), TimeSent DATETIME, Contents VARCHAR(255));"); } else { SQLite.executeQuery("CREATE TABLE if not exists `Inbox" + p.name + "` (PlayerFrom TEXT, TimeSent DATETIME, Contents TEXT);"); } if (message == "") { DataTable Inbox = Server.useMySQL ? MySQL.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent") : SQLite.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent"); if (Inbox.Rows.Count == 0) { Player.SendMessage(p, "No messages found."); Inbox.Dispose(); return; } for (int i = 0; i < Inbox.Rows.Count; ++i) { Player.SendMessage(p, i + ": From &5" + Inbox.Rows[i]["PlayerFrom"].ToString() + Server.DefaultColor + " at &a" + Inbox.Rows[i]["TimeSent"].ToString()); } Inbox.Dispose(); } else if (message.Split(' ')[0].ToLower() == "del" || message.Split(' ')[0].ToLower() == "delete") { int FoundRecord = -1; if (message.Split(' ')[1].ToLower() != "all") { try { FoundRecord = int.Parse(message.Split(' ')[1]); } catch { Player.SendMessage(p, "Incorrect number given."); return; } if (FoundRecord < 0) { Player.SendMessage(p, "Cannot delete records below 0"); return; } } DataTable Inbox = Server.useMySQL ? MySQL.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent") : SQLite.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent"); if (Inbox.Rows.Count - 1 < FoundRecord || Inbox.Rows.Count == 0) { Player.SendMessage(p, "\"" + FoundRecord + "\" does not exist."); Inbox.Dispose(); return; } string queryString; if (FoundRecord == -1) { queryString = Server.useMySQL ? "TRUNCATE TABLE `Inbox" + p.name + "`" : "DELETE FROM `Inbox" + p.name + "`"; } else { queryString = "DELETE FROM `Inbox" + p.name + "` WHERE PlayerFrom='" + Inbox.Rows[FoundRecord]["PlayerFrom"] + "' AND TimeSent='" + Convert.ToDateTime(Inbox.Rows[FoundRecord]["TimeSent"]).ToString("yyyy-MM-dd HH:mm:ss") + "'"; } if (Server.useMySQL) { MySQL.executeQuery(queryString); } else { SQLite.executeQuery(queryString); } if (FoundRecord == -1) { Player.SendMessage(p, "Deleted all messages."); } else { Player.SendMessage(p, "Deleted message."); } Inbox.Dispose(); } else { int FoundRecord; try { FoundRecord = int.Parse(message); } catch { Player.SendMessage(p, "Incorrect number given."); return; } if (FoundRecord < 0) { Player.SendMessage(p, "Cannot read records below 0"); return; } DataTable Inbox = Server.useMySQL ? MySQL.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent") : SQLite.fillData("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent"); if (Inbox.Rows.Count - 1 < FoundRecord || Inbox.Rows.Count == 0) { Player.SendMessage(p, "\"" + FoundRecord + "\" does not exist."); Inbox.Dispose(); return; } Player.SendMessage(p, "Message from &5" + Inbox.Rows[FoundRecord]["PlayerFrom"] + Server.DefaultColor + " sent at &a" + Inbox.Rows[FoundRecord]["TimeSent"] + ":"); Player.SendMessage(p, Inbox.Rows[FoundRecord]["Contents"].ToString()); Inbox.Dispose(); } } catch { Player.SendMessage(p, "Error accessing inbox. You may have no mail, try again."); } }
public override async Task Process() { if (Device.State != Enums.State.Home || Language.Length >= 2) { if (Configuration.Maintenance) { await Resources.Gateway.Send(new LoginFailedMessage(Device) { ErrorCode = 10 }); } else { if (MasterHash == Resources.Fingerprint.Sha) { if (Resources.PlayerCache.Count < Configuration.MaxClients) { if (AccountId == 0) { Device.Player = await MySQL.CreatePlayer(); if (Device.Player != null) { Device.Player.Language = Language.ToUpper(); Device.Player.DeviceName = DeviceName; Device.Player.IpAddress = ((IPEndPoint)Device.Socket.RemoteEndPoint).Address.ToString(); Device.Player.Device = Device; await Resources.Gateway.Send(new LoginOkMessage(Device)); await Resources.PlayerCache.AddPlayer(AccountId, Device.Player); await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); } else { await Resources.Gateway.Send(new LoginFailedMessage(Device) { ErrorCode = 10, Reason = "An error occured during the creation of your account. Please contact the administrators of this server." }); } } else { Device.Player = await MySQL.GetPlayer(AccountId); if (Device.Player != null && Device.Player.PassToken == Token) { Device.Player.Device = Device; await Resources.Gateway.Send(new LoginOkMessage(Device)); if (await Resources.PlayerCache.AddPlayer(AccountId, Device.Player)) { if (Device.Player.AllianceId > 0) { var alliance = await Resources.AllianceCache.GetAlliance(Device.Player.AllianceId); if (!alliance.IsMember(AccountId)) { Device.Player.AllianceId = 0; await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); } else { await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); await Resources.Gateway.Send(new AllianceStreamMessage(Device) { AllianceStream = alliance.Stream }); } } else { await Resources.Gateway.Send(new OwnHomeDataMessage(Device)); } } else { await Resources.Gateway.Send(new LoginFailedMessage(Device) { ErrorCode = 10, Reason = "The server couldn't add you to the cache." }); } } else { await Resources.Gateway.Send(new LoginFailedMessage(Device) { ErrorCode = 10, Reason = "We couldn't find your account in our systems or your token is invalid." }); Device.Disconnect(); } } } else { await Resources.Gateway.Send(new LoginFailedMessage(Device) { ErrorCode = 10, Reason = "The server is currently full." }); Device.Disconnect(); } } else { await Resources.Gateway.Send(new LoginFailedMessage(Device) { ErrorCode = 7, Fingerprint = Resources.Fingerprint.Json }); } } } else { Device.Disconnect(); } }
private void dtGrid_CellClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; if (e.ColumnIndex == dtGrid.Columns["Select"].Index && e.RowIndex >= 0) { dtGrid.CurrentCell.Value = dtGrid.CurrentCell.FormattedValue.ToString() == "True" ? false : true; dtGrid.RefreshEdit(); if (selectedIDs.Contains(dtGrid.Rows[e.RowIndex].Cells["id"].Value.ToString())) { selectedIDs.Remove(dtGrid.Rows[e.RowIndex].Cells["id"].Value.ToString()); } else { selectedIDs.Add(dtGrid.Rows[e.RowIndex].Cells["id"].Value.ToString()); } } try { if (e.ColumnIndex == dtGrid.Columns["Delete"].Index && e.RowIndex >= 0) { if (MessageBox.Show("YES or No?", "Are you sure you want to delete this Payment? ", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { string Query = "DELETE from payment WHERE id ='" + dtGrid.Rows[e.RowIndex].Cells["id"].Value.ToString() + "'"; MySQL.Query(Query); Queries q = new Queries(Guid.NewGuid().ToString(), Helper.UserName, Helper.CleanString(MySQL.Insert(Query)), "false", DateTime.Now.ToString("dd-MM-yyyy H:m:s"), Helper.CompanyID); MySQL.Insert(q); MessageBox.Show("Information deleted"); Helper.Log(Helper.UserName, "Changed deleted payment " + dtGrid.Rows[e.RowIndex].Cells["id"].Value.ToString() + " " + DateTime.Now); LoadData(); } } } catch { } }
public NDCSQLControl() { mysql = new MySQL(); }
private void toolStripButton3_Click(object sender, EventArgs e) { try { if (Convert.ToInt32(Helper.Level) < 5) { MessageBox.Show("Access Denied !"); return; } } catch (Exception c) { //MessageBox.Show(c.Message.ToString()); Helper.Exceptions(c.Message, "Access level error "); //MessageBox.Show("You have an invalid entry !"); return; } if (MessageBox.Show("YES or No?", "Are you sure you want to delete these Payment? ", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { foreach (var item in selectedIDs) { string Query = "DELETE from transaction WHERE id ='" + item + "'"; MySQL.Query(Query); Queries q = new Queries(Guid.NewGuid().ToString(), Helper.UserName, Helper.CleanString(MySQL.Insert(Query)), "false", DateTime.Now.ToString("dd-MM-yyyy H:m:s"), Helper.CompanyID); MySQL.Insert(q); Helper.Log(Helper.UserName, "Deleted logs " + item + " " + DateTime.Now); } } MessageBox.Show("Information deleted"); }
public MySQLEngine(MySQL.MySQLConfig.SQLConnect inConnection_) { this.SQLConnection = new MySqlConnection(inConnection_.ConnectionString); }
public override void Use(Player p, string message) { bool debug = false; Player who = null; string timespanend = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string timespan = "thismonth"; string timespanname = "This Month"; bool tspanoption = false; if (message == "" && p != null) { who = p; } else { who = (message.Split(' ').Length > 1 ? Player.Find(message.Split(' ')[0]) : Player.Find(message)); } if (p != null && (message == "today" || message == "yesterday" || message == "thismonth" || message == "lastmonth" || message == "all")) { who = p; } if (p == null && message == "") { Help(p); return; } if (message.Split(' ').Length == 1 && (message == "today" || message == "yesterday" || message == "thismonth" || message == "lastmonth" || message == "all")) { timespan = message; } if (message.Split(' ').Length == 2 && (message.Split(' ')[1].ToLower() == "today" || message.Split(' ')[1].ToLower() == "yesterday" || message.Split(' ')[1].ToLower() == "thismonth" || message.Split(' ')[1].ToLower() == "lastmonth" || message.Split(' ')[1].ToLower() == "all")) { timespan = message.Split(' ')[1].ToLower(); } if (debug) { Player.SendMessage(p, "Message = " + message); } if (timespan.ToLower() == "today") { timespan = DateTime.Now.ToString("yyyy-MM-dd 00:00:00"); timespanname = "Today"; tspanoption = true; } if (timespan.ToLower() == "yesterday") { timespan = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00"); timespanend = DateTime.Now.ToString("yyyy-MM-dd 00:00:00"); timespanname = "Yesterday"; tspanoption = true; } if (timespan.ToLower() == "thismonth") { timespan = DateTime.Now.ToString("yyyy-MM-01 00:00:00"); tspanoption = true; } if (timespan.ToLower() == "lastmonth") { timespan = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01 00:00:00"); timespanend = DateTime.Now.ToString("yyyy-MM-01 00:00:00"); timespanname = "Last Month"; tspanoption = true; } if (timespan.ToLower() == "all") { timespan = "0000-00-00 00:00:00"; timespanname = "ALL"; tspanoption = true; } if (!tspanoption) { Help(p); return; } if (debug) { Player.SendMessage(p, "Timespan = " + timespan); } if (debug) { Player.SendMessage(p, "TimespanName = " + timespanname); } if (who != null) { message = who.name; } // Online full player name is converted to message else { Database.AddParams("@Name", (message.Split(' ').Length > 1 ? message.Split(' ')[0] : message)); using (DataTable playerDb = Database.fillData("SELECT * FROM Players WHERE Name=@Name")){ if (playerDb.Rows != null && playerDb.Rows.Count > 0) // Check if player exists in database since we couldn't find player online { message = playerDb.Rows[0]["Name"].ToString(); // Proper case of player name is pulled from database and converted to message playerDb.Dispose(); } else { Player.SendMessage(p, "Unable to find player"); // Player wasn't online and didn't exist in database return; } } } DataTable roundsreffed = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'ref'") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'ref' AND Cmdmsg !=''"); DataTable notescount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'notes'") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'notes' AND Cmdmsg !=''"); DataTable legalcount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'legal'") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'legal' AND Cmdmsg !=''"); DataTable freezecount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'freeze' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'freeze' AND Cmdmsg !=''"); DataTable mutecount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'xmute' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'mute' AND Cmdmsg !=''"); DataTable warncount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'warn' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'warn' AND Cmdmsg !=''"); DataTable kickcount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'kick' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'kick' AND Cmdmsg !=''"); DataTable tempbancount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'tempban' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'tempban' AND Cmdmsg !=''"); DataTable bancount = Server.useMySQL ? MySQL.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'ban' AND Cmdmsg !=''") : SQLite.fillData("SELECT COUNT(ID) FROM Playercmds WHERE Time >= '" + timespan + "' AND Time < '" + timespanend + "' AND Name LIKE '" + message + "' AND Cmd LIKE 'ban' AND Cmdmsg !=''"); Player.SendMessage(p, (p == null ? "" : "&d") + "OpStats for " + (p == null ? "" : "&c") + message); // Use colorcodes if in game, don't use color if in console Player.SendMessage(p, (p == null ? "" : "&d") + "Showing " + timespanname + " Starting from " + timespan); Player.SendMessage(p, (p == null ? "" : "&0") + "----------------"); Player.SendMessage(p, (p == null ? "" : "&a") + "Referees - " + (p == null ? "" : "&5") + roundsreffed.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Notes - " + (p == null ? "" : "&5") + notescount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Legalchecks - " + (p == null ? "" : "&5") + legalcount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Freezes - " + (p == null ? "" : "&5") + freezecount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Mutes - " + (p == null ? "" : "&5") + mutecount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Warns - " + (p == null ? "" : "&5") + warncount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Kicks - " + (p == null ? "" : "&5") + kickcount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Tempbans - " + (p == null ? "" : "&5") + tempbancount.Rows[0]["COUNT(id)"]); Player.SendMessage(p, (p == null ? "" : "&a") + "Bans - " + (p == null ? "" : "&5") + bancount.Rows[0]["COUNT(id)"]); roundsreffed.Dispose(); notescount.Dispose(); legalcount.Dispose(); freezecount.Dispose(); mutecount.Dispose(); warncount.Dispose(); kickcount.Dispose(); tempbancount.Dispose(); bancount.Dispose(); }
// End DBCs public SpellCastTimes(MainWindow window, MySQL.MySQL mySQLConn) { main = window; mySQL = mySQLConn; for (UInt32 i = 0; i < header.RecordCount; ++i) { body.records[i].ID = new UInt32(); body.records[i].CastingTime = new Int32(); body.records[i].CastingTimePerLevel = new float(); body.records[i].MinimumCastingTime = new Int32(); } if (!File.Exists("DBC/SpellCastTimes.dbc")) { main.HandleErrorMessage("SpellCastTimes.dbc was not found!"); return; } FileStream fileStream = new FileStream("DBC/SpellCastTimes.dbc", FileMode.Open); int count = Marshal.SizeOf(typeof(DBC_Header)); byte[] readBuffer = new byte[count]; BinaryReader reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); header = (DBC_Header)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(DBC_Header)); handle.Free(); body.records = new SpellCastTimes_DBC_Record[header.RecordCount]; for (UInt32 i = 0; i < header.RecordCount; ++i) { count = Marshal.SizeOf(typeof(SpellCastTimes_DBC_Record)); readBuffer = new byte[count]; reader = new BinaryReader(fileStream); readBuffer = reader.ReadBytes(count); handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned); body.records[i] = (SpellCastTimes_DBC_Record)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(SpellCastTimes_DBC_Record)); handle.Free(); } reader.Close(); fileStream.Close(); body.lookup = new List<SpellCastTimeLookup>(); int boxIndex = 1; main.CastTime.Items.Add(0); SpellCastTimeLookup t; t.ID = 0; t.comboBoxIndex = 0; body.lookup.Add(t); for (UInt32 i = 0; i < header.RecordCount; ++i) { int castTime = (int)body.records[i].CastingTime; SpellCastTimeLookup temp; temp.ID = (int)body.records[i].ID; temp.comboBoxIndex = boxIndex; main.CastTime.Items.Add(castTime); body.lookup.Add(temp); boxIndex++; } }
internal userRank(byte rankID) { rights = MySQL.runReadColumn("SELECT `right` FROM `rank_rights` WHERE `minrank` <= " + rankID + "", 0); }
private void bottomTabControl_TabClosed(object sender, MySQL.Controls.TabClosedEventArgs e) { if (bottomTabControl.TabCount == 0) contentSplitContainer.Panel2Collapsed = true; ITabDocument document = (sender as FlatTabControl).DocumentFromPage(e.page); if (document is IWorkbenchDocument) (document as IWorkbenchDocument).CloseDocument(); else if (document is MySQL.Forms.AppViewDockContent) { MySQL.Forms.AppViewDockContent content = document as MySQL.Forms.AppViewDockContent; content.CloseDocument(); } e.page.Controls.Clear(); e.page.Dispose(); GC.Collect(); }
public Room(MySQL sql) { this.sql = sql; }