Merge branch 'develop'

This commit is contained in:
Daniel_I_Am 2020-06-08 22:04:21 +02:00
commit 1f221feef3
No known key found for this signature in database
GPG Key ID: 80C428FCC9743E84
17 changed files with 923 additions and 698 deletions

View File

@ -0,0 +1,84 @@
using System;
using System.Data;
using System.Linq;
using System.Threading;
using ChaosBot.Attribute;
using ChaosBot.Database;
using ChaosBot.Database.Entity;
using NUnit.Framework;
namespace ChaosBot.UnitTests
{
public class DataBaseTests
{
[SetUp]
public void SetUp()
{
Program.LoadConfiguration("./appsettings.json");
Program.LoadLogger();
AssemblyController.RegisterDBEntityType(typeof(TestEntity));
}
[TearDown]
public void TearDown()
{
Controller.RawQuery("DROP TABLE TestTable;", readOutput: false);
}
[Test]
public void Insert_CanInsertDataToDBAndDeleteFromDB_True()
{
var testEntity = new TestEntity(1);
Assert.AreEqual(0, TestEntity.Query().Count());
TestEntity.Query().Insert(testEntity);
Assert.AreEqual(1, TestEntity.Query().Count());
TestEntity.Query().Delete();
Assert.AreEqual(0, TestEntity.Query().Count());
}
[Test]
public void InsertUpdateDelete_CheckCanInsertUpdateAndDeleteFromDB_True()
{
Assert.AreEqual("", GetDBContent());
TestEntity.Query().Insert(new TestEntity(5));
Assert.AreEqual("5", GetDBContent());
TestEntity.Query().Where("id", 5).Set("id", 6).Update();
Assert.AreEqual("6", GetDBContent());
TestEntity.Query().Where("id", 6).Delete();
Assert.AreEqual("", GetDBContent());
}
public string GetDBContent()
{
return string.Join(" ", TestEntity.Query().Distinct().Get().Select(o => o.id).ToArray());
}
}
[DBEntity("TestTable")]
public class TestEntity : BaseEntity
{
public long id { get; private set; }
public TestEntity() {}
public TestEntity(int id)
{
this.id = id;
}
public static QueryBuilder<TestEntity> Query()
{
return BaseEntity.Query<TestEntity>();
}
public override void SetFromRow(DataRow row)
{
id = (long)row["id"];
}
}
}

View File

@ -11,12 +11,19 @@ namespace ChaosBot.Attribute
public static class AssemblyController
{
private static Logger _logger = Program._logger;
public static void Register()
public static void RegisterAll()
{
Assembly dbEntityAssembly = Assembly.GetAssembly(typeof(DBEntity));
if (dbEntityAssembly != null)
{
foreach (Type type in dbEntityAssembly.GetTypes())
{
RegisterDBEntityType(type);
}
}
}
public static void RegisterDBEntityType(Type type)
{
try
{
@ -36,7 +43,19 @@ namespace ChaosBot.Attribute
foreach (PropertyInfo prop in type.GetProperties())
{
string columnName = prop.Name;
string columnType = DBEntity.DataTypes.GetValueOrDefault(prop.PropertyType).ToString();
string columnType = null;
if (prop.PropertyType.IsGenericType &&
prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type[] typeArguments = prop.PropertyType.GetGenericArguments();
if (typeArguments.Length == 1)
columnType = DBEntity.DataTypes.GetValueOrDefault(typeArguments[0]).ToString();
}
else
{
columnType = DBEntity.DataTypes.GetValueOrDefault(prop.PropertyType).ToString();
}
StringBuilder constraintNameBuilder = new StringBuilder($"{table}_{columnName}");
List<string> constraintsList = new List<string>();
@ -61,8 +80,10 @@ namespace ChaosBot.Attribute
constraintsList.Insert(0, "CONSTRAINT");
constraintsList.Insert(1, constraintName);
}
string constraints = String.Join(" ", constraintsList);
columnList.Add(new Tuple<string, string, string, string>(columnName, columnType, constraintName, constraints));
columnList.Add(
new Tuple<string, string, string, string>(columnName, columnType, constraintName, constraints));
}
// Check table exists
@ -74,7 +95,7 @@ namespace ChaosBot.Attribute
{
string columnDefs = String.Join(", ", columnList.Select(c => $"{c.Item1} {c.Item2} {c.Item4}"));
string query = $"CREATE TABLE {table} ({columnDefs})";
Controller.RawQuery(query, false);
Controller.RawQuery(query, readOutput: false);
}
else
{
@ -84,7 +105,7 @@ namespace ChaosBot.Attribute
{
string query =
$"ALTER TABLE {table} ADD COLUMN {column.Item1} {column.Item2} {column.Item4}";
Controller.RawQuery(query, false, true);
Controller.RawQuery(query, readOutput: false, throwError: true);
}
catch
{
@ -101,5 +122,3 @@ namespace ChaosBot.Attribute
}
}
}
}
}

View File

