ClassRequests.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls.Primitives;
  11. using System.Xml.Linq;
  12. namespace PFC.Program
  13. {
  14. /* Общий класс */
  15. public class CommonClass
  16. {
  17. // Метод возврата соединения к базе данных //
  18. public static SqlConnection GetConnection()
  19. {
  20. string connection = @"Data Source=(LocalDB)\MSSQLLocalDB;
  21. AttachDbFilename=|DataDirectory|\DB\PFC_DB.mdf;
  22. Integrated Security=True;
  23. Connect Timeout=30";
  24. SqlConnection conn = new SqlConnection(connection);
  25. return conn;
  26. }
  27. }
  28. /* Класс запросов */
  29. public class ClassRequests
  30. {
  31. /** МОДУЛЬ РЕГИСТРАЦИИ **/
  32. // Проверка на уникальность введенного логина
  33. public static SqlDataReader CheckUniqLogin_Registration()
  34. {
  35. SqlConnection conn = CommonClass.GetConnection();
  36. conn.Open();
  37. string Expression = "SELECT login FROM Profiles";
  38. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  39. SqlDataReader reader = cmdExpression.ExecuteReader();
  40. return reader;
  41. }
  42. // Создание нового профиля
  43. public static void AddProfile_Registration(string login, string password, string secfrase)
  44. {
  45. string ExpressionAdd;
  46. SqlConnection conn = CommonClass.GetConnection();
  47. conn.Open();
  48. if (secfrase == "")
  49. {
  50. ExpressionAdd = $@"INSERT INTO Profiles(login, password)
  51. VALUES (N'{login}', N'{password}')";
  52. }
  53. else {
  54. ExpressionAdd = $@"INSERT INTO Profiles(login, password, secPhrase)
  55. VALUES (N'{login}', N'{password}', N'{secfrase}')";
  56. }
  57. SqlCommand cmdExpressionAdd = new SqlCommand(ExpressionAdd, conn);
  58. cmdExpressionAdd.ExecuteNonQuery();
  59. conn.Close();
  60. }
  61. /** МОДУЛЬ АВТОРИЗАЦИИ **/
  62. // Получение данных для авторизации
  63. public static SqlDataReader GetReader_Authorization()
  64. {
  65. SqlConnection conn = CommonClass.GetConnection();
  66. conn.Open();
  67. string Expression = "SELECT profile_id, login, password, secPhrase FROM Profiles";
  68. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  69. SqlDataReader reader = cmdExpression.ExecuteReader();
  70. return reader;
  71. }
  72. // Изменение пароля с помощью секретной фразы
  73. public static void ChangePassword_Authorization(string newPassword, string login)
  74. {
  75. string ExpressionAdd;
  76. SqlConnection conn = CommonClass.GetConnection();
  77. conn.Open();
  78. ExpressionAdd = $@"UPDATE Profiles SET password = N'{newPassword}'
  79. WHERE login = N'{login}'";
  80. SqlCommand cmdExpressionAdd = new SqlCommand(ExpressionAdd, conn);
  81. cmdExpressionAdd.ExecuteNonQuery();
  82. conn.Close();
  83. }
  84. /** МОДУЛЬ ПРОФИЛЯ **/
  85. // Изменение аватарки профиля
  86. public static void UpdateAva_Profile(int profile_ID, string path)
  87. {
  88. SqlConnection conn = CommonClass.GetConnection();
  89. conn.Open();
  90. string ExpressionCreateTable = $@"DECLARE @IMG VARBINARY(MAX)
  91. DECLARE @command NVARCHAR(1000)
  92. SET @command = N'SELECT @file1 = CAST(bulkcolumn AS VARBINARY(MAX))
  93. FROM OPENROWSET(BULK ''' + N'{path}' + ''',
  94. SINGLE_BLOB) ROW_SET'
  95. EXEC sp_executesql @command, N'@file1 VARBINARY(MAX) OUTPUT',@file1 =@IMG OUTPUT
  96. UPDATE Profiles
  97. SET avatar = @IMG
  98. WHERE (profile_ID = {profile_ID})";
  99. SqlCommand cmdExpressionCreate = new SqlCommand(ExpressionCreateTable, conn);
  100. cmdExpressionCreate.ExecuteNonQuery();
  101. conn.Close();
  102. }
  103. // Удаление профиля
  104. public static bool DeleteProfile()
  105. {
  106. bool IsDelete = false;
  107. SqlConnection conn = CommonClass.GetConnection();
  108. conn.Open();
  109. string ExpressionDelete = $@"DROP TABLE Txs_{GlobalVaribles.login},
  110. Wallets_{GlobalVaribles.login};
  111. DELETE FROM Profiles WHERE profile_id = {GlobalVaribles.prof_ID};";
  112. SqlCommand cmdExpressionDelete = new SqlCommand(ExpressionDelete, conn);
  113. cmdExpressionDelete.ExecuteNonQuery();
  114. conn.Close();
  115. return IsDelete;
  116. }
  117. // Получение аватарки профиля
  118. public static SqlDataReader GetAva_Profile(int profile_ID)
  119. {
  120. SqlConnection conn = CommonClass.GetConnection();
  121. conn.Open();
  122. string Expression = $@"SELECT avatar FROM Profiles
  123. WHERE (profile_ID = {profile_ID})";
  124. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  125. SqlDataReader reader = cmdExpression.ExecuteReader();
  126. return reader;
  127. }
  128. /** МОДУЛЬ КОШЕЛЬКА **/
  129. // Создание места для будущих кошельков при регистрации профиля
  130. public static void CreateSpaceWallets()
  131. {
  132. SqlConnection conn = CommonClass.GetConnection();
  133. conn.Open();
  134. string ExpressionCreateTable = $@"CREATE TABLE Wallets_{GlobalVaribles.login}
  135. (
  136. wallet_ID INT IDENTITY(1,1) NOT NULL,
  137. profile_ID INT NOT NULL,
  138. name NVARCHAR(50) NOT NULL,
  139. balance MONEY NOT NULL,
  140. tCurrency CHAR(3) NULL
  141. CONSTRAINT PK_Wallets_{GlobalVaribles.login} PRIMARY KEY (wallet_ID),
  142. CONSTRAINT FK_Wallets_{GlobalVaribles.login} FOREIGN KEY (profile_ID) REFERENCES Profiles (profile_ID)
  143. )";
  144. SqlCommand cmdExpressionCreate = new SqlCommand(ExpressionCreateTable, conn);
  145. cmdExpressionCreate.ExecuteNonQuery();
  146. conn.Close();
  147. }
  148. // Проверка на уникальность названия кошелька
  149. public static SqlDataReader CheckUniqNameWallet()
  150. {
  151. SqlConnection conn = CommonClass.GetConnection();
  152. conn.Open();
  153. string Expression = $"SELECT name FROM Wallets_{GlobalVaribles.login}";
  154. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  155. SqlDataReader reader = cmdExpression.ExecuteReader();
  156. return reader;
  157. }
  158. // Создание нового кошелька
  159. public static void CreateNewWallet(int profile_ID, string name, int balance)
  160. {
  161. SqlConnection conn = CommonClass.GetConnection();
  162. conn.Open();
  163. // TODO: в будущем добавить поле типа валюты
  164. string Expression = $@"INSERT INTO Wallets_{GlobalVaribles.login} (profile_ID, name, balance)
  165. VALUES ({profile_ID}, N'{name}', {balance})";
  166. SqlCommand cmdExpressionCreate = new SqlCommand(Expression, conn);
  167. cmdExpressionCreate.ExecuteNonQuery();
  168. conn.Close();
  169. }
  170. // Передача данных о существующих кошельках текущего пользователя
  171. public static SqlDataReader GetInfoAboutWallets()
  172. {
  173. SqlConnection conn = CommonClass.GetConnection();
  174. conn.Open();
  175. string Expression = $@"SELECT name, balance, wallet_ID
  176. FROM Wallets_{GlobalVaribles.login}";
  177. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  178. SqlDataReader reader = cmdExpression.ExecuteReader();
  179. return reader;
  180. }
  181. // Получение кол-ва кошельков
  182. public static SqlDataReader GetCountWallets()
  183. {
  184. SqlConnection conn = CommonClass.GetConnection();
  185. conn.Open();
  186. string Expression = $@"SELECT COUNT(*) AS amount FROM Wallets_{GlobalVaribles.login}";
  187. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  188. SqlDataReader reader = cmdExpression.ExecuteReader();
  189. return reader;
  190. }
  191. // Удаление кошелька
  192. public static bool DeleteWallet()
  193. {
  194. bool IsDelete = false;
  195. SqlConnection conn = CommonClass.GetConnection();
  196. conn.Open();
  197. string ExpressionDelete = $@"DELETE FROM Wallets_{GlobalVaribles.login}
  198. WHERE (wallet_ID = {GlobalVaribles.selectWallet})";
  199. try
  200. {
  201. SqlCommand cmdExpressionDelete = new SqlCommand(ExpressionDelete, conn);
  202. cmdExpressionDelete.ExecuteNonQuery();
  203. IsDelete = true;
  204. }
  205. catch (SqlException)
  206. {
  207. MessageBox.Show("Стоп! Вы пытаетесь удалить кошелек, в котором имеются данные о расходах или доходах",
  208. "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  209. }
  210. conn.Close();
  211. return IsDelete;
  212. }
  213. // Передача имени выбранного кошелька
  214. public static SqlDataReader GetNameChooseWallet(int wallet_ID)
  215. {
  216. SqlConnection conn = CommonClass.GetConnection();
  217. conn.Open();
  218. string Expression = $@"SELECT name FROM Wallets_{GlobalVaribles.login}
  219. WHERE ({wallet_ID} = Wallets_{GlobalVaribles.login}.wallet_ID)";
  220. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  221. SqlDataReader reader = cmdExpression.ExecuteReader();
  222. return reader;
  223. }
  224. /** МОДУЛЬ ТРАНЗАКЦИЙ **/
  225. // Создание таблицы транзакций для профиля
  226. public static void CreateTxsTable()
  227. {
  228. SqlConnection conn = CommonClass.GetConnection();
  229. conn.Open();
  230. string ExpressionCreateTable = $@"CREATE TABLE Txs_{GlobalVaribles.login}
  231. (
  232. tx_ID INT IDENTITY(1,1) NOT NULL,
  233. wallet_ID INT NOT NULL,
  234. catTx_ID INT NOT NULL,
  235. sum MONEY NOT NULL,
  236. description NVARCHAR(250) NULL,
  237. date DATETIME NOT NULL,
  238. CONSTRAINT PK_Txs_{GlobalVaribles.login} PRIMARY KEY (tx_ID),
  239. CONSTRAINT FK1_Txs_{GlobalVaribles.login}
  240. FOREIGN KEY (wallet_ID)
  241. REFERENCES Wallets_{GlobalVaribles.login} (wallet_ID),
  242. CONSTRAINT FK2_Txs_{GlobalVaribles.login}
  243. FOREIGN KEY (catTx_ID)
  244. REFERENCES CategoryTx (catTx_id)
  245. )";
  246. SqlCommand cmdExpressionCreate = new SqlCommand(ExpressionCreateTable, conn);
  247. cmdExpressionCreate.ExecuteNonQuery();
  248. conn.Close();
  249. }
  250. // Полученике кол-ва транзакций в выбранном кошельке
  251. public static SqlDataReader GetCountTxs(int wallet_ID)
  252. {
  253. SqlConnection conn = CommonClass.GetConnection();
  254. conn.Open();
  255. string Expression = $@"SELECT COUNT(*) AS amount FROM Txs_{GlobalVaribles.login}
  256. WHERE ({wallet_ID} = Txs_{GlobalVaribles.login}.wallet_ID)";
  257. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  258. SqlDataReader reader = cmdExpression.ExecuteReader();
  259. return reader;
  260. }
  261. // Получение кол-ва категорий
  262. public static SqlDataReader GetCountCategories()
  263. {
  264. SqlConnection conn = CommonClass.GetConnection();
  265. conn.Open();
  266. string Expression = $@"SELECT COUNT(*) AS amount FROM CategoryTx";
  267. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  268. SqlDataReader reader = cmdExpression.ExecuteReader();
  269. return reader;
  270. }
  271. // Получение ID категорий
  272. public static SqlDataReader GetCategoriesID()
  273. {
  274. SqlConnection conn = CommonClass.GetConnection();
  275. conn.Open();
  276. string Expression = $@"SELECT catTx_id, name FROM CategoryTx";
  277. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  278. SqlDataReader reader = cmdExpression.ExecuteReader();
  279. return reader;
  280. }
  281. // Передача данных обо всех транзакциях текущего профиля
  282. public static SqlDataReader GetInfo_AboutTx(int wallet_ID)
  283. {
  284. SqlConnection conn = CommonClass.GetConnection();
  285. conn.Open();
  286. string Expression = $@"SELECT CategoryTx.name, sum, description, date
  287. FROM CategoryTx, Txs_{GlobalVaribles.login}
  288. WHERE ({wallet_ID} = Txs_{GlobalVaribles.login}.wallet_ID) AND
  289. (Txs_{GlobalVaribles.login}.catTx_ID = CategoryTx.catTx_id)
  290. ORDER BY date";
  291. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  292. SqlDataReader reader = cmdExpression.ExecuteReader();
  293. return reader;
  294. }
  295. // Удаление категории
  296. public static void DeleteCategory(int catTx_id)
  297. {
  298. SqlConnection conn = CommonClass.GetConnection();
  299. conn.Open();
  300. string ExpressionDelete = $@"DELETE FROM CategoryTx
  301. WHERE (catTx_id = {catTx_id})";
  302. try
  303. {
  304. SqlCommand cmdExpressionDelete = new SqlCommand(ExpressionDelete, conn);
  305. cmdExpressionDelete.ExecuteNonQuery();
  306. }
  307. catch (SqlException)
  308. {
  309. MessageBox.Show("Стоп! Вы пытаетесь удалить категорию, которая уже используется в транзакциях" +
  310. "\nУдалите транзакции и повторите операцию снова.",
  311. "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  312. }
  313. conn.Close();
  314. }
  315. // Добавление новой категории
  316. public static void CreateNewCategory(string name)
  317. {
  318. SqlConnection conn = CommonClass.GetConnection();
  319. conn.Open();
  320. string Expression = $@"INSERT INTO CategoryTx (name)
  321. VALUES (N'{name}')";
  322. SqlCommand cmdExpressionCreate = new SqlCommand(Expression, conn);
  323. cmdExpressionCreate.ExecuteNonQuery();
  324. conn.Close();
  325. }
  326. // Передача имени категорий для сравнения
  327. public static SqlDataReader GetCategoryName()
  328. {
  329. SqlConnection conn = CommonClass.GetConnection();
  330. conn.Open();
  331. string Expression = $"SELECT name FROM CategoryTx";
  332. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  333. SqlDataReader reader = cmdExpression.ExecuteReader();
  334. return reader;
  335. }
  336. // Передача данных о транзакциях расхода
  337. public static SqlDataReader GetInfo_AboutExpTxs(int wallet_ID)
  338. {
  339. SqlConnection conn = CommonClass.GetConnection();
  340. conn.Open();
  341. string Expression = $@"SELECT CategoryTx.name, sum, description, date
  342. FROM CategoryTx, Txs_{GlobalVaribles.login}
  343. WHERE ({wallet_ID} = Txs_{GlobalVaribles.login}.wallet_ID) AND
  344. (Txs_{GlobalVaribles.login}.catTx_ID = CategoryTx.catTx_id) AND
  345. (sum < 0)";
  346. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  347. SqlDataReader reader = cmdExpression.ExecuteReader();
  348. return reader;
  349. }
  350. // Передача данных о транзакциях дохода
  351. public static SqlDataReader GetInfo_AboutPrfTxs(int wallet_ID)
  352. {
  353. SqlConnection conn = CommonClass.GetConnection();
  354. conn.Open();
  355. string Expression = $@"SELECT CategoryTx.name, sum, description, date
  356. FROM CategoryTx, Txs_{GlobalVaribles.login}
  357. WHERE ({wallet_ID} = Txs_{GlobalVaribles.login}.wallet_ID) AND
  358. (Txs_{GlobalVaribles.login}.catTx_ID = CategoryTx.catTx_id) AND
  359. (sum > 0)";
  360. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  361. SqlDataReader reader = cmdExpression.ExecuteReader();
  362. return reader;
  363. }
  364. // Получение reader'a для поиска транзакций расхода через ComboBox
  365. public static SqlDataReader GetReaderCbx_ExpTxs(int index)
  366. {
  367. SqlConnection conn = CommonClass.GetConnection();
  368. conn.Open();
  369. string Expression = $@"SELECT CategoryTx.name, sum, description, date
  370. FROM CategoryTx, Txs_{GlobalVaribles.login}
  371. WHERE ({index} = Txs_{GlobalVaribles.login}.catTx_id) AND
  372. ({index} = CategoryTx.catTx_id) AND
  373. (sum < 0) AND ({GlobalVaribles.selectWallet} = wallet_ID)
  374. ORDER BY date";
  375. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  376. SqlDataReader reader = cmdExpression.ExecuteReader();
  377. return reader;
  378. }
  379. // Получение reader'a для поиска транзакций дохода через ComboBox
  380. public static SqlDataReader GetReaderCbx_PrfTxs(int index)
  381. {
  382. SqlConnection conn = CommonClass.GetConnection();
  383. conn.Open();
  384. string Expression = $@"SELECT CategoryTx.name, sum, description, date
  385. FROM CategoryTx, Txs_{GlobalVaribles.login}
  386. WHERE ({index} = Txs_{GlobalVaribles.login}.catTx_id) AND
  387. ({index} = CategoryTx.catTx_id) AND
  388. (sum > 0) AND ({GlobalVaribles.selectWallet} = wallet_ID)
  389. ORDER BY date";
  390. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  391. SqlDataReader reader = cmdExpression.ExecuteReader();
  392. return reader;
  393. }
  394. // Получить сумму последней транзакции из таблицы
  395. public static SqlDataReader GetLastSum_FromTxs(int wallet_ID)
  396. {
  397. SqlConnection conn = CommonClass.GetConnection();
  398. conn.Open();
  399. string Expression = $@"SELECT sum FROM Txs_{GlobalVaribles.login}
  400. WHERE tx_ID = (SELECT MAX(tx_ID) FROM Txs_{GlobalVaribles.login}
  401. WHERE wallet_ID = {wallet_ID})";
  402. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  403. SqlDataReader reader = cmdExpression.ExecuteReader();
  404. return reader;
  405. }
  406. // Удаление последней транзакции
  407. public static void DeleteLastTx(int wallet_ID)
  408. {
  409. SqlConnection conn = CommonClass.GetConnection();
  410. conn.Open();
  411. string Expression = $@"DELETE FROM Txs_{GlobalVaribles.login}
  412. WHERE (tx_ID = (SELECT MAX(tx_ID) FROM Txs_{GlobalVaribles.login}
  413. WHERE wallet_ID = {wallet_ID}))";
  414. SqlCommand cmdExpressionDelete = new SqlCommand(Expression, conn);
  415. cmdExpressionDelete.ExecuteNonQuery();
  416. conn.Close();
  417. }
  418. // Передача значений в ComboBox из категорий транзакций
  419. public static SqlDataReader GetInfo_FromCategoryTx()
  420. {
  421. SqlConnection conn = CommonClass.GetConnection();
  422. conn.Open();
  423. string Expression = $@"SELECT name FROM CategoryTx";
  424. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  425. SqlDataReader reader = cmdExpression.ExecuteReader();
  426. return reader;
  427. }
  428. // Передача значений в таблицу транзакций
  429. public static void InsertData_Tx(int wallet_ID, int catTx_ID, int sum, string desc, string date)
  430. {
  431. SqlConnection conn = CommonClass.GetConnection();
  432. conn.Open();
  433. string Expression = $@"INSERT INTO Txs_{GlobalVaribles.login}
  434. (wallet_ID, catTx_ID, sum, description, date)
  435. VALUES
  436. ({wallet_ID}, {catTx_ID}, {sum}, N'{desc}', '{date}')";
  437. SqlCommand cmdExpressionCreate = new SqlCommand(Expression, conn);
  438. cmdExpressionCreate.ExecuteNonQuery();
  439. conn.Close();
  440. }
  441. // Передача данных баланса
  442. public static SqlDataReader GetInfo_AboutBalance(int wallet_ID)
  443. {
  444. SqlConnection conn = CommonClass.GetConnection();
  445. conn.Open();
  446. string Expression = $@"SELECT balance FROM Wallets_{GlobalVaribles.login}
  447. WHERE ({wallet_ID} = Wallets_{GlobalVaribles.login}.wallet_ID)";
  448. SqlCommand cmdExpression = new SqlCommand(Expression, conn);
  449. SqlDataReader reader = cmdExpression.ExecuteReader();
  450. return reader;
  451. }
  452. // Изменение баланса
  453. public static void UpdateBalance(int wallet_ID, int newBalance)
  454. {
  455. SqlConnection conn = CommonClass.GetConnection();
  456. conn.Open();
  457. string ExpressionCreateTable = $@"UPDATE Wallets_{GlobalVaribles.login}
  458. SET balance = {newBalance}
  459. WHERE ({wallet_ID} = Wallets_{GlobalVaribles.login}.wallet_ID)";
  460. SqlCommand cmdExpressionCreate = new SqlCommand(ExpressionCreateTable, conn);
  461. cmdExpressionCreate.ExecuteNonQuery();
  462. conn.Close();
  463. }
  464. }
  465. }