First Version Ever that runs a little bit

This commit is contained in:
BlubbFish 2016-01-26 14:20:42 +00:00
parent 6513a92c77
commit 78e559985f
19 changed files with 11352 additions and 1309 deletions

View File

@ -50,7 +50,7 @@ void doJob(String task, String value) {
co = 0x00539F; //Rwth Color co = 0x00539F; //Rwth Color
} }
job = value.toInt(); job = value.toInt();
Rb.fillRectangle(1, 2, 6, 7, 0x000000); Rb.fillRectangle(1, 2, 7, 6, 0x000000);
Rb.drawChar(b, 1, 1, co); Rb.drawChar(b, 1, 1, co);
} else if(task == "online") { } else if(task == "online") {
Rb.setPixelXY(0,7,value.toInt()==0?0xFF0000:0x00FF00); Rb.setPixelXY(0,7,value.toInt()==0?0xFF0000:0x00FF00);

View File

@ -42,7 +42,7 @@ void loadFromDisplay() {
print_disp("getStoreData=1"); print_disp("getStoreData=1");
parse(disp.readStringUntil('\n')); parse(disp.readStringUntil('\n'));
} }
if(keepAlive()) { if(storeCount > 0 && keepAlive()) {
doJob("getStore","1"); doJob("getStore","1");
} }
} }

View File

