/// <summary> /// Inserts values the specified table. /// </summary> /// <param name="table">The table.</param> /// <param name="values">The values.</param> /// <returns></returns> public long insert(string table, params string[] values) { string query = "INSERT INTO `" + sanitise(table) + "` VALUES ("; foreach (string item in values) { if (item != string.Empty) { query += " \"" + sanitise(item) + "\","; } else { query += "null,"; } } query = query.TrimEnd(','); query += " );"; long lastInsertedId = -1; try { MySqlCommand cmd = new MySqlCommand(query); this.executeNonQuery(ref cmd); lastInsertedId = cmd.LastInsertedId; } catch (MySqlException ex) { GlobalFunctions.errorLog(ex); } return(lastInsertedId); }
private void listenerThread() { try { _listener.Start(); while (true) { if (!_listener.Pending()) { Thread.Sleep(100); continue; } TcpClient client = _listener.AcceptTcpClient(); new IrcProxyInstance(client, _password, _baseIal); } } catch (ThreadAbortException) {} catch (Exception ex) { GlobalFunctions.errorLog(ex); } }
private void executeNonQuery(ref MySqlCommand cmd) { Logger.instance().addToLog("Locking access to DAL...", Logger.LogTypes.DalLock); lock (this) { Logger.instance().addToLog("Executing (non)query: " + cmd.CommandText, Logger.LogTypes.DAL); try { runConnectionTest(); //MySqlTransaction transact = _connection.BeginTransaction( System.Data.IsolationLevel.RepeatableRead ); cmd.Connection = _connection; cmd.ExecuteNonQuery(); //transact.Commit( ); } catch (MySqlException ex) { GlobalFunctions.errorLog(ex); } catch (InvalidOperationException ex) { GlobalFunctions.errorLog(ex); } catch (Exception ex) { GlobalFunctions.errorLog(ex); } Logger.instance().addToLog("Done executing (non)query: " + cmd.CommandText, Logger.LogTypes.DAL); } Logger.instance().addToLog("DAL Lock released.", Logger.LogTypes.DalLock); }
/// <summary> /// /// </summary> /// <param name="query"></param> /// <returns></returns> /// <remarks>Needs Lock!</remarks> private MySqlDataReader executeReaderQuery(string query) { MySqlDataReader result = null; Logger.instance().addToLog("Executing (reader)query: " + query, Logger.LogTypes.DAL); try { runConnectionTest(); MySqlCommand cmd = new MySqlCommand(query) { Connection = this._connection }; result = cmd.ExecuteReader(); Logger.instance().addToLog("Done executing (reader)query: " + query, Logger.LogTypes.DAL); return(result); } catch (Exception ex) { Logger.instance().addToLog("Problem executing (reader)query: " + query, Logger.LogTypes.DAL); GlobalFunctions.errorLog(ex); } return(result); }
public bool connect() { try { _tcpClient = new TcpClient(_ircServer, (int)_ircPort); Stream ircStream = _tcpClient.GetStream(); _ircReader = new StreamReader(ircStream, Encoding.UTF8); _ircWriter = new StreamWriter(ircStream, Encoding.UTF8); _sendQ = new Queue(100); ThreadStart ircReaderThreadStart = _ircReaderThreadMethod; _ircReaderThread = new Thread(ircReaderThreadStart); ThreadStart ircWriterThreadStart = _ircWriterThreadMethod; _ircWriterThread = new Thread(ircWriterThreadStart); this.registerInstance(); _ircReaderThread.Start(); _ircWriterThread.Start(); this.connectionRegistrationRequiredEvent(); return(true); } catch (SocketException ex) { GlobalFunctions.errorLog(ex); return(false); } }
/// <summary> /// Updates the authenticating user's status. Requires the status parameter specified below. Request must be a POST. A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates. /// </summary> /// <param name = "status">The text of your status update. URL encode as necessary. Statuses over 140 characters will cause a 403 error to be returned from the API.</param> /// <see cref = "http://apiwiki.twitter.com/Twitter-REST-API-Method:-statuses%C2%A0update" /> public TwitterStatus updateStatus(string status) { if (status.Length == 0) { return(null); } status = (status.Length > 140 ? status.Substring(0, 140) : status); if (_accessToken == "") { throw new TwitterizerException("Must authorise first!"); } OAuthTokens tokens = new OAuthTokens { AccessToken = _accessToken, AccessTokenSecret = _accessTokenSecret, ConsumerKey = _consumerKey, ConsumerSecret = _consumerSecret }; TwitterStatus returnval; try { returnval = TwitterStatus.Update(tokens, status); } catch (System.Net.WebException ex) { GlobalFunctions.errorLog(ex); returnval = null; } return(returnval); }
/// <summary> /// Initializes a new instance of the <see cref="Twitter"/> class. /// </summary> public Twitter() { _consumerKey = Configuration.singleton( )["twitterConsumerKey"]; _consumerSecret = Configuration.singleton( )["twitterConsumerSecret"]; _accessToken = Configuration.singleton( )["twitterAccessToken"]; _accessTokenSecret = Configuration.singleton( )["twitterAccessTokenSecret"]; if (Configuration.singleton()["twitterRequestToken"] != "" || (_accessToken != "" && _accessTokenSecret != "")) { return; } try { OAuthTokenResponse tkn = OAuthUtility.GetRequestToken(_consumerKey, _consumerSecret); Configuration.singleton( )["twitterRequestToken"] = tkn.Token; Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(tkn.Token); Helpmebot6.irc.ircPrivmsg(Helpmebot6.debugChannel, "Please authorise access to Twitter: " + authorizationUri); } catch (TwitterizerException ex) { GlobalFunctions.errorLog(ex); } }
private static void receivedMessage(User source, string destination, string message) { CommandParser cmd = new CommandParser(); try { bool overrideSilence = cmd.overrideBotSilence; if (CommandParser.isRecognisedMessage(ref message, ref overrideSilence)) { cmd.overrideBotSilence = overrideSilence; string[] messageWords = message.Split(' '); string command = messageWords[0]; string joinedargs = string.Join(" ", messageWords, 1, messageWords.Length - 1); string[] commandArgs = joinedargs == string.Empty ? new string[0] : joinedargs.Split(' '); cmd.handleCommand(source, destination, command, commandArgs); } string aiResponse = Intelligence.singleton().respond(message); if (Configuration.singleton()["silence", destination] == "false" && aiResponse != string.Empty) { string[] aiParameters = { source.nickname }; irc.ircPrivmsg(destination, new Message().get(aiResponse, aiParameters)); } } catch (Exception ex) { GlobalFunctions.errorLog(ex); } }
/// <summary> /// Connects this instance to the database. /// </summary> /// <returns></returns> public bool connect() { try { lock (this) { Logger.instance().addToLog("Opening database connection...", Logger.LogTypes.DAL); MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder { Database = this._mySqlSchema, Password = this. _mySqlPassword, Server = this._mySqlServer, UserID = this. _mySqlUsername, Port = this._mySqlPort }; _connection = new MySqlConnection(csb.ConnectionString); _connection.Open(); } return(true); } catch (MySqlException ex) { GlobalFunctions.errorLog(ex); return(false); } }
// ReSharper disable InconsistentNaming public void proc_HMB_UPDATE_BINARYSTORE(byte[] raw, string desc) // ReSharper restore InconsistentNaming { MySqlCommand cmd = new MySqlCommand { Connection = this._connection, CommandType = CommandType.StoredProcedure, CommandText = "HMB_UPDATE_BINARYSTORE" }; cmd.Parameters.Add("@raw", MySqlDbType.Blob).Value = raw; cmd.Parameters.Add("@desc", MySqlDbType.VarChar).Value = desc; lock (this) { try { runConnectionTest(); cmd.ExecuteNonQuery(); } catch (InvalidOperationException ex) { GlobalFunctions.errorLog(ex); } } }
// ReSharper disable InconsistentNaming public string proc_HMB_GET_MESSAGE_CONTENT(string title) // ReSharper restore InconsistentNaming { byte[] binarymessage = new byte[0]; try { lock (this) { runConnectionTest(); MySqlCommand cmd = new MySqlCommand { Connection = this._connection, CommandType = CommandType.StoredProcedure, CommandText = "HMB_GET_MESSAGE_CONTENT" }; byte[] titlebytes = new byte[255]; Encoding.ASCII.GetBytes(title, 0, title.Length, titlebytes, 0); cmd.Parameters.Add("@title", MySqlDbType.VarBinary).Value = title; cmd.Parameters["@title"].Direction = ParameterDirection.Input; byte[] messagebytes = new byte[0]; cmd.Parameters.Add("@message", MySqlDbType.MediumBlob).Value = messagebytes; cmd.Parameters["@message"].Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); // Logger.instance().addToLog("pre-error.", Logger.LogTypes.General); object foo = cmd.Parameters["@message"].Value is DBNull ? new byte[0] : cmd.Parameters["@message"].Value; // Logger.instance().addToLog("empty or param value", Logger.LogTypes.General); // Logger.instance().addToLog(foo.GetType().ToString(), Logger.LogTypes.General); binarymessage = (byte[])(foo); // Logger.instance().addToLog("convert to byte", Logger.LogTypes.General); // Logger.instance().addToLog("got binary message, returning.", Logger.LogTypes.General); } } catch (InvalidOperationException ex) { GlobalFunctions.errorLog(ex); } return(Encoding.UTF8.GetString(binarymessage)); }
private void _ircWriterThreadMethod() { bool threadIsAlive = true; do { try { string line = null; lock (_sendQ) { if (_sendQ.Count > 0) { line = (string)_sendQ.Dequeue(); } } if (line != null) { Logger.instance().addToLog("< " + line, Logger.LogTypes.IAL); _ircWriter.WriteLine(line); _ircWriter.Flush(); Thread.Sleep(this.floodProtectionWaitTime); } else { // wait a short while before rechecking Thread.Sleep(100); } } catch (ThreadAbortException ex) { threadIsAlive = false; GlobalFunctions.errorLog(ex); _sendQ.Clear(); } catch (IOException ex) { threadIsAlive = false; GlobalFunctions.errorLog(ex); } catch (Exception ex) { GlobalFunctions.errorLog(ex); } } while (threadIsAlive && _ircReaderThread.IsAlive); Console.WriteLine("*** Writer thread died."); EventHandler temp = this.threadFatalError; if (temp != null) { temp(this, new EventArgs()); } }
/// <summary> /// Determines whether this instance is valid. /// </summary> /// <returns> /// <c>true</c> if this instance is valid; otherwise, <c>false</c>. /// </returns> public bool isValid() { try { TimeSpan difference = DateTime.Now - _lastRetrieval; return(difference.TotalMinutes <= CACHE_TIMEOUT); } catch (Exception ex) { GlobalFunctions.errorLog(ex); } return(false); }
/// <summary> /// Updates rows in the specified table. /// </summary> /// <param name="table">The table.</param> /// <param name="items">The items.</param> /// <param name="limit">The limit.</param> /// <param name="conditions">The conditions.</param> public bool update(string table, Dictionary <string, string> items, int limit, params WhereConds[] conditions) { bool succeed = false; if (items.Count < 1) { return(true); } string query = "UPDATE `" + sanitise(table) + "` SET "; foreach (KeyValuePair <string, string> col in items) { query += "`" + sanitise(col.Key) + "` = \"" + sanitise(col.Value) + "\", "; } query = query.TrimEnd(',', ' '); for (int i = 0; i < conditions.Length; i++) { if (i == 0) { query += " WHERE "; } else { query += " AND "; } query += conditions[i].ToString(); } if (limit > 0) { query += " LIMIT " + limit; } query += ";"; try { MySqlCommand updateCommand = new MySqlCommand(query); this.executeNonQuery(ref updateCommand); succeed = true; } catch (MySqlException ex) { GlobalFunctions.errorLog(ex); } return(succeed); }
// ReSharper disable InconsistentNaming public string proc_HMB_GET_IW_URL(string prefix) // ReSharper restore InconsistentNaming { string surl = string.Empty; try { lock (this) { runConnectionTest(); MySqlCommand cmd = new MySqlCommand { Connection = this._connection, CommandType = CommandType.StoredProcedure, CommandText = "HMB_GET_IW_URL" }; if (prefix.Length > 32) { return(string.Empty); } cmd.Parameters.Add("@prefix", MySqlDbType.VarChar).Value = prefix; cmd.Parameters["@prefix"].Direction = ParameterDirection.Input; byte[] url = new byte[0]; cmd.Parameters.Add("@url", MySqlDbType.VarChar).Value = url; cmd.Parameters["@url"].Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); surl = (string) (cmd.Parameters["@url"].Value is System.DBNull ? string.Empty : cmd.Parameters["@url"].Value); } } catch (InvalidOperationException ex) { GlobalFunctions.errorLog(ex); } return(surl); }
private void _ircReaderThreadMethod() { bool threadIsAlive = true; do { try { string line = _ircReader.ReadLine(); if (line == null) { // noop } else { if (this.dataRecievedEvent != null) { this.dataRecievedEvent(line); } } } catch (ThreadAbortException ex) { threadIsAlive = false; GlobalFunctions.errorLog(ex); } catch (IOException ex) { threadIsAlive = false; GlobalFunctions.errorLog(ex); } catch (Exception ex) { GlobalFunctions.errorLog(ex); } } while (threadIsAlive); Console.WriteLine("*** Reader thread died."); EventHandler temp = this.threadFatalError; if (temp != null) { temp(this, new EventArgs()); } }
// ReSharper disable InconsistentNaming public string proc_HMB_GET_LOCAL_OPTION(string option, string channel) // ReSharper restore InconsistentNaming { try { lock (this) { runConnectionTest(); MySqlCommand cmd = new MySqlCommand { Connection = this._connection, CommandType = CommandType.StoredProcedure, CommandText = "HMB_GET_LOCAL_OPTION" }; cmd.Parameters.AddWithValue("@optionName", option); cmd.Parameters["@optionName"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("@channel", channel); cmd.Parameters["@channel"].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("@optionValue", ""); cmd.Parameters["@optionValue"].Direction = ParameterDirection.Output; cmd.ExecuteNonQuery(); return((string)cmd.Parameters["@optionValue"].Value); } } catch (FormatException ex) { GlobalFunctions.errorLog(ex); Logger.instance().addToLog(option + "@" + channel, Logger.LogTypes.Error); throw; } catch (InvalidOperationException ex) { GlobalFunctions.errorLog(ex); } return(null); }
private string retrieveOptionFromDatabase(string optionName) { try { DAL.Select q = new DAL.Select("configuration_value"); q.setFrom("configuration"); q.addLimit(1, 0); q.addWhere(new DAL.WhereConds("configuration_name", optionName)); string result = this._dbal.executeScalarSelect(q) ?? ""; return(result); } catch (Exception ex) { GlobalFunctions.errorLog(ex); } return(null); }
/// <summary> /// New user from string. /// </summary> /// <param name="source">The source.</param> /// <param name="network">The network.</param> /// <returns></returns> public static User newFromString(string source, uint network) { string user, host; string nick = user = host = null; try { if ((source.Contains("@")) && (source.Contains("!"))) { char[] splitSeparators = { '!', '@' }; string[] sourceSegment = source.Split(splitSeparators, 3); nick = sourceSegment[0]; user = sourceSegment[1]; host = sourceSegment[2]; } else if (source.Contains("@")) { char[] splitSeparators = { '@' }; string[] sourceSegment = source.Split(splitSeparators, 2); nick = sourceSegment[0]; host = sourceSegment[1]; } else { nick = source; } } catch (IndexOutOfRangeException ex) { GlobalFunctions.errorLog(ex); } User ret = new User { hostname = host, nickname = nick, username = user, network = network }; return(ret); }
/// <summary> /// Executes the select. /// </summary> /// <param name="query">The query.</param> /// <param name="columns">A list of column names</param> /// <returns>Arraylist of arrays. Each array is one row in the dataset.</returns> public ArrayList executeSelect(Select query, out List <string> columns) { columns = new List <string>(); ArrayList resultSet = new ArrayList(); lock (this) { MySqlDataReader dr = this.executeReaderQuery(query.ToString()); if (dr != null) { try { DataTableReader cols = dr.GetSchemaTable().CreateDataReader(); while (cols.Read()) { columns.Add((string)cols.GetValue(0)); } cols.Close(); while (dr.Read()) { object[] row = new object[dr.FieldCount]; dr.GetValues(row); resultSet.Add(row); } } catch (MySqlException ex) { GlobalFunctions.errorLog(ex); throw; } finally { dr.Close(); } } } return(resultSet); }
/// <summary> /// Deletes from the specified table. /// </summary> /// <param name="table">The table.</param> /// <param name="limit">The limit.</param> /// <param name="conditions">The conditions.</param> public bool delete(string table, int limit, params WhereConds[] conditions) { bool succeed = false; string query = "DELETE FROM `" + sanitise(table) + "`"; for (int i = 0; i < conditions.Length; i++) { if (i == 0) { query += " WHERE "; } else { query += " AND "; } query += conditions[i].ToString(); } if (limit > 0) { query += " LIMIT " + limit; } query += ";"; try { MySqlCommand deleteCommand = new MySqlCommand(query); this.executeNonQuery(ref deleteCommand); succeed = true; } catch (MySqlException ex) { GlobalFunctions.errorLog(ex); } return(succeed); }
/// <summary> /// Shortens the specified long URL. /// </summary> /// <param name="longUrl">The long URL.</param> /// <returns></returns> public static Uri shorten(Uri longUrl) { DAL.Select q = new DAL.Select("suc_shorturl"); q.setFrom("shorturlcache"); q.addWhere(new DAL.WhereConds("suc_fullurl", longUrl.ToString())); string cachelookup = DAL.singleton().executeScalarSelect(q); if (cachelookup == "") { try { string shorturl = getShortUrl(longUrl); DAL.singleton().insert("shorturlcache", "", longUrl.ToString(), shorturl); return(new Uri(shorturl)); } catch (WebException ex) { GlobalFunctions.errorLog(ex); return(longUrl); } } return(new Uri(cachelookup)); }
private void ialDataRecievedEvent(string data) { Logger.instance().addToLog(data, Logger.LogTypes.IRC); char[] colonSeparator = { ':' }; string command, parameters; string messagesource = command = parameters = ""; basicParser(data, ref messagesource, ref command, ref parameters); User source = new User(); if (messagesource != null) { source = User.newFromString(messagesource, _networkId); } switch (command) { case "ERROR": if (parameters.ToLower().Contains(":closing link")) { _tcpClient.Close(); _ircReaderThread.Abort(); _ircWriterThread.Abort(); } break; case "PING": this.pingEvent(parameters); break; case "NICK": this.nicknameChangeEvent(source.nickname, parameters.Substring(1)); break; case "MODE": try { string subject = parameters.Split(' ')[0]; string flagchanges = parameters.Split(' ')[1]; string param = parameters.Split(' ').Length > 2 ? parameters.Split(' ')[2] : ""; this.modeChangeEvent(source, subject, flagchanges, param); } catch (NullReferenceException ex) { GlobalFunctions.errorLog(ex); } break; case "QUIT": this.quitEvent(source, parameters); break; case "JOIN": this.joinEvent(source, parameters); break; case "PART": this.partEvent(source, parameters.Split(' ')[0], parameters.Contains(new String(colonSeparator)) ? parameters.Split(colonSeparator, 2)[1] : string.Empty); break; case "TOPIC": this.topicEvent(source, parameters.Split(' ')[0], parameters.Split(colonSeparator, 2)[1]); break; case "INVITE": this.inviteEvent(source, parameters.Split(' ')[0], parameters.Split(' ')[1].Substring(1)); break; case "KICK": this.kickEvent(source, parameters.Split(' ')[0], parameters.Split(' ')[1], parameters.Split(colonSeparator, 2)[1]); break; case "PRIVMSG": string message = parameters.Split(colonSeparator, 2)[1]; ASCIIEncoding asc = new ASCIIEncoding(); byte[] ctcp = { Convert.ToByte(1) }; string destination = parameters.Split(colonSeparator, 2)[0].Trim(); if (destination == this.ircNickname) { destination = source.nickname; } if (message.StartsWith(asc.GetString(ctcp))) { this.ctcpEvent( source, destination, message.Trim(Convert.ToChar(Convert.ToByte(1))) ); } else { this.privmsgEvent(source, destination, message.Trim()); } break; case "NOTICE": string noticedestination = parameters.Split(colonSeparator, 2)[0].Trim(); if (noticedestination == this.ircNickname) { noticedestination = source.nickname; } this.noticeEvent(source, noticedestination, parameters.Split(colonSeparator, 2)[1]); break; case "001": this.connectionRegistrationSucceededEvent(); break; case "002": this.RPL_YourHostEvent(parameters); break; case "003": this.RPL_CreatedEvent(parameters); break; case "004": this.RPL_MyInfoEvent(parameters); break; case "433": this.errNicknameInUseEvent(); break; case "437": this.errUnavailResource(); break; default: this.unrecognisedDataRecievedEvent(data); break; } }