-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDatabaseHelper.cs
More file actions
214 lines (192 loc) · 7.56 KB
/
Copy pathDatabaseHelper.cs
File metadata and controls
214 lines (192 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ScreenTime
{
public static class DatabaseHelper
{
public class AppUsageData
{
public int Id { get; set; }
public string AppName { get; set; }
public long StartTime { get; set; }
public long EndTime { get; set; }
}
private static string connectionString = "Data Source=mydatabase.db;Version=3;";
private static ConcurrentQueue<Action<SQLiteConnection>> taskQueue = new ConcurrentQueue<Action<SQLiteConnection>>();
private static CancellationTokenSource cts = new CancellationTokenSource();
private static Task backgroundTask = Task.Run(() => ProcessQueue(cts.Token));
static DatabaseHelper()
{
// Ensure the database is initialized when the class is first accessed
InitializeDatabase();
}
private static async Task ProcessQueue(CancellationToken token)
{
using (var connection = new SQLiteConnection(connectionString))
{
await connection.OpenAsync();
while (!token.IsCancellationRequested)
{
if (taskQueue.TryDequeue(out var task))
{
task(connection);
}
else
{
await Task.Delay(100); // Adjust the delay as needed
}
}
}
}
public static void InitializeDatabase()
{
EnqueueTask(connection =>
{
string createTableQuery = @"CREATE TABLE IF NOT EXISTS FocusSessions (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
AppName TEXT NOT NULL,
StartTime INTEGER NOT NULL,
EndTime INTEGER NOT NULL
);";
using (SQLiteCommand cmd = new SQLiteCommand(createTableQuery, connection))
{
cmd.ExecuteNonQuery();
}
});
}
public static void InsertData(string appName, long startTime, long endTime)
{
EnqueueTask(connection =>
{
string insertQuery = "INSERT INTO FocusSessions (AppName, StartTime, EndTime) VALUES (@AppName, @StartTime, @EndTime)";
Stopwatch stopwatch = Stopwatch.StartNew();
using (SQLiteCommand cmd = new SQLiteCommand(insertQuery, connection))
{
cmd.Parameters.AddWithValue("@AppName", appName);
cmd.Parameters.AddWithValue("@StartTime", startTime);
cmd.Parameters.AddWithValue("@EndTime", endTime);
cmd.ExecuteNonQuery();
}
stopwatch.Stop();
Debug.WriteLine($"Time elapsed of db operation: {stopwatch.ElapsedMilliseconds} ms");
});
}
public static DataTable LoadData()
{
var dt = new DataTable();
var tcs = new TaskCompletionSource<object>();
EnqueueTask(connection =>
{
try
{
string selectQuery = "SELECT * FROM FocusSessions";
using (SQLiteCommand cmd = new SQLiteCommand(selectQuery, connection))
{
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd))
{
adapter.Fill(dt);
}
}
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
tcs.Task.Wait();
return dt;
}
public static void UpdateData(int id, string appName, long startTime, long endTime)
{
EnqueueTask(connection =>
{
string updateQuery = "UPDATE FocusSessions SET AppName = @AppName, StartTime = @StartTime, EndTime = @EndTime WHERE Id = @Id";
using (SQLiteCommand cmd = new SQLiteCommand(updateQuery, connection))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@AppName", appName);
cmd.Parameters.AddWithValue("@StartTime", startTime);
cmd.Parameters.AddWithValue("@EndTime", endTime);
cmd.ExecuteNonQuery();
}
});
}
public static void DeleteData(int id)
{
EnqueueTask(connection =>
{
string deleteQuery = "DELETE FROM FocusSessions WHERE Id = @Id";
using (SQLiteCommand cmd = new SQLiteCommand(deleteQuery, connection))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.ExecuteNonQuery();
}
});
}
public static void DeleteAllData()
{
EnqueueTask(connection =>
{
string deleteAllQuery = "DELETE FROM FocusSessions";
using (SQLiteCommand cmd = new SQLiteCommand(deleteAllQuery, connection))
{
cmd.ExecuteNonQuery();
}
});
}
public static List<AppUsageData> GetDataFromSpecificDay(long startOfDayUnix, long endOfDayUnix)
{
var results = new List<AppUsageData>();
var tcs = new TaskCompletionSource<object>();
EnqueueTask(connection =>
{
try
{
string selectQuery = "SELECT * FROM FocusSessions WHERE StartTime >= @StartOfDayUnix AND StartTime <= @EndOfDayUnix";
using (SQLiteCommand cmd = new SQLiteCommand(selectQuery, connection))
{
cmd.Parameters.AddWithValue("@StartOfDayUnix", startOfDayUnix);
cmd.Parameters.AddWithValue("@EndOfDayUnix", endOfDayUnix);
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var data = new AppUsageData
{
Id = reader.GetInt32(0),
AppName = reader.GetString(1),
StartTime = reader.GetInt64(2),
EndTime = reader.GetInt64(3)
};
results.Add(data);
}
}
}
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
tcs.Task.Wait();
return results;
}
private static void EnqueueTask(Action<SQLiteConnection> task)
{
taskQueue.Enqueue(task);
}
public static void Dispose()
{
cts.Cancel();
backgroundTask.Wait();
}
}
}