@ -10,11 +10,10 @@ using System.Data.SQLite;
using MySql; using MySql;
using MySql.Data.Common; using MySql.Data.Common;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using TimeKeeper.Exceptions;
namespace BF2Statistics.Database namespace TimeKeeper.Database {
{ public class DatabaseDriver : IDisposable {
public class DatabaseDriver : IDisposable
{
/// <summary> /// <summary>
/// Current DB Engine /// Current DB Engine
/// </summary> /// </summary>
@ -28,16 +27,14 @@ namespace BF2Statistics.Database
/// <summary> /// <summary>
/// Returns whether the Database connection is open /// Returns whether the Database connection is open
/// </summary> /// </summary>
public bool IsConnected public bool IsConnected {
{
get { return (Connection.State == ConnectionState.Open); } get { return (Connection.State == ConnectionState.Open); }
} }
/// <summary> /// <summary>
/// Returns the current conenction state of the database /// Returns the current conenction state of the database
/// </summary> /// </summary>
public ConnectionState State public ConnectionState State {
{
get { return Connection.State; } get { return Connection.State; }
} }
@ -65,22 +62,18 @@ namespace BF2Statistics.Database
/// <param name="DatabaseName">The name of the database</param> /// <param name="DatabaseName">The name of the database</param>
/// <param name="User">A username, with database privliages</param> /// <param name="User">A username, with database privliages</param>
/// <param name="Pass">The password to the User</param> /// <param name="Pass">The password to the User</param>
public DatabaseDriver(string Engine, string Host, int Port, string DatabaseName, string User, string Pass) public DatabaseDriver(string Engine, string Host, int Port, string DatabaseName, string User, string Pass, DatabaseEngine[] allowedEngines) {
{
// Set class variables, and create a new connection builder // Set class variables, and create a new connection builder
this.DatabaseEngine = GetDatabaseEngine(Engine); this.DatabaseEngine = GetDatabaseEngine(Engine);
DbConnectionStringBuilder Builder; DbConnectionStringBuilder Builder;
// Establish the connection // Establish the connection
if (this.DatabaseEngine == DatabaseEngine.Sqlite) if(this.DatabaseEngine == DatabaseEngine.Sqlite && allowedEngines.Contains(DatabaseEngine.Sqlite)) {
{
// Create the connection // Create the connection
Builder = new SQLiteConnectionStringBuilder(); Builder = new SQLiteConnectionStringBuilder();
Builder.Add("Data Source", Path.Combine(Program.RootPath, DatabaseName + ".sqlite3")); Builder.Add("Data Source", Path.Combine(StaticConfig.RootPath, DatabaseName + ".sqlite3"));
Connection = new SQLiteConnection(Builder.ConnectionString); Connection = new SQLiteConnection(Builder.ConnectionString);
} } else if(this.DatabaseEngine == DatabaseEngine.Mysql && allowedEngines.Contains(DatabaseEngine.Mysql)) {
else if (this.DatabaseEngine == DatabaseEngine.Mysql)
{
// Create the connection // Create the connection
Builder = new MySqlConnectionStringBuilder(); Builder = new MySqlConnectionStringBuilder();
Builder.Add("Server", Host); Builder.Add("Server", Host);
@ -90,9 +83,7 @@ namespace BF2Statistics.Database
Builder.Add("Database", DatabaseName); Builder.Add("Database", DatabaseName);
Builder.Add("Convert Zero Datetime", "true"); Builder.Add("Convert Zero Datetime", "true");
Connection = new MySqlConnection(Builder.ConnectionString); Connection = new MySqlConnection(Builder.ConnectionString);
} } else {
else
{
throw new Exception("Invalid Database type."); throw new Exception("Invalid Database type.");
} }
} }
@ -100,24 +91,19 @@ namespace BF2Statistics.Database
/// <summary> /// <summary>
/// Destructor /// Destructor
/// </summary> /// </summary>
~DatabaseDriver() ~DatabaseDriver() {
{
Dispose(); Dispose();
} }
/// <summary> /// <summary>
/// Disposes the DB connection /// Disposes the DB connection
/// </summary> /// </summary>
public void Dispose() public void Dispose() {
{ if(Connection != null && !IsDisposed) {
if(Connection != null && !IsDisposed) try {
{
try
{
Connection.Close(); Connection.Close();
Connection.Dispose(); Connection.Dispose();
} } catch(ObjectDisposedException) { }
catch (ObjectDisposedException) { }
IsDisposed = true; IsDisposed = true;
} }
@ -126,16 +112,11 @@ namespace BF2Statistics.Database
/// <summary> /// <summary>
/// Opens the database connection /// Opens the database connection
/// </summary> /// </summary>
public void Connect() public void Connect() {
{ if(Connection.State != ConnectionState.Open) {
if (Connection.State != ConnectionState.Open) try {
{
try
{
Connection.Open(); Connection.Open();
} } catch(Exception e) {
catch (Exception e)
{
throw new DbConnectException("Unable to etablish database connection", e); throw new DbConnectException("Unable to etablish database connection", e);
} }
} }
@ -144,22 +125,19 @@ namespace BF2Statistics.Database
/// <summary> /// <summary>
/// Closes the connection to the database /// Closes the connection to the database
/// </summary> /// </summary>
public void Close() public void Close() {
{
try { try {
if (Connection.State != ConnectionState.Closed) if(Connection.State != ConnectionState.Closed)
Connection.Close(); Connection.Close();
} } catch(ObjectDisposedException) { }
catch (ObjectDisposedException) { }
} }
/// <summary> /// <summary>
/// Creates a new command to be executed on the database /// Creates a new command to be executed on the database
/// </summary> /// </summary>
/// <param name="QueryString"></param> /// <param name="QueryString"></param>
public DbCommand CreateCommand(string QueryString) public DbCommand CreateCommand(string QueryString) {
{ if(DatabaseEngine == Database.DatabaseEngine.Sqlite)
if (DatabaseEngine == Database.DatabaseEngine.Sqlite)
return new SQLiteCommand(QueryString, Connection as SQLiteConnection); return new SQLiteCommand(QueryString, Connection as SQLiteConnection);
else else
return new MySqlCommand(QueryString, Connection as MySqlConnection); return new MySqlCommand(QueryString, Connection as MySqlConnection);
@ -169,9 +147,8 @@ namespace BF2Statistics.Database
/// Creates a DbParameter using the current Database engine's Parameter object /// Creates a DbParameter using the current Database engine's Parameter object
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public DbParameter CreateParam() public DbParameter CreateParam() {
{ if(DatabaseEngine == Database.DatabaseEngine.Sqlite)
if (DatabaseEngine == Database.DatabaseEngine.Sqlite)
return (new SQLiteParameter() as DbParameter); return (new SQLiteParameter() as DbParameter);
else else
return (new MySqlParameter() as DbParameter); return (new MySqlParameter() as DbParameter);
@ -182,8 +159,7 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Sql">The SQL Statement to run on the database</param> /// <param name="Sql">The SQL Statement to run on the database</param>
/// <returns></returns> /// <returns></returns>
public List<Dictionary<string, object>> Query(string Sql) public List<Dictionary<string, object>> Query(string Sql) {
{
return this.Query(Sql, new List<DbParameter>()); return this.Query(Sql, new List<DbParameter>());
} }
@ -195,11 +171,9 @@ namespace BF2Statistics.Database
/// The first parameter replaces @P0, second @P1 etc etc. /// The first parameter replaces @P0, second @P1 etc etc.
/// </param> /// </param>
/// <returns></returns> /// <returns></returns>
public List<Dictionary<string, object>> Query(string Sql, params object[] Items) public List<Dictionary<string, object>> Query(string Sql, params object[] Items) {
{
List<DbParameter> Params = new List<DbParameter>(Items.Length); List<DbParameter> Params = new List<DbParameter>(Items.Length);
for (int i = 0; i < Items.Length; i++) for(int i = 0; i < Items.Length; i++) {
{
DbParameter Param = this.CreateParam(); DbParameter Param = this.CreateParam();
Param.ParameterName = "@P" + i; Param.ParameterName = "@P" + i;
Param.Value = Items[i]; Param.Value = Items[i];
@ -215,8 +189,7 @@ namespace BF2Statistics.Database
/// <param name="Sql">The SQL Statement to run on the database</param> /// <param name="Sql">The SQL Statement to run on the database</param>
/// <param name="Params">A list of sql params to add to the command</param> /// <param name="Params">A list of sql params to add to the command</param>
/// <returns></returns> /// <returns></returns>
public List<Dictionary<string, object>> Query(string Sql, List<DbParameter> Params) public List<Dictionary<string, object>> Query(string Sql, List<DbParameter> Params) {
{
// Create our Rows result // Create our Rows result
List<Dictionary<string, object>> Rows = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> Rows = new List<Dictionary<string, object>>();
@ -224,23 +197,19 @@ namespace BF2Statistics.Database
NumQueries++; NumQueries++;
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql)) {
{
// Add params // Add params
foreach (DbParameter Param in Params) foreach(DbParameter Param in Params)
Command.Parameters.Add(Param); Command.Parameters.Add(Param);
// Execute the query // Execute the query
using (DbDataReader Reader = Command.ExecuteReader()) using(DbDataReader Reader = Command.ExecuteReader()) {
{
// If we have rows, add them to the list // If we have rows, add them to the list
if (Reader.HasRows) if(Reader.HasRows) {
{
// Add each row to the rows list // Add each row to the rows list
while (Reader.Read()) while(Reader.Read()) {
{
Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount); Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount);
for (int i = 0; i < Reader.FieldCount; ++i) for(int i = 0; i < Reader.FieldCount; ++i)
Row.Add(Reader.GetName(i), Reader.GetValue(i)); Row.Add(Reader.GetName(i), Reader.GetValue(i));
Rows.Add(Row); Rows.Add(Row);
@ -261,23 +230,19 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Sql">The SQL Statement to run on the database</param> /// <param name="Sql">The SQL Statement to run on the database</param>
/// <returns></returns> /// <returns></returns>
public IEnumerable<Dictionary<string, object>> QueryReader(string Sql) public IEnumerable<Dictionary<string, object>> QueryReader(string Sql) {
{
// Increase Query Count // Increase Query Count
NumQueries++; NumQueries++;
// Create the SQL Command, and execute the reader // Create the SQL Command, and execute the reader
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql))
using (DbDataReader Reader = Command.ExecuteReader()) using(DbDataReader Reader = Command.ExecuteReader()) {
{
// If we have rows, add them to the list // If we have rows, add them to the list
if (Reader.HasRows) if(Reader.HasRows) {
{
// Add each row to the rows list // Add each row to the rows list
while (Reader.Read()) while(Reader.Read()) {
{
Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount); Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount);
for (int i = 0; i < Reader.FieldCount; ++i) for(int i = 0; i < Reader.FieldCount; ++i)
Row.Add(Reader.GetName(i), Reader.GetValue(i)); Row.Add(Reader.GetName(i), Reader.GetValue(i));
yield return Row; yield return Row;
@ -294,23 +259,19 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Command">The database command to execute the reader on</param> /// <param name="Command">The database command to execute the reader on</param>
/// <returns></returns> /// <returns></returns>
public IEnumerable<Dictionary<string, object>> QueryReader(DbCommand Command) public IEnumerable<Dictionary<string, object>> QueryReader(DbCommand Command) {
{
// Increase Query Count // Increase Query Count
NumQueries++; NumQueries++;
// Execute the query // Execute the query
using (Command) using(Command)
using (DbDataReader Reader = Command.ExecuteReader()) using(DbDataReader Reader = Command.ExecuteReader()) {
{
// If we have rows, add them to the list // If we have rows, add them to the list
if (Reader.HasRows) if(Reader.HasRows) {
{
// Add each row to the rows list // Add each row to the rows list
while (Reader.Read()) while(Reader.Read()) {
{
Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount); Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount);
for (int i = 0; i < Reader.FieldCount; ++i) for(int i = 0; i < Reader.FieldCount; ++i)
Row.Add(Reader.GetName(i), Reader.GetValue(i)); Row.Add(Reader.GetName(i), Reader.GetValue(i));
yield return Row; yield return Row;
@ -328,25 +289,21 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Command">The database command to execute the reader on</param> /// <param name="Command">The database command to execute the reader on</param>
/// <returns></returns> /// <returns></returns>
public List<Dictionary<string, object>> ExecuteReader(DbCommand Command) public List<Dictionary<string, object>> ExecuteReader(DbCommand Command) {
{
// Execute the query // Execute the query
List<Dictionary<string, object>> Rows = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> Rows = new List<Dictionary<string, object>>();
// Increase Query Count // Increase Query Count
NumQueries++; NumQueries++;
using (Command) using(Command)
using (DbDataReader Reader = Command.ExecuteReader()) using(DbDataReader Reader = Command.ExecuteReader()) {
{
// If we have rows, add them to the list // If we have rows, add them to the list
if (Reader.HasRows) if(Reader.HasRows) {
{
// Add each row to the rows list // Add each row to the rows list
while (Reader.Read()) while(Reader.Read()) {
{
Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount); Dictionary<string, object> Row = new Dictionary<string, object>(Reader.FieldCount);
for (int i = 0; i < Reader.FieldCount; ++i) for(int i = 0; i < Reader.FieldCount; ++i)
Row.Add(Reader.GetName(i), Reader.GetValue(i)); Row.Add(Reader.GetName(i), Reader.GetValue(i));
Rows.Add(Row); Rows.Add(Row);
@ -366,10 +323,9 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Sql">The SQL statement to be executes</param> /// <param name="Sql">The SQL statement to be executes</param>
/// <returns>Returns the number of rows affected by the statement</returns> /// <returns>Returns the number of rows affected by the statement</returns>
public int Execute(string Sql) public int Execute(string Sql) {
{
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql))
return Command.ExecuteNonQuery(); return Command.ExecuteNonQuery();
} }
@ -379,16 +335,14 @@ namespace BF2Statistics.Database
/// <param name="Sql">The SQL statement to be executed</param> /// <param name="Sql">The SQL statement to be executed</param>
/// <param name="Params">A list of Sqlparameters</param> /// <param name="Params">A list of Sqlparameters</param>
/// <returns>Returns the number of rows affected by the statement</returns> /// <returns>Returns the number of rows affected by the statement</returns>
public int Execute(string Sql, List<DbParameter> Params) public int Execute(string Sql, List<DbParameter> Params) {
{
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql)) {
{
// Increase Query Count // Increase Query Count
NumQueries++; NumQueries++;
// Add params // Add params
foreach (DbParameter Param in Params) foreach(DbParameter Param in Params)
Command.Parameters.Add(Param); Command.Parameters.Add(Param);
// Execute command, and dispose of the command // Execute command, and dispose of the command
@ -404,14 +358,11 @@ namespace BF2Statistics.Database
/// The first parameter replaces @P0, second @P1 etc etc. /// The first parameter replaces @P0, second @P1 etc etc.
/// </param> /// </param>
/// <returns>Returns the number of rows affected by the statement</returns> /// <returns>Returns the number of rows affected by the statement</returns>
public int Execute(string Sql, params object[] Items) public int Execute(string Sql, params object[] Items) {
{
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql)) {
{
// Add params // Add params
for (int i = 0; i < Items.Length; i++) for(int i = 0; i < Items.Length; i++) {
{
DbParameter Param = this.CreateParam(); DbParameter Param = this.CreateParam();
Param.ParameterName = "@P" + i; Param.ParameterName = "@P" + i;
Param.Value = Items[i]; Param.Value = Items[i];
@ -432,13 +383,12 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Sql">The SQL statement to be executed</param> /// <param name="Sql">The SQL statement to be executed</param>
/// <returns></returns> /// <returns></returns>
public object ExecuteScalar(string Sql) public object ExecuteScalar(string Sql) {
{
// Increase Query Count // Increase Query Count
NumQueries++; NumQueries++;
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql))
return Command.ExecuteScalar(); return Command.ExecuteScalar();
} }
@ -449,16 +399,14 @@ namespace BF2Statistics.Database
/// <param name="Sql">The SQL statement to be executed</param> /// <param name="Sql">The SQL statement to be executed</param>
/// <param name="Params">A list of Sqlparameters</param> /// <param name="Params">A list of Sqlparameters</param>
/// <returns></returns> /// <returns></returns>
public object ExecuteScalar(string Sql, List<DbParameter> Params) public object ExecuteScalar(string Sql, List<DbParameter> Params) {
{
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql)) {
{
// Increase Query Count // Increase Query Count
NumQueries++; NumQueries++;
// Add params // Add params
foreach (DbParameter Param in Params) foreach(DbParameter Param in Params)
Command.Parameters.Add(Param); Command.Parameters.Add(Param);
// Execute command, and dispose of the command // Execute command, and dispose of the command
@ -473,14 +421,11 @@ namespace BF2Statistics.Database
/// <param name="Sql">The SQL statement to be executed</param> /// <param name="Sql">The SQL statement to be executed</param>
/// <param name="Items"></param> /// <param name="Items"></param>
/// <returns></returns> /// <returns></returns>
public object ExecuteScalar(string Sql, params object[] Items) public object ExecuteScalar(string Sql, params object[] Items) {
{
// Create the SQL Command // Create the SQL Command
using (DbCommand Command = this.CreateCommand(Sql)) using(DbCommand Command = this.CreateCommand(Sql)) {
{
// Add params // Add params
for (int i = 0; i < Items.Length; i++) for(int i = 0; i < Items.Length; i++) {
{
DbParameter Param = this.CreateParam(); DbParameter Param = this.CreateParam();
Param.ParameterName = "@P" + i; Param.ParameterName = "@P" + i;
Param.Value = Items[i]; Param.Value = Items[i];
@ -499,8 +444,7 @@ namespace BF2Statistics.Database
/// Begins a new database transaction /// Begins a new database transaction
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public DbTransaction BeginTransaction() public DbTransaction BeginTransaction() {
{
return Connection.BeginTransaction(); return Connection.BeginTransaction();
} }
@ -509,8 +453,7 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Level"></param> /// <param name="Level"></param>
/// <returns></returns> /// <returns></returns>
public DbTransaction BeginTransaction(IsolationLevel Level) public DbTransaction BeginTransaction(IsolationLevel Level) {
{
return Connection.BeginTransaction(Level); return Connection.BeginTransaction(Level);
} }
@ -519,8 +462,7 @@ namespace BF2Statistics.Database
/// </summary> /// </summary>
/// <param name="Name"></param> /// <param name="Name"></param>
/// <returns></returns> /// <returns></returns>
public static DatabaseEngine GetDatabaseEngine(string Name) public static DatabaseEngine GetDatabaseEngine(string Name) {
{
return ((DatabaseEngine)Enum.Parse(typeof(DatabaseEngine), Name, true)); return ((DatabaseEngine)Enum.Parse(typeof(DatabaseEngine), Name, true));
} }
} }

View File

@ -1,9 +1,4 @@
using System; namespace TimeKeeper.Database
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BF2Statistics.Database
{ {
public enum DatabaseEngine public enum DatabaseEngine
{ {

View File

@ -1,298 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BF2Statistics.Database
{
/// <summary>
/// A class to provide common tasks against the Gamespy Login Database
/// </summary>
public class GamespyDatabase : DatabaseDriver, IDisposable
{
/// <summary>
/// Constructor
/// </summary>
public GamespyDatabase() :
base(
MainForm.Config.GamespyDBEngine,
MainForm.Config.GamespyDBHost,
MainForm.Config.GamespyDBPort,
MainForm.Config.GamespyDBName,
MainForm.Config.GamespyDBUser,
MainForm.Config.GamespyDBPass
)
{
// Try and Reconnect
try
{
Connect();
// Try to get the database version
try
{
if (base.Query("SELECT dbver FROM _version LIMIT 1").Count == 0)
throw new Exception();
}
catch
{
// If an exception is thrown, table doesnt exist... fresh install
if (DatabaseEngine == DatabaseEngine.Sqlite)
base.Execute(Utils.GetResourceAsString("BF2Statistics.SQL.SQLite.Gamespy.sql"));
else
base.Execute(Utils.GetResourceAsString("BF2Statistics.SQL.MySQL.Gamespy.sql"));
}
}
catch (Exception)
{
if (Connection != null)
Connection.Dispose();
throw;
}
}
/// <summary>
/// Destructor
/// </summary>
~GamespyDatabase()
{
if (!IsDisposed)
base.Dispose();
}
/// <summary>
/// Fetches an account from the gamespy database
/// </summary>
/// <param name="Nick">The user's Nick</param>
/// <returns></returns>
public Dictionary<string, object> GetUser(string Nick)
{
// Fetch the user
var Rows = base.Query("SELECT * FROM accounts WHERE name=@P0", Nick);
return (Rows.Count == 0) ? null : Rows[0];
}
/// <summary>
/// Fetches an account from the gamespy database
/// </summary>
/// <param name="Pid">The account player ID</param>
/// <returns></returns>
public Dictionary<string, object> GetUser(int Pid)
{
// Fetch the user
var Rows = base.Query("SELECT * FROM accounts WHERE id=@P0", Pid);
return (Rows.Count == 0) ? null : Rows[0];
}
/// <summary>
/// Fetches an account from the gamespy database
/// </summary>
/// <param name="Email">Account email</param>
/// <param name="Password">Account Password</param>
/// <returns></returns>
public Dictionary<string, object> GetUser(string Email, string Password)
{
var Rows = base.Query("SELECT * FROM accounts WHERE email=@P0 AND password=@P1", Email, Password);
return (Rows.Count == 0) ? null : Rows[0];
}
/// <summary>
/// Returns a list of player names that are similar to the passed parameter
/// </summary>
/// <param name="Nick"></param>
/// <returns></returns>
public List<string> GetUsersLike(string Nick)
{
// Generate our return list
List<string> List = new List<string>();
var Rows = base.Query("SELECT name FROM accounts WHERE name LIKE @P0", "%" + Nick + "%");
foreach (Dictionary<string, object> Account in Rows)
List.Add(Account["name"].ToString());
return List;
}
/// <summary>
/// Returns wether an account exists from the provided Nick
/// </summary>
/// <param name="Nick"></param>
/// <returns></returns>
public bool UserExists(string Nick)
{
// Fetch the user
return (base.Query("SELECT id FROM accounts WHERE name=@P0", Nick).Count != 0);
}
/// <summary>
/// Returns wether an account exists from the provided Account Id
/// </summary>
/// <param name="PID"></param>
/// <returns></returns>
public bool UserExists(int PID)
{
// Fetch the user
return (base.Query("SELECT name FROM accounts WHERE id=@P0", PID).Count != 0);
}
/// <summary>
/// Creates a new Gamespy Account
/// </summary>
/// <remarks>Used by the login server when a create account request is made</remarks>
/// <param name="Nick">The Account Name</param>
/// <param name="Pass">The Account Password</param>
/// <param name="Email">The Account Email Address</param>
/// <param name="Country">The Country Code for this Account</param>
/// <returns>A bool indicating whether the account was created sucessfully</returns>
public bool CreateUser(string Nick, string Pass, string Email, string Country)
{
int Pid = 0;
// Attempt to connect to stats database, and get a PID from there
/*try
{
// try see if the player ID exists in the stats database
using (StatsDatabase Db = new StatsDatabase())
{
// NOTE: online account names in the stats DB start with a single space!
var Row = Db.Query("SELECT id FROM player WHERE upper(name) = upper(@P0)", " " + Nick);
Pid = (Row.Count == 0) ? GenerateAccountId() : Int32.Parse(Row[0]["id"].ToString());
}
}
catch
{*/
Pid = GenerateAccountId();
//}
// Create the user in the database
int Rows = base.Execute("INSERT INTO accounts(id, name, password, email, country) VALUES(@P0, @P1, @P2, @P3, @P4)",
Pid, Nick, Pass, Email, Country
);
return (Rows != 0);
}
/// <summary>
/// Generates a new Account Id
/// </summary>
/// <returns></returns>
private int GenerateAccountId()
{
var Row = base.Query("SELECT COALESCE(MAX(id), 500000000) AS max FROM accounts");
int max = Int32.Parse(Row[0]["max"].ToString()) + 1;
return (max < 500000000) ? 500000000 : max;
}
/// <summary>
/// Creates a new Gamespy Account
/// </summary>
/// <remarks>Only used in the Gamespy Account Creation Form</remarks>
/// <param name="Pid">The Profile Id to assign this account</param>
/// <param name="Nick">The Account Name</param>
/// <param name="Pass">The Account Password</param>
/// <param name="Email">The Account Email Address</param>
/// <param name="Country">The Country Code for this Account</param>
/// <returns>A bool indicating whether the account was created sucessfully</returns>
public bool CreateUser(int Pid, string Nick, string Pass, string Email, string Country)
{
// Make sure the user doesnt exist!
if (UserExists(Pid))
throw new Exception("Account ID is already taken!");
else if(UserExists(Nick))
throw new Exception("Account username is already taken!");
// Create the user in the database
int Rows = base.Execute("INSERT INTO accounts(id, name, password, email, country) VALUES(@P0, @P1, @P2, @P3, @P4)",
Pid, Nick, Pass, Email, Country
);
return (Rows != 0);
}
/// <summary>
/// Updates an Accounts Country Code
/// </summary>
/// <param name="Nick"></param>
/// <param name="Country"></param>
public void UpdateUser(string Nick, string Country)
{
base.Execute("UPDATE accounts SET country=@P0 WHERE name=@P1", Nick, Country);
}
/// <summary>
/// Updates an Account's information by ID
/// </summary>
/// <param name="Id">The Current Account ID</param>
/// <param name="NewPid">New Account ID</param>
/// <param name="NewNick">New Account Name</param>
/// <param name="NewPassword">New Account Password</param>
/// <param name="NewEmail">New Account Email Address</param>
public void UpdateUser(int Id, int NewPid, string NewNick, string NewPassword, string NewEmail)
{
base.Execute("UPDATE accounts SET id=@P0, name=@P1, password=@P2, email=@P3 WHERE id=@P4",
NewPid, NewNick, NewPassword, NewEmail, Id);
}
/// <summary>
/// Deletes a Gamespy Account
/// </summary>
/// <param name="Nick"></param>
/// <returns></returns>
public int DeleteUser(string Nick)
{
return base.Execute("DELETE FROM accounts WHERE name=@P0", Nick);
}
/// <summary>
/// Deletes a Gamespy Account
/// </summary>
/// <param name="Nick"></param>
/// <returns></returns>
public int DeleteUser(int Pid)
{
return base.Execute("DELETE FROM accounts WHERE id=@P0", Pid);
}
/// <summary>
/// Fetches a Gamespy Account id from an account name
/// </summary>
/// <param name="Nick"></param>
/// <returns></returns>
public int GetPID(string Nick)
{
var Rows = base.Query("SELECT id FROM accounts WHERE name=@P0", Nick);
return (Rows.Count == 0) ? 0 : Int32.Parse(Rows[0]["id"].ToString());
}
/// <summary>
/// Sets the Account (Player) Id for an account by Name
/// </summary>
/// <param name="Nick">The account Nick we are setting the new Pid for</param>
/// <param name="Pid">The new Pid</param>
/// <returns></returns>
public int SetPID(string Nick, int Pid)
{
// If no user exists, return code -1
if (!UserExists(Nick))
return -1;
// If the Pid already exists, return -2
if (UserExists(Pid))
return -2;
// If PID is false, the PID is not taken
int Success = base.Execute("UPDATE accounts SET id=@P0 WHERE name=@P1", Pid, Nick);
return (Success > 0) ? 1 : 0;
}
/// <summary>
/// Returns the number of accounts in the database
/// </summary>
/// <returns></returns>
public int GetNumAccounts()
{
var Row = base.Query("SELECT COUNT(id) AS count FROM accounts");
return Int32.Parse(Row[0]["count"].ToString());
}
}
}

View File

@ -0,0 +1,98 @@
-- phpMyAdmin SQL Dump
-- version 3.4.11.1deb2+deb7u2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Erstellungszeit: 26. Jan 2016 um 10:01
-- Server Version: 5.6.25
-- PHP-Version: 5.4.45-1~dotdeb+7.1
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Datenbank: `worktime`
--
-- --------------------------------------------------------
--
-- Tabellenstruktur für Tabelle `location`
--
CREATE TABLE IF NOT EXISTS `location` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`tag` varchar(10) NOT NULL,
`weeklength` float NOT NULL,
`days` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Tabellenstruktur für Tabelle `month`
--
CREATE TABLE IF NOT EXISTS `month` (
`year` int(11) NOT NULL,
`month` int(11) NOT NULL,
`duration` double NOT NULL,
`location` int(11) DEFAULT NULL,
UNIQUE KEY `year` (`year`,`month`,`location`),
KEY `location` (`location`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Tabellenstruktur für Tabelle `work`
--
CREATE TABLE IF NOT EXISTS `work` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`start` time NOT NULL,
`stop` time NOT NULL,
`pause` int(11) DEFAULT NULL,
`type` enum('ok','free','we','ill','vac','feiertag') NOT NULL,
`notice` varchar(200) DEFAULT NULL,
`location` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `location` (`location`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Tabellenstruktur für Tabelle `_version`
--
CREATE TABLE IF NOT EXISTS `_version` (
`dbver` int(4) NOT NULL,
`dbdate` datetime NOT NULL,
PRIMARY KEY (`dbver`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints der exportierten Tabellen
--
--
-- Constraints der Tabelle `month`
--
ALTER TABLE `month`
ADD CONSTRAINT `month_ibfk_1` FOREIGN KEY (`location`) REFERENCES `location` (`id`) ON DELETE SET NULL ON UPDATE SET NULL;
--
-- Constraints der Tabelle `work`
--
ALTER TABLE `work`
ADD CONSTRAINT `work_ibfk_1` FOREIGN KEY (`location`) REFERENCES `location` (`id`) ON DELETE SET NULL ON UPDATE SET NULL;
--
-- Daten
--
INSERT INTO `_version` (`dbver` ,`dbdate`) VALUES ('1', CURRENT_TIMESTAMP);

View File

@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeKeeper.Models.Types;
namespace TimeKeeper.Database {
public class TDatabase : DatabaseDriver, IDisposable {
private static TDatabase instance;
private TDatabase() : base(StaticConfig.DbConfig.Engine, StaticConfig.DbConfig.Host, StaticConfig.DbConfig.Port, StaticConfig.DbConfig.Db, StaticConfig.DbConfig.User, StaticConfig.DbConfig.Pass, new DatabaseEngine[] { DatabaseEngine.Mysql}) {
// Try and Reconnect
try {
Connect();
// Try to get the database version
try {
if(base.Query("SELECT dbver FROM _version LIMIT 1").Count == 0)
throw new Exception();
} catch {
base.Execute(Utils.GetResourceAsString("TimeKeeper.Database.SQL.MySQL.Install.sql"));
}
} catch(Exception) {
if(Connection != null)
Connection.Dispose();
throw;
}
}
public static TDatabase getInstance() {
if(instance == null) {
instance = new TDatabase();
}
return instance;
}
~TDatabase() {
if(!IsDisposed)
base.Dispose();
}
internal void addWorking(WorkMessage m) {
List<Dictionary<String, Object>> dayItems = this.getWorkOnDay(m.time);
if(dayItems.Count == 0 && m.working == 1) {
this.insertStartWork(m.time, m.jobID);
} else if(dayItems.Count > 0) {
int started = -1;
int job = -1;
foreach(Dictionary<String, Object> dayItem in dayItems) {
if((TimeSpan)dayItem["stop"] == TimeSpan.Zero) {
started = (int)dayItem["id"];
job = (int)dayItem["location"];
break;
}
}
if(started != -1 && m.working == 0 && m.jobID == job) {
this.updateStopWorking(started, m.time);
} else if(started == -1 && m.working == 1) {
this.insertStartWork(m.time, m.jobID);
} else {
throw new NotImplementedException();
}
} else {
throw new NotImplementedException();
}
}
private void updateStopWorking(Int32 started, DateTime time) {
base.Execute("UPDATE `work` SET stop=@P0 WHERE id=@P1",
time.ToString("HH:mm:ss"), started.ToString());
}
internal bool insertStartWork(DateTime time, Int32 jobID) {
int Rows = base.Execute("INSERT INTO `work` (`date`, `start`, `type`, `location`) VALUES (@P0, @P1, @P2, @P3)",
time.ToString("yyyy-MM-dd"), time.ToString("HH:mm:ss"), "ok", jobID.ToString()
);
return (Rows != 0);
}
internal List<Dictionary<String, Object>> getWorkOnDay(DateTime time) {
return base.Query("SELECT * FROM `work` WHERE date=@P0 ORDER BY `start` ASC", time.ToString("yyyy-MM-dd"));
}
/// <summary>
/// Returns the number of accounts in the database
/// </summary>
/// <returns></returns>
public int GetNumAccounts() {
var Row = base.Query("SELECT COUNT(id) AS count FROM accounts");
return Int32.Parse(Row[0]["count"].ToString());
}
}
}

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeKeeper.Exceptions {
class DbConnectException : Exception {
public DbConnectException(string Message, Exception Inner) : base(Message, Inner) { }
}
}

View File

@ -0,0 +1,17 @@
using BlubbFish.Utils;
using System.Windows.Forms;
namespace TimeKeeper {
class StaticConfig {
public static class DbConfig {
private static InIReader i = InIReader.getInstance("settings.ini");
public static string Engine { get { return i.getValue("database", "engine"); } }
public static string Host { get { return i.getValue("database", "host"); } }
public static int Port { get { return int.Parse(i.getValue("database", "port")); } }
public static string Db { get { return i.getValue("database", "db"); } }
public static string User { get { return i.getValue("database", "user"); } }
public static string Pass { get { return i.getValue("database", "pass"); } }
}
public static readonly string RootPath = Application.StartupPath;
}
}

21
TimeKeeper/Misc/Utils.cs Normal file
View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace TimeKeeper {
class Utils {
public static string GetResourceAsString(string ResName) {
string Res = "";
using(Stream ResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResName)) {
using(StreamReader Reader = new StreamReader(ResourceStream)) {
Res = Reader.ReadToEnd();
}
}
return Res;
}
}
}

View File

@ -0,0 +1,31 @@
using BlubbFish.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TimeKeeper.Database;
using TimeKeeper.Models.Types;
namespace TimeKeeper.Models {
class Database : OwnModel<Database> {
private TDatabase database;
public Queue<WorkMessage> Messages { get; internal set; }
protected override void init() {
this.database = TDatabase.getInstance();
}
private Database() {
this.init();
}
internal void checkinMessages() {
while(this.Messages.Count > 0) {
WorkMessage m = this.Messages.Dequeue();
this.database.addWorking(m);
}
}
}
}

View File

@ -18,10 +18,12 @@ namespace TimeKeeper.Models {
private Thread setTimeThread; private Thread setTimeThread;
private InIReader settingsfile; private InIReader settingsfile;
private FileLogger sLogger; private FileLogger sLogger;
private Stack<WorkMessages> MessagesValue = new Stack<WorkMessages>(); private Queue<WorkMessage> MessagesValue = new Queue<WorkMessage>();
private Database DatabaseModel;
private Boolean initComplete = false;
private Tray() { private Tray() {
this.sLogger = FileLogger.getInstance("serial.log", true); this.sLogger = FileLogger.getInstance("serial.log", false);
this.init(); this.init();
} }
@ -35,13 +37,15 @@ namespace TimeKeeper.Models {
set { this.OffsetTimeValue = value; this.update(); } set { this.OffsetTimeValue = value; this.update(); }
} }
public Stack<WorkMessages> Messages { public Queue<WorkMessage> Messages {
get { return this.MessagesValue; } get { return this.MessagesValue; }
} }
public void MessagesPush(WorkMessages m) { public void MessagesPush(WorkMessage m) {
this.MessagesValue.Push(m); this.MessagesValue.Enqueue(m);
this.update(); this.update();
this.DatabaseModel.Messages = this.Messages;
this.DatabaseModel.checkinMessages();
} }
override protected void init() { override protected void init() {
@ -52,6 +56,7 @@ namespace TimeKeeper.Models {
this.serialConnectThread.Start(); this.serialConnectThread.Start();
this.setTimeThread = new Thread(timeRunner); this.setTimeThread = new Thread(timeRunner);
this.setTimeThread.Start(); this.setTimeThread.Start();
this.DatabaseModel = Database.Instance;
} }
internal void Dispose() { internal void Dispose() {
@ -63,7 +68,9 @@ namespace TimeKeeper.Models {
} }
private void timeRunner() { private void timeRunner() {
Thread.Sleep(1000 * 10); while(!this.initComplete) {
Thread.Sleep(100);
}
while(true) { while(true) {
DateTime n = DateTime.UtcNow; DateTime n = DateTime.UtcNow;
this.DataSendHandler("time=" + ((int)((n - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds)).ToString()); this.DataSendHandler("time=" + ((int)((n - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds)).ToString());
@ -90,21 +97,23 @@ namespace TimeKeeper.Models {
private void DataReceivedHandler(Object sender, SerialDataReceivedEventArgs e) { private void DataReceivedHandler(Object sender, SerialDataReceivedEventArgs e) {
SerialPort sp = (SerialPort)sender; SerialPort sp = (SerialPort)sender;
string s = sp.ReadLine().Trim(); string s = sp.ReadLine().Trim();
sLogger.setLine("<-: " + s); sLogger.setLine("<-: " + s, DateTime.Now);
this.parseSerial(s); this.parseSerial(s);
} }
[MethodImpl(MethodImplOptions.Synchronized)] [MethodImpl(MethodImplOptions.Synchronized)]
private void DataSendHandler(String v) { private void DataSendHandler(String v) {
sLogger.setLine("->: " + v); sLogger.setLine("->: " + v, DateTime.Now);
this.serial.WriteLine(v); this.serial.WriteLine(v);
} }
private void parseSerial(String s) { private void parseSerial(String s) {
if(s == "requestKeep=1") { if(s == "requestKeep=1") {
this.DataSendHandler("keep=1"); this.DataSendHandler("keep=1");
} else if(s == "Init...." || s == "Init loading!" || s == "Init finished!") { } else if(s == "Init...." || s == "Init loading!") {
//Ignore that Stuff //Ignore that Stuff
} else if(s == "Init finished!") {
this.initComplete = true;
} else if((s.Length > 4 && s.Substring(0, 4) == "d->:") || (s.Length > 4 && s.Substring(0, 4) == "i<-:")) { } else if((s.Length > 4 && s.Substring(0, 4) == "d->:") || (s.Length > 4 && s.Substring(0, 4) == "i<-:")) {
//Ignore that Stuff also.... //Ignore that Stuff also....
} else if(s.Length > 2 && s.Substring(0, 2) == "t=") { } else if(s.Length > 2 && s.Substring(0, 2) == "t=") {
@ -134,7 +143,7 @@ namespace TimeKeeper.Models {
working = int.Parse(t[1]); working = int.Parse(t[1]);
} }
} }
this.MessagesPush(new WorkMessages(userID, time, jobID, working)); this.MessagesPush(new WorkMessage(userID, time, jobID, working));
} }
private void setOffset(String v) { private void setOffset(String v) {

View File

@ -5,13 +5,13 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace TimeKeeper.Models.Types { namespace TimeKeeper.Models.Types {
class WorkMessages { class WorkMessage {
public Int32 jobID; public Int32 jobID;
public DateTime time; public DateTime time;
public Int64 userID; public Int64 userID;
public Int32 working; public Int32 working;
public WorkMessages(Int64 userID, DateTime time, Int32 jobID, Int32 working) { public WorkMessage(Int64 userID, DateTime time, Int32 jobID, Int32 working) {
this.userID = userID; this.userID = userID;
this.time = time; this.time = time;
this.jobID = jobID; this.jobID = jobID;

View File

@ -13,6 +13,9 @@ namespace TimeKeeper {
t.execute(); t.execute();
Application.Run(); Application.Run();
} catch(Exception e) { } catch(Exception e) {
if(e.InnerException != null) {
e = e.InnerException;
}
MessageBox.Show("Fehler: " + e.Message + "\nStack: " + e.StackTrace, "Exception: " + e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Fehler: " + e.Message + "\nStack: " + e.StackTrace, "Exception: " + e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -13,7 +13,7 @@
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
@ -23,7 +23,7 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>x64</PlatformTarget>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
@ -38,8 +38,15 @@
<ApplicationIcon>Resources\Icons\main.ico</ApplicationIcon> <ApplicationIcon>Resources\Icons\main.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="MySql.Data">
<HintPath>..\lib\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Data.SQLite, Version=1.0.84.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
@ -51,9 +58,15 @@
<ItemGroup> <ItemGroup>
<Compile Include="Controller\CTray.cs" /> <Compile Include="Controller\CTray.cs" />
<Compile Include="Controller\CWindow.cs" /> <Compile Include="Controller\CWindow.cs" />
<Compile Include="Database\DatabaseDriver.cs" />
<Compile Include="Database\DatabaseEngine.cs" />
<Compile Include="Database\TDatabase.cs" />
<Compile Include="Exceptions\DbConnectException.cs" />
<Compile Include="Misc\Utils.cs" />
<Compile Include="Models\MDatabase.cs" />
<Compile Include="Models\MTray.cs" /> <Compile Include="Models\MTray.cs" />
<Compile Include="Models\MWindow.cs" /> <Compile Include="Models\MWindow.cs" />
<Compile Include="Models\Types\WorkMessages.cs" /> <Compile Include="Models\Types\WorkMessage.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs"> <Compile Include="Properties\Resources.Designer.cs">
@ -61,6 +74,7 @@
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon> <DependentUpon>Resources.resx</DependentUpon>
</Compile> </Compile>
<Compile Include="Misc\StaticConfig.cs" />
<Compile Include="View\ViewWindowForm.cs"> <Compile Include="View\ViewWindowForm.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
@ -89,10 +103,12 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="Database\SQL\MySQL.Install.sql" />
<Content Include="Resources\Icons\door_open.png" /> <Content Include="Resources\Icons\door_open.png" />
<Content Include="Resources\Icons\main_con.ico" /> <Content Include="Resources\Icons\main_con.ico" />
<Content Include="Resources\Icons\main_dis.ico" /> <Content Include="Resources\Icons\main_dis.ico" />
</ItemGroup> </ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -7,12 +7,15 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using TimeKeeper.Properties; using TimeKeeper.Properties;
using System.Drawing; using System.Drawing;
using TimeKeeper.Models;
namespace TimeKeeper.View { namespace TimeKeeper.View {
class Tray : OwnView { class Tray : OwnView {
public Models.Tray Model { get; private set; } public Models.Tray Model { get; private set; }
private NotifyIcon trayi; private NotifyIcon trayi;
private Icon[] trayIcons = { new Icon(Resources.TrayIconConnected, 40, 40), new Icon(Resources.TrayIconDisconnected, 40, 40) }; private Icon[] trayIcons = { new Icon(Resources.TrayIconConnected, 40, 40), new Icon(Resources.TrayIconDisconnected, 40, 40) };
private Boolean offsetTimeFail;
public Tray() { public Tray() {
this.init(); this.init();
@ -23,6 +26,19 @@ namespace TimeKeeper.View {
public override void update() { public override void update() {
this.trayi.ContextMenuStrip = this.genMenu(); this.trayi.ContextMenuStrip = this.genMenu();
this.trayi.Icon = (this.Model.isConnected) ? this.trayIcons[0] : this.trayIcons[1]; this.trayi.Icon = (this.Model.isConnected) ? this.trayIcons[0] : this.trayIcons[1];
if(this.Model.Messages.Count > 0) {
Models.Types.WorkMessage m = this.Model.Messages.Peek();
string text = (m.working==1)?"Angefangen zu arbeiten ":"Aufgehört zu arbeiten ";
text += "am " + m.time.ToShortDateString() + " " + m.time.ToLongTimeString() + " ";
text += "in Job " + m.jobID.ToString();
this.showBallonTooltip(text, ToolTipIcon.Info);
} else if(Math.Abs(this.Model.OffsetTime.TotalSeconds) >= 2) {
this.showBallonTooltip("Achtung Abweichung von der Zeit: " + this.Model.OffsetTime.TotalSeconds, ToolTipIcon.Warning);
this.offsetTimeFail = true;
} else if(Math.Abs(this.Model.OffsetTime.TotalSeconds) < 2 && this.offsetTimeFail) {
this.showBallonTooltip("Zeitabweichung ok: " + this.Model.OffsetTime.TotalSeconds, ToolTipIcon.Info);
this.offsetTimeFail = false;
}
} }
override protected void init() { override protected void init() {

View File

@ -1,2 +1,10 @@
[general] [general]
comport=COM4 comport=COM4
[database]
engine=Mysql
host=localhost
port=3306
db=worktime
user=root
pass=mafia

Binary file not shown.

File diff suppressed because it is too large Load Diff