@ -26,7 +26,7 @@ namespace ChaosBot.Database
/// <param name="readOutput">Whether to read the output and return it as a <c>DataFrame</c></param>
/// <param name="throwError">Whether to throw any exceptions or to log and shrug.</param>
/// <returns></returns>
public static DataTable RawQuery(string query, bool readOutput = true, bool throwError = false)
public static DataTable RawQuery(string query, Dictionary<string, object> parameters = null, bool readOutput = true, bool throwError = false)
{
DataTable dt = new DataTable();
@ -41,10 +41,23 @@ namespace ChaosBot.Database
SqliteCommand cmd = _conn.CreateCommand();
cmd.CommandText = query;
// Add parameters if they exist
if (parameters != null)
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.Key, parameter.Value);
}
}
// Prepare the statement
_logger.Trace($"Database.Controller.RawQuery: Running query {cmd.CommandText}");
cmd.Prepare();
if (readOutput)
{
// output needs to be read, make a reader and fill the datatable with the data
SqliteDataReader executeReader = cmd.ExecuteReader(CommandBehavior.SingleResult);
SqliteDataReader executeReader = cmd.ExecuteReader();
dt.Load(executeReader);
}
else
@ -71,321 +84,5 @@ namespace ChaosBot.Database
return dt;
}
/// <summary>
/// Insert a list of parameters into a table in the database
/// </summary>
/// <code>
/// string table = "SomeTable";
/// Dictionary&lt;string, object&gt; parameters = new Dictionary&lt;string, object&gt;
/// {
/// { "someInt", 123 },
/// { "someString", "asdf" },
/// { "someChar", 'x' }
/// }
///
/// Controller.InsertQuery(table, parameters);
/// </code>
/// <param name="table">Table to insert into</param>
/// <param name="parameters">List of parameters to insert to the row. Every type is a key</param>
public static void InsertQuery(string table, Dictionary<string, object> parameters)
{
try
{
using (_conn)
{
// Open the SQLite connection
_conn.Open();
// Start the command creation
SqliteCommand cmd = _conn.CreateCommand();
// Build the command bit by bit
// INSERT INTO {table} (key1, key2, key3) VALUES (@key1,@key2,@key3)
StringBuilder commandText = new StringBuilder();
commandText.Append("INSERT INTO ");
commandText.Append(table);
commandText.Append(" (");
foreach (string key in parameters.Keys)
{
commandText.Append($"{key}, ");
}
commandText.Remove(commandText.Length - 2, 2);
commandText.Append(") VALUES (");
foreach (string key in parameters.Keys)
{
// We use @key to indicate the parameter placeholder
commandText.Append($"@{key},");
}
// Remove the trailing comma
commandText.Remove(commandText.Length - 1, 1);
commandText.Append(")");
// Assign onto QueryCommand
cmd.CommandText = commandText.ToString();
// Replace all the parameters to the query
foreach (string key in parameters.Keys)
{
cmd.Parameters.AddWithValue($"@{key}", parameters.GetValueOrDefault(key));
}
// Prepare the parameters
cmd.Prepare();
// Execute, do not return anything
cmd.ExecuteNonQuery();
_conn.Close();
}
}
catch (Exception ex)
{
_logger.Fatal($"Database.Controller.InsertQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
}
/// <summary>
/// Update rows in the database
/// </summary>
/// <code>
/// string table = "SomeTable";
/// Dictionary&lt;string, object&gt; values = new Dictionary&lt;string, object&gt;
/// {
/// {"key", "newValue"}
/// };
/// Dictionary&lt;string, object&gt; parameters = new Dictionary&lt;string, object&gt;
/// {
/// {"key", "oldValue"}
/// };
/// Controller.UpdateQuery(table, values, parameters);
/// </code>
/// <param name="table">Table to update data in</param>
/// <param name="values">List of keys to set. Equivalent of SQL: SET {key} = {value}</param>
/// <param name="parameters">List of filters to apply in the SQL WHERE condition</param>
public static void UpdateQuery(string table, Dictionary<string, object> values, Dictionary<string, object> parameters)
{
try
{
using (_conn)
{
// Open SQLite connection
_conn.Open();
// Create the command
SqliteCommand cmd = _conn.CreateCommand();
// Build the commandtext
// UPDATE {table} SET {key}=@val_{key} WHERE {key}=@fil_{key}
StringBuilder commandText = new StringBuilder();
commandText.Append("UPDATE ");
commandText.Append(table);
commandText.Append(" SET ");
// Build the list of values
List<string> updateList = new List<string>();
foreach (string key in values.Keys)
{
updateList.Add($"{key}=@val_{key} ");
cmd.Parameters.AddWithValue($@"val_{key}", values.GetValueOrDefault(key));
}
// Append the list of values, comma-separated
commandText.Append(string.Join(", ", updateList));
// Build the list of filters
List<string> filterList = new List<string>();
foreach (string key in parameters.Keys)
{
filterList.Add($"{key}=@fil_{key} ");
cmd.Parameters.AddWithValue($"@fil_{key}", parameters.GetValueOrDefault(key));
}
if (filterList.Count > 0)
{
// Prepend with WHERE if there are parameters
commandText.Append("WHERE ");
// Append the list of filters AND separated
commandText.Append(string.Join("AND ", filterList));
}
// Assign the command
cmd.CommandText = commandText.ToString();
// Prepare the parameters
cmd.Prepare();
// Execute, do not return
cmd.ExecuteNonQuery();
// Close connection
_conn.Close();
}
}
catch (Exception ex)
{
_logger.Fatal($"Database.Controller.UpdateQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
}
public static int TransactionQuery(List<SqliteCommand> cmds)
{
SqliteCommand command = _conn.CreateCommand();
SqliteTransaction transaction;
_conn.Open();
// Start a local transaction.
transaction = _conn.BeginTransaction();
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = _conn;
command.Transaction = transaction;
try
{
foreach (var cmd in cmds)
{
command.CommandText = cmd.CommandText;
command.ExecuteNonQuery();
}
// Attempt to commit the transaction.
transaction.Commit();
_logger.Info($"{cmds.Count} record(s) are written to database.");
}
catch (Exception ex)
{
_logger.Warn("Commit Exception Type: {0}", ex.GetType());
_logger.Warn(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
_logger.Warn("Rollback Exception Type: {0}", ex2.GetType());
_logger.Warn(" Message: {0}", ex2.Message);
}
return 0;
}
_conn.Close();
return cmds.Count;
}
public static DataTable SelectQuery(string table, string selectColumns = "*", Dictionary<string, object> filterColumns = null, string orderByKey = null)
{
DataTable dt = new DataTable();
try
{
using (_conn)
{
_conn.Open();
SqliteCommand cmd = _conn.CreateCommand();
string filter = null;
if (filterColumns != null)
{
List<string> filterList = new List<string>();
foreach (string key in filterColumns.Keys)
{
filterList.Add($"{key} = @{key}");
}
filter = $"WHERE {Strings.Join(filterList.ToArray(), " AND ")}";
foreach (string key in filterColumns.Keys)
{
cmd.Parameters.AddWithValue($@"{key}", filterColumns.GetValueOrDefault(key));
}
}
string order = null;
if (orderByKey != null)
{
order = $"ORDER BY {orderByKey}";
}
string query = $"SELECT {selectColumns} FROM {table} {filter} {order}";
cmd.CommandText = query;
cmd.Prepare();
SqliteDataReader executeReader = cmd.ExecuteReader();
dt.Load(executeReader);
_conn.Close();
}
}
catch (Exception ex)
{
_logger.Fatal($"Database.Controller.SelectQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
return dt;
}
public static void DeleteQuery(string table, Dictionary<string, object> filterColumns = null, string orderByKey = null, int limit = -1, int offset = -1)
{
try
{
using (_conn)
{
_conn.Open();
SqliteCommand cmd = _conn.CreateCommand();
string filter = null;
if (filterColumns != null)
{
List<string> filterList = new List<string>();
foreach (string key in filterColumns.Keys)
{
filterList.Add($"{key} = @{key}");
}
filter = $"WHERE {Strings.Join(filterList.ToArray(), " AND ")}";
foreach (string key in filterColumns.Keys)
{
cmd.Parameters.AddWithValue($@"{key}", filterColumns.GetValueOrDefault(key));
}
}
string order = null;
if (orderByKey != null)
{
order = $"ORDER BY {orderByKey}";
}
string limitString = limit > 0 ? $"LIMIT {limit}" : null;
string offsetString = offset > 0 ? $"OFFSET {offset}" : null;
string query = $"DELETE FROM {table} {filter} {order} {limitString} {offsetString}";
cmd.CommandText = query;
cmd.Prepare();
cmd.ExecuteNonQuery();
_conn.Close();
}
}
catch (Exception ex)
{
_logger.Fatal($"Database.Controller.DeleteQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Data;
using System.Linq;
using ChaosBot.Attribute;
using ChaosBot.Database;
namespace ChaosBot.Database.Entity
{
public abstract class BaseEntity
{
protected BaseEntity() {}
public abstract void SetFromRow(DataRow row);
protected static QueryBuilder<T> Query<T>() where T : BaseEntity, new()
{
var dbEntityAttribute = typeof(T).GetCustomAttributes(
typeof(DBEntity),
true
).FirstOrDefault() as DBEntity;
if (dbEntityAttribute != null)
{
return new QueryBuilder<T>(dbEntityAttribute.Table);
}
throw new SystemException($"Class {typeof(T)} does not have an attribute of {typeof(DBEntity)} set");
}
}
}

View File

@ -1,20 +1,24 @@
using System;
using System.Data;
using ChaosBot.Attribute;
namespace ChaosBot.Database.Entity
{
[DBEntity("PointsTable")]
public class Points
public class Points : BaseEntity
{
[DBPrimaryKey]
[DBAutoIncrement]
[DBNotNull]
[DBUnique]
public int id { get; }
public Nullable<int> id { get; private set; }
public int points { get; private set; }
public string userId { get; private set; }
public string guildId { get; private set; }
public long userId { get; private set; }
public long guildId { get; private set; }
public Points(int id, string userId, string guildId, int points)
public Points() {}
public Points(int id, long userId, long guildId, int points)
{
this.id = id;
this.userId = userId;
@ -22,11 +26,24 @@ namespace ChaosBot.Database.Entity
this.points = points;
}
public Points(string userId, string guildId, int points)
public Points(long userId, long guildId, int points)
{
this.points = points;
this.userId = userId;
this.guildId = guildId;
}
public static QueryBuilder<Points> Query()
{
return BaseEntity.Query<Points>();
}
public override void SetFromRow(DataRow row)
{
id = (int)row["id"];
userId = (long)row["userId"];
guildId = (long)row["guildId"];
points = (int)row["points"];
}
}
}

View File

@ -1,29 +1,45 @@
using System;
using System.Data;
using ChaosBot.Attribute;
namespace ChaosBot.Database.Entity
{
[DBEntity("RaffleTable")]
public class Raffle
public class Raffle : BaseEntity
{
[DBPrimaryKey]
[DBAutoIncrement]
[DBNotNull]
[DBUnique]
public int id { get; }
public string userId { get; private set; }
public string guildId { get; private set; }
public Nullable<int> id { get; private set; }
public long userId { get; private set; }
public long guildId { get; private set; }
public Raffle(int id, string userId, string guildId)
public Raffle() {}
public Raffle(int id, long userId, long guildId)
{
this.id = id;
this.userId = userId;
this.guildId = guildId;
}
public Raffle(string userId, string guildId)
public Raffle(long userId, long guildId)
{
this.userId = userId;
this.guildId = guildId;
}
public static QueryBuilder<Raffle> Query()
{
return BaseEntity.Query<Raffle>();
}
public override void SetFromRow(DataRow row)
{
id = (int)row["id"];
userId = (long)row["userid"];
guildId = (long) row["guildid"];
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Text.Json;
@ -8,14 +9,15 @@ using ChaosBot.Attribute;
namespace ChaosBot.Database.Entity
{
[DBEntity("ServerConfigurationFlags")]
public class ServerConfigurationFlag<T>
public class ServerConfigurationFlag<T> : BaseEntity
{
[DBUnique]
public string key { get; }
public string key { get; private set; }
public string serializedValue { get; }
public string serializedValue { get; set; }
public long guildId { get; }
public long guildId { get; private set; }
public ServerConfigurationFlag() {}
public ServerConfigurationFlag(string key, T value, ulong guildId)
{
@ -23,6 +25,29 @@ namespace ChaosBot.Database.Entity
this.key = key;
this.guildId = Convert.ToInt64(guildId);
}
public ServerConfigurationFlag(string key, T value, long guildId)
{
this.serializedValue = Serialize(value);
this.key = key;
this.guildId = guildId;
}
public ServerConfigurationFlag(string key, long guildId)
{
this.key = key;
this.guildId = guildId;
}
public static QueryBuilder<ServerConfigurationFlag<T>> Query()
{
return BaseEntity.Query<ServerConfigurationFlag<T>>();
}
public override void SetFromRow(DataRow row)
{
key = (string)row["key"];
serializedValue = (string)row["serializedValue"];
guildId = (long)row["guildId"];
}
public T GetValue()
{

View File

@ -0,0 +1,16 @@
using NLog.Filters;
namespace ChaosBot.Database
{
public struct FilterValue
{
public object Value;
public string Comparison;
public FilterValue(object value, string comparison = null)
{
this.Value = value;
this.Comparison = comparison;
}
}
}

View File

@ -0,0 +1,278 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using ChaosBot.Attribute;
using ChaosBot.Database.Entity;
namespace ChaosBot.Database
{
public class QueryBuilder<T> where T : BaseEntity, new()
{
private string _table;
private bool _distinct;
private Dictionary<string, FilterValue> _whereConditions;
private Dictionary<string, object> _setList;
private List<string> _orderKeys;
private List<string> _groupByList;
private int _limit;
private int _offset;
public QueryBuilder(string table)
{
_table = table;
_distinct = false;
_whereConditions = new Dictionary<string, FilterValue>();
_setList = new Dictionary<string, object>();
_orderKeys = new List<string>();
_groupByList = new List<string>();
_limit = -1;
_offset = -1;
}
/*
* Fetch all records from a database
*/
public List<T> All()
{
QueryBuilderRaw query = new QueryBuilderRaw();
DataTable dt = query
.Select()
.Append("*")
.FromTable(_table)
.Run();
List<T> returnList = new List<T>();
foreach (DataRow row in dt.Rows)
{
T newObject = new T();
newObject.SetFromRow(row);
returnList.Add(newObject);
}
return returnList;
}
/*
* Set a where condition
*/
public QueryBuilder<T> Where(string key, object value, string comparison = null)
{
_whereConditions.Add(key, new FilterValue(value, comparison));
return this;
}
/*
* Set distinct
*/
public QueryBuilder<T> Distinct()
{
_distinct = true;
return this;
}
/*
* Set SET field
*/
public QueryBuilder<T> Set(string key, object value)
{
_setList.Add(key, value);
return this;
}
/*
* Set an order key
*/
public QueryBuilder<T> OrderBy(string key)
{
_orderKeys.Add(key);
return this;
}
/*
* Set a groupBy key
*/
public QueryBuilder<T> GroupBy(string key)
{
_groupByList.Add(key);
return this;
}
/*
* Limit amount of responses
*/
public QueryBuilder<T> Limit(int amount)
{
_limit = amount;
return this;
}
public QueryBuilder<T> Offset(int amount)
{
_offset = amount;
return this;
}
public QueryBuilder<T> Limit(int limit, int offset)
{
Limit(limit);
return Offset(offset);
}
/*
* Basic mathematical operations
*/
public int Count()
{
QueryBuilderRaw query = new QueryBuilderRaw();
long amount = (long)query
.Select()
.Append("COUNT(*) as count")
.FromTable(_table)
.Run().Rows[0]["count"];
return Convert.ToInt32(amount);
}
/*
* Basic logical operations
*/
public bool Exists()
{
QueryBuilderRaw query = new QueryBuilderRaw();
return (bool)query
.Select()
.Append("COUNT(*)>0 as present")
.FromTable(_table)
.Run().Rows[0]["present"];
}
public bool DoesNotExist()
{
QueryBuilderRaw query = new QueryBuilderRaw();
return (bool)query
.Select()
.Append("COUNT(*)=0 as notPresent")
.FromTable(_table)
.Run().Rows[0]["notPresent"];
}
/*
* Actions
*/
public List<T> Get()
{
List<T> returnList = new List<T>();
QueryBuilderRaw query = new QueryBuilderRaw();
query
.Select();
if (_distinct)
query.Distinct();
query
.Append("*")
.FromTable(_table);
if (_whereConditions.Keys.Count > 0)
query.Where(_whereConditions);
if (_groupByList.Count > 0)
query.GroupBy(_groupByList);
if (_orderKeys.Count > 0)
query.OrderBy(_orderKeys);
if (_limit >= 0)
{
if (_offset >= 0)
{
query.Limit(_limit, _offset);
}
else
{
query.Limit(_limit);
}
}
DataTable dt = query.Run();
foreach (DataRow row in dt.Rows)
{
T newObject = new T();
newObject.SetFromRow(row);
returnList.Add(newObject);
}
return returnList;
}
public T First()
{
Limit(1);
List<T> list = Get();
if (list.Count > 0)
return list[0];
return null;
}
public void Insert(T obj)
{
Dictionary<string, object> objectKeysAndValues = GetObjectKeysAndValues(obj);
QueryBuilderRaw query = new QueryBuilderRaw();
query
.Insert()
.IntoTable(_table)
.Columns(new List<string>(objectKeysAndValues.Keys))
.Values(objectKeysAndValues);
query.Run();
}
public void Update()
{
QueryBuilderRaw query = new QueryBuilderRaw();
query
.Update()
.Table(_table)
.Set(_setList);
if (_whereConditions.Keys.Count > 0)
query.Where(_whereConditions);
query.Run();
}
public void Delete()
{
QueryBuilderRaw query = new QueryBuilderRaw();
query
.Delete()
.FromTable(_table);
if (_whereConditions.Keys.Count > 0)
query.Where(_whereConditions);
query.Run();
}
/*
* Helpers
*/
private Dictionary<string, object> GetObjectKeysAndValues(T obj)
{
var returnValue = new Dictionary<string, object>();
foreach (PropertyInfo prop in typeof(T).GetProperties())
{
string columnName = prop.Name;
object value = prop.GetValue(obj);
if (value != null)
returnValue.Add(columnName, value);
}
return returnValue;
}
}
}

View File

@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace ChaosBot.Database
{
public class QueryBuilderRaw
{
private StringBuilder _query;
private Dictionary<string, object> _parameters;
private int keyIndex = 0;
public QueryBuilderRaw()
{
_query = new StringBuilder();
_parameters = new Dictionary<string, object>();
}
public QueryBuilderRaw Append(string text)
{
_query.Append(text);
if (!text.EndsWith(" "))
_query.Append(" ");
return this;
}
public DataTable Run()
{
return Controller.RawQuery(_query.ToString(), _parameters);
}
public QueryBuilderRaw Select()
{
return Append("SELECT");
}
public QueryBuilderRaw Insert(string alternativeAction = null)
{
Append("INSERT");
if (alternativeAction != null)
Append(alternativeAction);
return this;
}
public QueryBuilderRaw Update(string alternativeAction = null)
{
Append("UPDATE");
if (alternativeAction != null)
Append(alternativeAction);
return this;
}
public QueryBuilderRaw Delete()
{
return Append("DELETE");
}
public QueryBuilderRaw Distinct()
{
return Append("DISTINCT");
}
public QueryBuilderRaw Table(string table)
{
return Append(table);
}
public QueryBuilderRaw FromTable(string table)
{
Append("FROM");
return Table(table);
}
public QueryBuilderRaw IntoTable(string table)
{
Append("INTO");
return Table(table);
}
public QueryBuilderRaw Columns(List<string> columnList)
{
Append("(");
Append(String.Join(", ", columnList));
Append(")");
return this;
}
public QueryBuilderRaw Values(Dictionary<string, object> keyValueList)
{
Append("VALUES (");
List<string> parameterKeys = new List<string>();
foreach (KeyValuePair<string, object> pair in keyValueList)
{
string parameterName = AddParameterAndReturnKey(pair.Key, pair.Value);
parameterKeys.Add(parameterName);
}
Append(string.Join(", ", parameterKeys));
Append(")");
return this;
}
public QueryBuilderRaw Set(Dictionary<string, object> keyValueList)
{
Append("SET");
List<string> parameterKeys = new List<string>();
foreach (KeyValuePair<string, object> pair in keyValueList)
{
string parameterName = AddParameterAndReturnKey(pair.Key, pair.Value);
parameterKeys.Add($"{pair.Key} = {parameterName}");
}
Append(string.Join(", ", parameterKeys));
return this;
}
public QueryBuilderRaw Where(Dictionary<string, FilterValue> whereCondition)
{
Append("WHERE");
List<string> whereConditionList = new List<string>();
foreach (string key in whereCondition.Keys)
{
FilterValue value = whereCondition.GetValueOrDefault(key);
string parameterName = AddParameterAndReturnKey(key, value.Value);
whereConditionList.Add($"{key} {value.Comparison ?? "="} {parameterName}");
}
Append(string.Join(" AND ", whereConditionList));
return this;
}
public QueryBuilderRaw GroupBy(List<string> groupByList)
{
Append("GROUP BY");
return Append(string.Join(", ", groupByList));
}
public QueryBuilderRaw OrderBy(List<string> orderKeys)
{
Append("ORDER BY");
return Append(string.Join(", ", orderKeys));
}
public QueryBuilderRaw Limit(int limit)
{
return Append($"LIMIT {limit}");
}
public QueryBuilderRaw Limit(int limit, int offset)
{
return Append($"LIMIT {limit} OFFSET {offset}");
}
private void AddParameter(string parameterName, object value)
{
_parameters.Add(parameterName, value);
}
private string AddParameterAndReturnKey(string key, object value)
{
string parameterKey = GetUniqueParameterName(key);
AddParameter(parameterKey, value);
return parameterKey;
}
private string GetStaticParameterName(string key)
{
return $"@databasevalue{key}";
}
private string GetUniqueParameterName(string key)
{
return $"{GetStaticParameterName(key)}_{keyIndex++}";
}
}
}

View File

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Data;
using ChaosBot.Database.Entity;
using Microsoft.Extensions.Configuration;
using NLog;
namespace ChaosBot.Database.Repository
{
@ -43,13 +42,13 @@ namespace ChaosBot.Database.Repository
public static string GetValueRaw(string configurationFlag, long guildId)
{
Dictionary<string, object> filterColumns = new Dictionary<string, object>();
filterColumns.Add("key", configurationFlag);
filterColumns.Add("guildId", guildId);
DataTable valueTable = Controller.SelectQuery(ServersTable, filterColumns: filterColumns);
if (valueTable.Rows.Count == 1)
Dictionary<string, FilterValue> filterColumns = new Dictionary<string, FilterValue>();
filterColumns.Add("key", new FilterValue(configurationFlag));
filterColumns.Add("guildId", new FilterValue(guildId));
ServerConfigurationFlag<string> serverConfigurationFlag = ServerConfigurationFlag<string>.Query().Where("key", configurationFlag).Where("guildId", guildId).First();
if (serverConfigurationFlag != null)
{
return valueTable.Rows[0]["serializedValue"].ToString();
return serverConfigurationFlag.serializedValue;
}
return null;
@ -81,23 +80,22 @@ namespace ChaosBot.Database.Repository
{
try
{
Dictionary<string, object> filterColumns = new Dictionary<string, object>();
filterColumns.Add("key", configurationFlag);
filterColumns.Add("guildId", guildId);
Dictionary<string, object> newValue = new Dictionary<string, object>();
newValue.Add("key", configurationFlag);
newValue.Add("guildId", guildId);
newValue.Add("serializedValue", serializedValue);
DataTable valueTable = Controller.SelectQuery(ServersTable, "COUNT(*)", filterColumns);
if ((long) valueTable.Rows[0]["COUNT(*)"] == 1)
int matchCount = ServerConfigurationFlag<string>.Query().Where("key", configurationFlag).Where("guildId", guildId).Count();
if (matchCount > 0)
{
Controller.UpdateQuery(ServersTable, newValue, filterColumns);
ServerConfigurationFlag<string>.Query()
.Where("key", configurationFlag)
.Where("guildId", guildId)
.Set("key", configurationFlag)
.Set("guildId", guildId)
.Set("serializedValue", serializedValue)
.Update();
return;
}
Controller.InsertQuery(ServersTable, newValue);
ServerConfigurationFlag<string> newValue = new ServerConfigurationFlag<string>(configurationFlag, guildId);
newValue.serializedValue = serializedValue;
ServerConfigurationFlag<string>.Query().Insert(newValue);
}
catch (Exception ex)
{

View File

@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using ChaosBot.Database.Entity;
using Microsoft.Data.Sqlite;
namespace ChaosBot.Database.Repository
{
@ -14,136 +11,66 @@ namespace ChaosBot.Database.Repository
public static Points[] All()
{
DataTable dataTable = Controller.SelectQuery(Table);
List<Points> pointsList = Points.Query().All();
List<Points> pointslist = new List<Points>();
foreach (DataRow row in dataTable.Rows)
{
int id = Convert.ToInt32((long)row["id"]);
int points = Convert.ToInt32(row["points"]);
string userId = row["userId"].ToString();
string guildId = row["guildId"].ToString();
pointslist.Add(new Points(id, userId, guildId, points));
return pointsList.ToArray();
}
return pointslist.ToArray();
}
public static Points[] All(string guildId)
public static Points[] All(long guildId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("guildId", guildId);
List<Points> pointsList = Points.Query().Where("guildId", guildId).All();
DataTable dataTable = Controller.SelectQuery(Table, filterColumns: filterDict);
List<Points> pointslist = new List<Points>();
foreach (DataRow row in dataTable.Rows)
{
int idFetch = Convert.ToInt32((long)row["id"]);
int pointsFetch = Convert.ToInt32(row["points"]);
string userIdFetch = row["userId"].ToString();
string guildIdFetch = row["guildId"].ToString();
pointslist.Add(new Points(idFetch, userIdFetch, guildIdFetch, pointsFetch));
}
return pointslist.ToArray();
return pointsList.ToArray();
}
public static int Total(string userId, string guildId)
public static int Total(long userId, long guildId)
{
Dictionary<string, object> selectfilterDict = new Dictionary<string, object>();
selectfilterDict.Add("userId", userId);
selectfilterDict.Add("guildId", guildId);
Points userPoints = Points.Query().Where("userId", userId).Where("guildId", guildId).First();
DataTable dt = Controller.SelectQuery(Table, "points", selectfilterDict);
if (Convert.ToInt32(dt.Rows.Count) != 0)
return Convert.ToInt32(dt.Rows[0]["points"]);
else
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("userId", userId);
dict.Add("guildId", guildId);
dict.Add("points", 0);
Controller.InsertQuery(Table, dict);
}
if (userPoints != null)
return userPoints.points;
Points emptyUserPoints = new Points(userId, guildId, 0);
Points.Query().Insert(emptyUserPoints);
return 0;
}
public static int Count(string userId, string guildId)
public static int Count(long userId, long guildId)
{
Dictionary<string, object> selectfilterDict = new Dictionary<string, object>();
selectfilterDict.Add("userId", userId);
selectfilterDict.Add("guildId", guildId);
DataTable dt = Controller.SelectQuery(Table, "COUNT(*)", selectfilterDict);
return Convert.ToInt32(dt.Rows[0]["COUNT(*)"]);
return Points.Query().Where("userId", userId).Where("guildId", guildId).Count();
}
public static int Add(string userId, int points, string guildId)
public static int Add(long userId, int points, long guildId)
{
Dictionary<string, object> selectfilterDict = new Dictionary<string, object>();
selectfilterDict.Add("userId", userId);
selectfilterDict.Add("guildId", guildId);
DataTable dt = Controller.SelectQuery(Table, "points", selectfilterDict);
if (Convert.ToInt32(dt.Rows.Count) != 0)
Points userPoints = Points.Query().Where("userId", userId).Where("guildId", guildId).First();
if (userPoints != null)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("userId", userId);
filterDict.Add("guildId", guildId);
Dictionary<string, object> updateDict = new Dictionary<string, object>();
updateDict.Add("points", Convert.ToInt32(dt.Rows[0]["points"]) + points);
Controller.UpdateQuery(Table, updateDict, filterDict);
return Convert.ToInt32(dt.Rows[0]["points"]) + points;
Points.Query().Where("userId", userId).Where("guildId", guildId).Set("points", userPoints.points + points).Update();
return userPoints.points + points;
}
else
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("userId", userId);
dict.Add("guildId", guildId);
dict.Add("points", points);
Controller.InsertQuery(Table, dict);
Points newUserPoints = new Points(userId, guildId, points);
Points.Query().Insert(newUserPoints);
return points;
}
}
public static int Remove(string userId, int points, string guildId)
public static int Remove(long userId, int points, long guildId)
{
Dictionary<string, object> selectfilterDict = new Dictionary<string, object>();
selectfilterDict.Add("userId", userId);
selectfilterDict.Add("guildId", guildId);
DataTable dt = Controller.SelectQuery(Table, "points", selectfilterDict);
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("userId", userId);
filterDict.Add("guildId", guildId);
Dictionary<string, object> updateDict = new Dictionary<string, object>();
updateDict.Add("points", Convert.ToInt32(dt.Rows[0]["points"]) - points);
Controller.UpdateQuery(Table, updateDict, filterDict);
return Convert.ToInt32(dt.Rows[0]["points"]) - points;
Points userPoints = Points.Query().Where("userId", userId).Where("guildId", guildId).First();
Points.Query().Where("userId", userId).Where("guildId", guildId).Set("points", userPoints.points - points).Update();
return userPoints.points - points;
}
public static void Delete(int userId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("userId", userId);
Controller.DeleteQuery(Table, filterDict);
}
Points.Query().Where("userId", userId).Delete();
}
}
}

View File

@ -17,17 +17,7 @@ namespace ChaosBot.Database.Repository
/// <returns>List of raffles</returns>
public static Raffle[] All()
{
DataTable dataTable = Controller.SelectQuery(Table);
List<Raffle> raffles = new List<Raffle>();
foreach (DataRow row in dataTable.Rows)
{
int id = Convert.ToInt32((long) row["id"]);
string userId = row["userId"].ToString();
string guildId = row["guildId"].ToString();
raffles.Add(new Raffle(id, userId, guildId));
}
var raffles = Raffle.Query().All();
return raffles.ToArray();
}
@ -37,22 +27,9 @@ namespace ChaosBot.Database.Repository
/// </summary>
/// <param name="guildId"></param>
/// <returns>List of raffles</returns>
public static Raffle[] All(string guildId)
public static Raffle[] All(long guildId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("guildId", guildId);
DataTable dataTable = Controller.SelectQuery(Table, filterColumns: filterDict);
List<Raffle> raffles = new List<Raffle>();
foreach (DataRow row in dataTable.Rows)
{
int idFetch = Convert.ToInt32((long) row["id"]);
string userIdFetch = row["userId"].ToString();
string guildIdFetch = row["guildId"].ToString();
raffles.Add(new Raffle(idFetch, userIdFetch, guildIdFetch));
}
var raffles = Raffle.Query().Where("guildId", guildId).All();
return raffles.ToArray();
}
@ -63,9 +40,7 @@ namespace ChaosBot.Database.Repository
/// <returns>Amount of raffles</returns>
public static int Count()
{
DataTable dataTable = Controller.SelectQuery(Table, "COUNT(*)");
return Convert.ToInt32(dataTable.Rows[0]["COUNT(*)"]);
return Raffle.Query().Count();
}
/// <summary>
@ -73,14 +48,9 @@ namespace ChaosBot.Database.Repository
/// </summary>
/// <param name="guildId"></param>
/// <returns>Amount of raffles</returns>
public static int Count(string guildId)
public static int Count(long guildId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("guildId", guildId);
DataTable dataTable = Controller.SelectQuery(Table, "COUNT(*)", filterDict);
return Convert.ToInt32(dataTable.Rows[0]["COUNT(*)"]);
return Raffle.Query().Where("guildId", guildId).Count();
}
/// <summary>
@ -89,15 +59,9 @@ namespace ChaosBot.Database.Repository
/// <param name="userId"></param>
/// <param name="guildId"></param>
/// <returns>Amount of raffles</returns>
public static int Count(string userId, string guildId)
public static int Count(long userId, long guildId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("userId", userId);
filterDict.Add("guildId", guildId);
DataTable dataTable = Controller.SelectQuery(Table, "COUNT(*)", filterDict);
return Convert.ToInt32(dataTable.Rows[0]["COUNT(*)"]);
return Raffle.Query().Where("userId", userId).Where("guildId", guildId).Count();
}
/// <summary>
@ -105,22 +69,9 @@ namespace ChaosBot.Database.Repository
/// </summary>
/// <param name="userId"></param>
/// <returns>List of raffles</returns>
public static Raffle[] SelectUser(string userId)
public static Raffle[] SelectUser(long userId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("userId", userId);
DataTable dataTable = Controller.SelectQuery(Table, filterColumns: filterDict);
List<Raffle> raffles = new List<Raffle>();
foreach (DataRow row in dataTable.Rows)
{
int id = Convert.ToInt32((long) row["id"]);
string userIdFetch = row["userId"].ToString();
string guildIdFetch = row["guildId"].ToString();
raffles.Add(new Raffle(id, userIdFetch, guildIdFetch));
}
List<Raffle> raffles = Raffle.Query().Where("userId", userId).Get();
return raffles.ToArray();
}
@ -131,23 +82,9 @@ namespace ChaosBot.Database.Repository
/// <param name="userId"></param>
/// <param name="guildId"></param>
/// <returns>List of raffles</returns>
public static Raffle[] SelectUser(string userId, string guildId)
public static Raffle[] SelectUser(long userId, long guildId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("userId", userId);
filterDict.Add("guildId", guildId);
DataTable dataTable = Controller.SelectQuery(Table, filterColumns: filterDict);
List<Raffle> raffles = new List<Raffle>();
foreach (DataRow row in dataTable.Rows)
{
int id = Convert.ToInt32((long) row["id"]);
string userIdFetch = row["userId"].ToString();
string guildIdFetch = row["guildId"].ToString();
raffles.Add(new Raffle(id, userIdFetch, guildIdFetch));
}
List<Raffle> raffles = Raffle.Query().Where("userId", userId).Where("guildId", guildId).Get();
return raffles.ToArray();
}
@ -158,12 +95,7 @@ namespace ChaosBot.Database.Repository
/// <param name="raffle"></param>
public static void Insert(Raffle raffle)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("userId", raffle.userId);
dict.Add("guildId", raffle.guildId);
Controller.InsertQuery(Table, dict);
Raffle.Query().Insert(raffle);
}
/// <summary>
@ -174,12 +106,7 @@ namespace ChaosBot.Database.Repository
{
foreach (var raf in raffles)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("userId", raf.userId);
dict.Add("guildId", raf.guildId);
Controller.InsertQuery(Table, dict);
Raffle.Query().Insert(raf);
}
}
@ -188,32 +115,18 @@ namespace ChaosBot.Database.Repository
/// </summary>
/// <param name="guildId"></param>
/// <returns>Random raffle</returns>
public static Raffle PickRandom(string guildId)
public static Raffle PickRandom(long guildId)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("guildId", guildId);
DataTable dataTable = Controller.SelectQuery(Table, "*", filterDict, "RANDOM()");
if (dataTable.Rows.Count == 0) return null;
DataRow row = dataTable.Rows[0];
int idFetch = Convert.ToInt32((long)row["id"]);
string userIdFetch = row["userId"].ToString();
string guildIdFetch = row["guildId"].ToString();
return new Raffle(idFetch, userIdFetch, guildIdFetch);
return Raffle.Query().Where("guildId", guildId).OrderBy("RANDOM()").First();
}
/// <summary>
/// Clear all <c>Raffle</c>s for a given guild
/// </summary>
/// <param name="guildId"></param>
public static void ClearRaffle(string guildId)
public static void ClearRaffle(long guildId)
{
Dictionary<string,object> filterDict = new Dictionary<string, object>();
filterDict.Add("guildId", guildId);
Controller.DeleteQuery(Table, filterDict);
Raffle.Query().Where("guildId", guildId).Delete();
}
/// <summary>
@ -222,10 +135,7 @@ namespace ChaosBot.Database.Repository
/// <param name="id"></param>
public static void Delete(int id)
{
Dictionary<string, object> filterDict = new Dictionary<string, object>();
filterDict.Add("id", id);
Controller.DeleteQuery(Table, filterDict);
Raffle.Query().Where("id", id).Delete();
}
}
}

View File

@ -58,7 +58,7 @@ namespace ChaosBot.Discord.Modules
[Alias("points info")]
public async Task PointsCommandTotal()
{
int cur = PointsRepository.Total(Context.User.Id.ToString(), Context.Guild.Id.ToString());
int cur = PointsRepository.Total(Convert.ToInt64(Context.User.Id), Convert.ToInt64(Context.Guild.Id));
await ReplyAsync($"You have {cur} points.", false);
}
@ -72,7 +72,7 @@ namespace ChaosBot.Discord.Modules
{
ulong userId = Convert.ToUInt64(user.Substring(3, user.Length - 4));
await ReplyAsync($"{Context.User.Mention} has given <@{userId}> {amount} points for a total of {PointsRepository.Add(userId.ToString(), amount, Context.Guild.Id.ToString())} points.", false);
await ReplyAsync($"{Context.User.Mention} has given <@{userId}> {amount} points for a total of {PointsRepository.Add(Convert.ToInt64(userId), amount, Convert.ToInt64(Context.Guild.Id))} points.", false);
}
else
await ReplyAsync($"NO ACCESS");
@ -85,9 +85,9 @@ namespace ChaosBot.Discord.Modules
public async Task RaffleCommandRemove(string user, int amount = 1)
{
ulong userId = Convert.ToUInt64(user.Substring(3, user.Length - 4));
int cur = PointsRepository.Total(Context.User.Id.ToString(), Context.Guild.Id.ToString());
int cur = PointsRepository.Total(Convert.ToInt64(Context.User.Id), Convert.ToInt64(Context.Guild.Id));
if (cur > amount)
await ReplyAsync($"{Context.User.Mention} has removed {amount} points from <@{userId}> for a total of {PointsRepository.Remove(userId.ToString(), amount, Context.Guild.Id.ToString())} points.", false);
await ReplyAsync($"{Context.User.Mention} has removed {amount} points from <@{userId}> for a total of {PointsRepository.Remove(Convert.ToInt64(userId), amount, Convert.ToInt64(Context.Guild.Id))} points.", false);
else
await ReplyAsync($"{Context.User.Mention} has tried to remove {amount} points from <@{userId}> they only had {cur} points. None were taken...", false);
}
@ -97,16 +97,11 @@ namespace ChaosBot.Discord.Modules
public async Task DeletePoints(string userMention)
{
ulong userId = Convert.ToUInt64(userMention.Substring(3, userMention.Length - 4));
Dictionary<string, object> filterColumns = new Dictionary<string, object>
{
{ "userId", userId },
{ "guildId", Context.Guild.Id }
};
int matches = PointsRepository.Count(userId.ToString(), Context.Guild.Id.ToString());
int matches = PointsRepository.Count(Convert.ToInt64(userId), Convert.ToInt64(Context.Guild.Id));
if (matches > 0)
{
Controller.DeleteQuery("PointsTable", filterColumns);
Points.Query().Where("userId", userId).Where("guildId", Context.Guild.Id).Delete();
string message = $"{Context.User.Mention} has removed <@{userId}> from the database.";
await ReplyAsync(message, false);

View File

@ -140,32 +140,33 @@ namespace ChaosBot.Discord.Modules
List<Raffle> raffles = new List<Raffle>();
for (int i = 0; i < amount; i++)
raffles.Add(new Raffle(userId.ToString(), Context.Guild.Id.ToString()));
raffles.Add(new Raffle(Convert.ToInt64(userId), Convert.ToInt64(Context.Guild.Id)));
RaffleRepository.MassInsert(raffles);
}
else
{
RaffleRepository.Insert(new Raffle(userId.ToString(), Context.Guild.Id.ToString()));
RaffleRepository.Insert(new Raffle(Convert.ToInt64(userId), Convert.ToInt64(Context.Guild.Id)));
}
sb.AppendLine($"{Context.User.Mention} has added {amount} rafflepoints to <@{userId}>.");
sb.AppendLine();
sb.AppendLine($"<@{userId}> now has {RaffleRepository.Count(userId.ToString(), Context.Guild.Id.ToString())} rafflepoints!");
sb.AppendLine($"<@{userId}> now has {RaffleRepository.Count(Convert.ToInt64(userId), Convert.ToInt64(Context.Guild.Id))} rafflepoints!");
}
private void PickRaffle(StringBuilder sb)
{
Raffle winner = RaffleRepository.PickRandom(Context.Guild.Id.ToString());
RaffleRepository.Delete(winner.id);
Raffle winner = RaffleRepository.PickRandom(Convert.ToInt64(Context.Guild.Id));
if (winner.id != null)
RaffleRepository.Delete((int)winner.id);
sb.Append($"<@{winner.userId}> has won the raffle!");
}
private void ClearRaffle(StringBuilder sb, bool noOutput = false)
{
int removed = RaffleRepository.Count(Context.Guild.Id.ToString());
int removed = RaffleRepository.Count(Convert.ToInt64(Context.Guild.Id));
RaffleRepository.ClearRaffle(Context.Guild.Id.ToString());
RaffleRepository.ClearRaffle(Convert.ToInt64(Context.Guild.Id));
sb.AppendLine($"{Context.User.Mention} has cleared all {removed} rafflepoints");
}
@ -174,8 +175,8 @@ namespace ChaosBot.Discord.Modules
{
ulong userId = Convert.ToUInt64(user.Substring(3, user.Length-4));
sb.AppendLine($"<@{userId}>, you have {RaffleRepository.Count(userId.ToString(), Context.Guild.Id.ToString())} rafflepoints.");
sb.AppendLine($"There is a total of {RaffleRepository.Count(Context.Guild.Id.ToString())} rafflepoints.");
sb.AppendLine($"<@{userId}>, you have {RaffleRepository.Count(Convert.ToInt64(userId), Convert.ToInt64(Context.Guild.Id))} rafflepoints.");
sb.AppendLine($"There is a total of {RaffleRepository.Count(Convert.ToInt64(Context.Guild.Id))} rafflepoints.");
}
}
}

View File

@ -27,6 +27,8 @@ namespace ChaosBot.Discord.Services
if (lodestoneChannelSloganDescriptionId == null) continue;
async void UpdateChannelSloganDescription()
{
try
{
SocketGuild guild = _client.GetGuild(Convert.ToUInt64(serverConfig.Key));
if (guild == null)
@ -35,10 +37,12 @@ namespace ChaosBot.Discord.Services
return;
}
SocketChannel socketChannel = guild.GetChannel(Convert.ToUInt64(lodestoneChannelSloganDescriptionId));
SocketChannel socketChannel =
guild.GetChannel(Convert.ToUInt64(lodestoneChannelSloganDescriptionId));
if (socketChannel == null)
{
_logger.Warn($"Channel {Convert.ToUInt64(lodestoneChannelSloganDescriptionId)} not found in server {guild.Name}");
_logger.Warn(
$"Channel {Convert.ToUInt64(lodestoneChannelSloganDescriptionId)} not found in server {guild.Name}");
return;
}
@ -47,13 +51,20 @@ namespace ChaosBot.Discord.Services
{
_logger.Warn($"Could not cast channel {socketChannel.Id} to ITextChannel");
return;
};
}
string description = LodestoneManager.GetFreeCompanyById(serverConfig.GetValue<string>("Lodestone:FreeCompanyId")).FreeCompany.Slogan;;
await channel.ModifyAsync(x =>
if (!guild.GetUser(_client.CurrentUser.Id).GetPermissions(channel).ManageChannel) return;
string description = LodestoneManager
.GetFreeCompanyById(serverConfig.GetValue<string>("Lodestone:FreeCompanyId")).FreeCompany
.Slogan;
await channel.ModifyAsync(x => { x.Topic = description; });
}
catch (Exception ex)
{
x.Topic = description;
});
_logger.Error($"TimerHandler.UpdateChannelSloganDescription: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
}
Timer.RunTimer(UpdateChannelSloganDescription, new TimeSpan(TimeSpan.TicksPerMinute * refreshMinutes));

View File

@ -1,12 +1,13 @@
using NLog;
using System;
using System.Runtime.CompilerServices;
using ChaosBot.Discord;
using System.Threading.Tasks;
using ChaosBot.Attribute;
using ChaosBot.Database.Repository;
using Microsoft.Extensions.Configuration;
[assembly: InternalsVisibleTo("ChaosBot.UnitTests")]
namespace ChaosBot
{
internal class Program
@ -27,28 +28,26 @@ namespace ChaosBot
/*
* Load configuration from AppSettings.Json and save as Cfg
*/
ConfigurationRepository.AppSettingsHandler = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile(appsettingsPath, optional: false, reloadOnChange: true).Build();
LoadConfiguration(appsettingsPath);
/*
* Initialize the _logger for logging purposes
*/
_logger = Logging.GenLog();
LoadLogger();
/*
* Attempt to load our custom assemblies
*/
AssemblyController.Register();
RegisterAssemblyController();
/*
* Initialize the Discord Client and Login
*/
_logger.Info($"Starting Up {ConfigurationRepository.GetValue<string>("Bot:Name")} v{ConfigurationRepository.GetValue<string>("Bot:Version")}");
var discordBot = DiscordConnect.StartUp();
WebServer.WebServer.Start(new string[]{});
var discordBot = LoadDiscord();
LoadWebServer();
await discordBot;
}
catch (Exception ex)
@ -56,5 +55,32 @@ namespace ChaosBot
_logger.Error(ex, $"Program.MainFunction: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
}
public static void LoadConfiguration(string appsettingsPath)
{
ConfigurationRepository.AppSettingsHandler = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile(appsettingsPath, optional: false, reloadOnChange: true).Build();
}
public static void LoadLogger()
{
_logger = Logging.GenLog();
}
public static void RegisterAssemblyController()
{
AssemblyController.RegisterAll();
}
public static void LoadWebServer()
{
WebServer.WebServer.Start(new string[]{});
}
public static Task LoadDiscord()
{
return DiscordConnect.StartUp();
}
}
}