Advertisement
Guest User

C# Ayzada Project

a guest
Jun 13th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 37.21 KB | None | 0 0
  1. //
  2. //
  3. // Код для основной панели пользователя
  4. //
  5. //
  6.  
  7. using System;
  8. using System.Collections.Generic;
  9. using System.ComponentModel;
  10. using System.Data;
  11. using System.Drawing;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Windows.Forms;
  15. using System.Data.Common;
  16. using System.Data.SQLite;
  17.  
  18. namespace DataBaseProject
  19. {
  20.     public partial class MainPanel : Form
  21.     {
  22.         public MainPanel()
  23.         {
  24.             InitializeComponent();
  25.         }
  26.  
  27.         private void MainPanel_Load(object sender, EventArgs e)
  28.         {
  29.         // После авторизации нам необходимо заполнить всю информацию для пользователя
  30.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  31.             connection.Open();
  32.  
  33.             SQLiteCommand allInfoOfUserRequest = new SQLiteCommand(String.Format("SELECT * FROM `users` WHERE `id`='{0}'", StaticExp.sUserID), connection);
  34.             SQLiteDataReader allInfoOfUser = allInfoOfUserRequest.ExecuteReader();
  35.  
  36.             foreach (DbDataRecord record in allInfoOfUser)
  37.             {
  38.                 StaticExp.sUserLogin = record["username"].ToString();
  39.                 StaticExp.sUserFullName = record["fullname"].ToString();
  40.             }
  41.             connection.Close();
  42.  
  43.             userNameDisplay.Text = StaticExp.sUserFullName;
  44.         }
  45.  
  46.         private void MainPanel_FormClosed(object sender, FormClosedEventArgs e)
  47.         {
  48.             Application.ExitThread();
  49.             Application.Exit();
  50.         }
  51.  
  52.         private void btn_myProfile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  53.         {
  54.             userProfileForm myProfileForm = new userProfileForm();
  55.             myProfileForm.ShowDialog();
  56.         }
  57.  
  58.         private void btn_newRequest_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  59.         {
  60.             NewRequest newRequestForm = new NewRequest();
  61.             newRequestForm.ShowDialog();
  62.         }
  63.  
  64.         private void btn_myRequests_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  65.         {
  66.             allMyRequests allMyRequestsForm = new allMyRequests();
  67.             allMyRequestsForm.ShowDialog();
  68.         }
  69.  
  70.         private void btn_restartApp_Click(object sender, EventArgs e)
  71.         {
  72.             Application.Restart();
  73.         }
  74.  
  75.         private void btn_MessageCenter_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  76.         {
  77.             MessagesCenter messagesCenterForm = new MessagesCenter();
  78.             messagesCenterForm.ShowDialog();
  79.         }
  80.  
  81.         private void btn_newRate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  82.         {
  83.             userSetRating rateForm = new userSetRating();
  84.             rateForm.ShowDialog();
  85.         }
  86.  
  87.         private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  88.         {
  89.             NewRequest newRequestForm = new NewRequest();
  90.             newRequestForm.ShowDialog();
  91.         }
  92.     }
  93. }
  94.  
  95.  
  96. //
  97. //
  98. // Код для регистации пользователя
  99. //
  100. //
  101. using System;
  102. using System.Collections.Generic;
  103. using System.ComponentModel;
  104. using System.Data;
  105. using System.Drawing;
  106. using System.Linq;
  107. using System.Text;
  108. using System.Windows.Forms;
  109. using System.Data.Common;
  110. using System.Data.SQLite;
  111.  
  112. namespace DataBaseProject
  113. {
  114.     public partial class RegisterForm : Form
  115.     {
  116.         private int CAPTCHA_firstNumber = 0;
  117.         private int CAPTCHA_secondNumber = 0;
  118.         private int CAPTCHA_result = 0;
  119.  
  120.         public RegisterForm()
  121.         {
  122.             InitializeComponent();
  123.         }
  124.  
  125.         private void RegisterForm_Load(object sender, EventArgs e)
  126.         {
  127.             Random generator = new Random();
  128.             CAPTCHA_firstNumber = generator.Next(0, 100);
  129.             CAPTCHA_secondNumber = generator.Next(0, 100);
  130.  
  131.             CAPTCHA.Text = CAPTCHA_firstNumber + " + " + CAPTCHA_secondNumber + " = ?";
  132.  
  133.             CAPTCHA_result = CAPTCHA_firstNumber + CAPTCHA_secondNumber;
  134.         }
  135.  
  136.         private void go_register_Click(object sender, EventArgs e)
  137.         {
  138.             // Сначала проверяем наши поля на введённость данных:
  139.             if (String.IsNullOrEmpty(username_textbox.Text))
  140.             {
  141.                 MessageBox.Show("Поле 'Логин' не может быть пустым!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  142.                 return;
  143.             }
  144.  
  145.             if (String.IsNullOrEmpty(password_textbox.Text))
  146.             {
  147.                 MessageBox.Show("Поле 'Пароль' не может быть пустым!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  148.                 return;
  149.             }
  150.  
  151.             if (password_textbox.Text != password_confirm_textbox.Text)
  152.             {
  153.                 MessageBox.Show("Пароли не совпадают, введите пароли заново!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  154.                 return;
  155.             }
  156.  
  157.             if (String.IsNullOrEmpty(fullname_textbox.Text))
  158.             {
  159.                 MessageBox.Show("Поле 'Ф.И.О' не заполнено. Заполните, пожалуйста.", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  160.                 return;
  161.             }
  162.  
  163.             if (String.IsNullOrEmpty(phoneNumber_textbox.Text) || phoneNumber_textbox.Text == "+7")
  164.             {
  165.                 MessageBox.Show("Поле 'Номер телефона' не заполнено. Заполните, пожалуйста.", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  166.                 return;
  167.             }
  168.  
  169.             if (captcha_textbox.Text != CAPTCHA_result.ToString())
  170.             {
  171.                 MessageBox.Show("Вы неверно ответили на вопрос. Пожалуйста, перепроверьте!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  172.                 return;
  173.             }
  174.  
  175.             /// После того, как данные проверены, мы должны проверить, нет ли такого пользователя у нас в базе данных:
  176.                 // Сначала преобразуем все символы логина в маленькие буквы:
  177.             username_textbox.Text = username_textbox.Text.ToLower();
  178.                 // Сначала создаём подключение к базе данных:
  179.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  180.                 // Открываем соединение к базе данных:
  181.             connection.Open();
  182.                 // Создаём запрос:
  183.             SQLiteCommand request = new SQLiteCommand(String.Format("SELECT COUNT(*) AS cnt FROM `users` WHERE `username` = '{0}'", username_textbox.Text), connection);
  184.                 // Теперь выполняем запрос и результат ложим в reader:
  185.             SQLiteDataReader reader = request.ExecuteReader();
  186.                 // Проверяем, есть ли у нас такой пользователь:
  187.             int count = 1;
  188.             foreach (DbDataRecord record in reader)
  189.             {
  190.                 count = int.Parse(record[0].ToString());
  191.             }
  192.                 // Если пользователь с таким логином существует - выводим ошибку:
  193.             if (count > 0)
  194.             {
  195.                 MessageBox.Show("Пользователь с таким логином уже существует. Пожалуйста, выберите другой логин.", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  196.                 return;
  197.             }
  198.                 // Если же пользователя с таким логином нет - создаём запрос для записи в базу данных:
  199.             SQLiteCommand addUserRequest = new SQLiteCommand(String.Format("INSERT INTO `users` (`username`, `password`, `fullname`, `birthday`, `phone`) VALUES ('{0}', '{1}','{2}', '{3}', '{4}')", username_textbox.Text, password_textbox.Text, fullname_textbox.Text, birthday_datePicker.Value.ToLongDateString(), phoneNumber_textbox.Text), connection);
  200.                 // Выполняем запрос к базе данных:
  201.             addUserRequest.ExecuteNonQuery();
  202.             SQLiteCommand getUserIDByLogin = new SQLiteCommand(String.Format("SELECT `id` FROM `users` WHERE `username`='{0}'", username_textbox.Text), connection);
  203.             SQLiteDataReader userIDResult = getUserIDByLogin.ExecuteReader();
  204.             string userID = null;
  205.             foreach (DbDataRecord record in userIDResult)
  206.             {
  207.                 userID = record["id"].ToString();
  208.             }
  209.             SQLiteCommand addAdditionalUserInfoRequest = new SQLiteCommand(String.Format("INSERT INTO `user_additional` (`id`, `photo`, `address`, `email`) VALUES ('{0}','','','')", userID), connection);
  210.             addAdditionalUserInfoRequest.ExecuteNonQuery();
  211.                 // Выводим сообщение о завершении регистрации:
  212.             MessageBox.Show("Регистрация завершена!");
  213.                 // Закрываем соединение:
  214.             connection.Close();
  215.                 // Закрываем окно:
  216.             this.Hide();
  217.         }
  218.     }
  219. }
  220.  
  221. //
  222. //
  223. // Код для входа пользователя
  224. //
  225. //
  226. using System;
  227. using System.Collections.Generic;
  228. using System.ComponentModel;
  229. using System.Data;
  230. using System.Drawing;
  231. using System.Linq;
  232. using System.Text;
  233. using System.Windows.Forms;
  234. using System.Data.Common;
  235. using System.Data.SQLite;
  236. using System.IO;
  237.  
  238. namespace DataBaseProject
  239. {
  240.     public partial class LoginForm : Form
  241.     {
  242.         public LoginForm()
  243.         {
  244.             InitializeComponent();
  245.         }
  246.  
  247.         private void LoginForm_Load(object sender, EventArgs e)
  248.         {
  249.             if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/database.db")) // Если база данных не существует, то:
  250.             {
  251.                 MessageBox.Show("База данных не существует. Приложение аварийно прекращает работу!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  252.                 Application.ExitThread();
  253.                 Application.Exit();
  254.             }
  255.         }
  256.  
  257.         private void btn_Register_Click(object sender, EventArgs e)
  258.         {
  259.             RegisterForm registerForm = new RegisterForm();
  260.             registerForm.ShowDialog();
  261.         }
  262.  
  263.         // Метод выполняется когда мы нажимаем на кнопку "Войти":
  264.         private void btn_Auth_Click(object sender, EventArgs e)
  265.         {
  266.             // Проверяем, ввёл ли пользователь какие-нибудь данные:
  267.             if (String.IsNullOrEmpty(username_textBox.Text) || String.IsNullOrEmpty(password_textBox.Text))
  268.             {
  269.                 MessageBox.Show("Поле 'Логин' или 'Пароль' пустое!", "Ошибка входа", MessageBoxButtons.OK, MessageBoxIcon.Error);
  270.                 return;
  271.             }
  272.             // Приводим логин в нижний регистр:
  273.             username_textBox.Text = username_textBox.Text.ToLower();
  274.             // Для того, чтобы выполнить вход нам необходимо проверить правильность ввода информации, для этого подключаемся к базе данных:
  275.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  276.             // Открываем соединение:
  277.             connection.Open();
  278.             // Создаём запрос на выборку по логину:
  279.             SQLiteCommand selectUserByLogin = new SQLiteCommand(String.Format("SELECT `id`, `password` FROM `users` WHERE `username`='{0}'", username_textBox.Text), connection);
  280.             // Выполняем запрос:
  281.             SQLiteDataReader selectedResult = selectUserByLogin.ExecuteReader();
  282.             // Сохраняем пароль в переменную password:
  283.             string userID = "0";
  284.             string password = "";
  285.             foreach (DbDataRecord reader in selectedResult)
  286.             {
  287.                 // Сохраняем результат в переменные:
  288.                 userID = reader["id"].ToString();
  289.                 password = reader["password"].ToString();
  290.             }
  291.             // Сравниваем пароль, тот который в базе и тот, который ввёл пользователь:
  292.             if ((password != password_textBox.Text) || int.Parse(userID) < 0 )
  293.             {
  294.                 MessageBox.Show("Неверный логин или пароль!", "Ошибка входа", MessageBoxButtons.OK, MessageBoxIcon.Error);
  295.             }
  296.             else
  297.             {
  298.                 StaticExp.sUserID = userID;
  299.                 MainPanel panelForm = new MainPanel();
  300.                 panelForm.Show();
  301.                 this.Hide();
  302.             }
  303.             // Закрываем соединение:
  304.             connection.Close();
  305.         }
  306.  
  307.         private void button1_Click(object sender, EventArgs e)
  308.         {
  309.             AdminLogin adminLoginForm = new AdminLogin();
  310.             adminLoginForm.Show();
  311.             this.Hide();
  312.         }
  313.     }
  314. }
  315.  
  316. //
  317. //
  318. // Код для создания новой заявки
  319. //
  320. //
  321. using System;
  322. using System.Collections.Generic;
  323. using System.ComponentModel;
  324. using System.Data;
  325. using System.Drawing;
  326. using System.Linq;
  327. using System.Text;
  328. using System.Windows.Forms;
  329. using System.Data.Common;
  330. using System.Data.SQLite;
  331.  
  332. namespace DataBaseProject
  333. {
  334.     public partial class NewRequest : Form
  335.     {
  336.         public NewRequest()
  337.         {
  338.             InitializeComponent();
  339.         }
  340.  
  341.         string priceOfSelectedItem = null;
  342.  
  343.         // Событие происходит, когда загружается форма
  344.         private void NewRequest_Load(object sender, EventArgs e)
  345.         {
  346.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  347.             connection.Open();
  348.  
  349.             SQLiteCommand getServiceTypes = new SQLiteCommand("SELECT `name` FROM `service_types`", connection);
  350.             SQLiteDataReader allServiceTypes = getServiceTypes.ExecuteReader();
  351.             foreach (DbDataRecord record in allServiceTypes)
  352.             {
  353.                 serviceTypes_comboBox.Items.Add(record["name"].ToString());
  354.             }
  355.             connection.Close();
  356.         }
  357.  
  358.         // Событие происходит, когда пользователь нажимает на кнопку отправить запрос
  359.         private void btn_sendRequest_Click(object sender, EventArgs e)
  360.         {
  361.             // Если вдруг услуга не выбрана, то просим пользователя сделать это
  362.             if (String.IsNullOrEmpty(serviceTypes_comboBox.Text))
  363.             {
  364.                 MessageBox.Show("Пожалуйста, выберите тип услуги!", "Ошибка создания заявки", MessageBoxButtons.OK, MessageBoxIcon.Error);
  365.                 return;
  366.             }
  367.  
  368.             if (Double.Parse(allMounthesPrice.Text) <= 0.00)
  369.             {
  370.                 MessageBox.Show("Дата окончания заявки не может быть раньше сегодняшней!", "Ошибка создания заявки", MessageBoxButtons.OK, MessageBoxIcon.Error);
  371.                 return;
  372.             }
  373.  
  374.             // Теперь отправляем запрос в базу данных:
  375.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  376.             connection.Open();
  377.             string datetime = DateTime.Now.ToString();
  378.             SQLiteCommand sendRequest = new SQLiteCommand(String.Format("INSERT INTO `requests` (`user_id`, `service`, `status`, `comment`, `datetime`, `price`, `end_time`) VALUES ('{0}', '{1}', '0', '{2}', '{3}', '{4}', '{5}')", StaticExp.sUserID, serviceTypes_comboBox.Text, comment_textBox.Text, datetime, priceOfSelectedItem, userServiceTo_datetime.Value.ToString() ), connection);
  379.             sendRequest.ExecuteNonQuery();
  380.  
  381.             MessageBox.Show("Заявка отправлена! Вы можете посмореть её в меню 'Все заявки'!");
  382.             this.Hide();
  383.  
  384.         }
  385.  
  386.         private void serviceTypes_comboBox_SelectedIndexChanged(object sender, EventArgs e)
  387.         {
  388.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  389.             connection.Open();
  390.             SQLiteCommand getServicePrice = new SQLiteCommand(String.Format("SELECT `price` FROM `service_types` WHERE `name`='{0}'", serviceTypes_comboBox.Text), connection);
  391.             SQLiteDataReader priceOfService = getServicePrice.ExecuteReader();
  392.             foreach (DbDataRecord record in priceOfService)
  393.             {
  394.                 pricePerMonth_label.Text = record["price"] + " тг/мес";
  395.                 priceOfSelectedItem = record["price"].ToString();
  396.                 TimeSpan interval = userServiceTo_datetime.Value - DateTime.Today;
  397.                 allMounthesPrice.Text = Math.Round((int.Parse(record["price"].ToString()) * (interval.TotalDays / 31)), 2).ToString();
  398.             }
  399.             connection.Close();
  400.         }
  401.  
  402.         private void userServiceTo_datetime_ValueChanged(object sender, EventArgs e)
  403.         {
  404.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  405.             connection.Open();
  406.             SQLiteCommand getServicePrice = new SQLiteCommand(String.Format("SELECT `price` FROM `service_types` WHERE `name`='{0}'", serviceTypes_comboBox.Text), connection);
  407.             SQLiteDataReader priceOfService = getServicePrice.ExecuteReader();
  408.             foreach (DbDataRecord record in priceOfService)
  409.             {
  410.                 pricePerMonth_label.Text = record["price"] + " тг/мес";
  411.                 priceOfSelectedItem = record["price"].ToString();
  412.                 TimeSpan interval = userServiceTo_datetime.Value - DateTime.Today;
  413.                 allMounthesPrice.Text = Math.Round((int.Parse(record["price"].ToString()) * (interval.TotalDays / 31)), 2).ToString();
  414.             }
  415.             connection.Close();
  416.         }
  417.     }
  418. }
  419.  
  420. //
  421. //
  422. // Код просмотра всех заявок пользователя
  423. //
  424. //
  425. using System;
  426. using System.Collections.Generic;
  427. using System.ComponentModel;
  428. using System.Data;
  429. using System.Drawing;
  430. using System.Linq;
  431. using System.Text;
  432. using System.Windows.Forms;
  433. using System.Data.Common;
  434. using System.Data.SQLite;
  435.  
  436. namespace DataBaseProject
  437. {
  438.     public partial class allMyRequests : Form
  439.     {
  440.         public allMyRequests()
  441.         {
  442.             InitializeComponent();
  443.         }
  444.  
  445.         // Событие происходит, когда загружается форма
  446.         private void allMyRequests_Load(object sender, EventArgs e)
  447.         {
  448.             refresh();
  449.         }
  450.  
  451.         // Действие для кнопки "удалить выбранную заявку"
  452.         private void btn_deleteSelectedItem_Click(object sender, EventArgs e)
  453.         {
  454.             string id = "0";
  455.             try
  456.             {
  457.                 id = allRequests_DataGrid.CurrentRow.Cells[0].Value.ToString();
  458.             }
  459.             catch
  460.             {
  461.                 MessageBox.Show("Пожалуйста, выберите запись!");
  462.             }
  463.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  464.             connection.Open();
  465.             SQLiteCommand checkRequestStatus = new SQLiteCommand(String.Format("SELECT `status` FROM `requests` WHERE `id`='{0}'", id), connection);
  466.             SQLiteDataReader requestStatus = checkRequestStatus.ExecuteReader();
  467.             foreach (DbDataRecord record in requestStatus)
  468.             {
  469.                 if (int.Parse(record["status"].ToString()) > 1)
  470.                 {
  471.                     MessageBox.Show("Извините, текущую заявку удалить нельзя, так как она уже проходит обработку или действует!", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
  472.                 }
  473.                 else
  474.                 {
  475.                     SQLiteCommand deleteSelectedRequest = new SQLiteCommand(String.Format("DELETE FROM `requests` WHERE `id`='{0}'", id), connection);
  476.                     deleteSelectedRequest.ExecuteNonQuery();
  477.                 }
  478.             }
  479.             connection.Close();
  480.             refresh();
  481.         }
  482.  
  483.         private void refresh()
  484.         {
  485.             allRequests_DataGrid.Rows.Clear();
  486.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  487.             connection.Open();
  488.             SQLiteCommand getMyRequests = new SQLiteCommand(String.Format("SELECT * FROM `requests` WHERE `user_id`='{0}'", StaticExp.sUserID), connection);
  489.             SQLiteDataReader allMyRequests = getMyRequests.ExecuteReader();
  490.             foreach (DbDataRecord record in allMyRequests)
  491.             {
  492.                 DataGridViewRow row = (DataGridViewRow)allRequests_DataGrid.Rows[0].Clone();
  493.                 row.Cells[0].Value = record["id"].ToString();
  494.                 row.Cells[1].Value = record["service"].ToString();
  495.                 row.Cells[2].Value = record["comment"].ToString();
  496.                 // Не просмотрена = 0
  497.                 // Просмотрена = 1
  498.                 // В обработке = 2
  499.                 // Принята = 3
  500.                 // Отвергнута = 4
  501.                 if (record["status"].ToString() == "0")
  502.                 {
  503.                     row.Cells[3].Value = "Заявка не просмотрена!";
  504.                 }
  505.                 else if (record["status"].ToString() == "1")
  506.                 {
  507.                     row.Cells[3].Value = "Заявка просмотрена!";
  508.                 }
  509.                 else if (record["status"].ToString() == "2")
  510.                 {
  511.                     row.Cells[3].Value = "Заявка в обработке!";
  512.                 }
  513.                 else if (record["status"].ToString() == "3")
  514.                 {
  515.                     row.Cells[3].Value = "Заявка принята!";
  516.                 }
  517.                 else if (record["status"].ToString() == "4")
  518.                 {
  519.                     row.Cells[3].Value = "Заявка отклонена!";
  520.                 }
  521.                 else
  522.                 {
  523.                     row.Cells[3].Value = "Неизвестное состояние!";
  524.                 }
  525.                 row.Cells[4].Value = record["datetime"].ToString();
  526.                 row.Cells[5].Value = record["end_time"].ToString();
  527.                 row.Cells[6].Value = record["price"].ToString();
  528.                 allRequests_DataGrid.Rows.Add(row);
  529.             }
  530.             connection.Close();
  531.         }
  532.     }
  533. }
  534.  
  535.  
  536. //
  537. //
  538. // Код для просмотра всех сообщений
  539. //
  540. //
  541. using System;
  542. using System.Collections.Generic;
  543. using System.ComponentModel;
  544. using System.Data;
  545. using System.Drawing;
  546. using System.Linq;
  547. using System.Text;
  548. using System.Windows.Forms;
  549. using System.Data.Common;
  550. using System.Data.SQLite;
  551. using System.IO;
  552.  
  553. namespace DataBaseProject
  554. {
  555.     public partial class MessagesCenter : Form
  556.     {
  557.         public MessagesCenter()
  558.         {
  559.             InitializeComponent();
  560.         }
  561.  
  562.         private void btn_newMessage_Click(object sender, EventArgs e)
  563.         {
  564.             NewMessage newMessageForm = new NewMessage();
  565.             newMessageForm.ShowDialog();
  566.         }
  567.  
  568.         private void refresh()
  569.         {
  570.             allMessages_dataGrid.Rows.Clear();
  571.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  572.             connection.Open();
  573.             SQLiteCommand getMyMessages = new SQLiteCommand(String.Format("SELECT * FROM `messages` WHERE `user_to`='{0}' ORDER BY `id` DESC", StaticExp.sUserID), connection);
  574.             SQLiteDataReader messages = getMyMessages.ExecuteReader();
  575.             foreach (DbDataRecord record in messages)
  576.             {
  577.                 DataGridViewRow row = (DataGridViewRow)allMessages_dataGrid.Rows[0].Clone();
  578.                 string username = "";
  579.                 if (record["user_from"].ToString() == "0")
  580.                 {
  581.                     username = "Администрация";
  582.                 }
  583.                 else
  584.                 {
  585.                     SQLiteCommand getUserInfo = new SQLiteCommand(String.Format("SELECT * FROM `users` WHERE `id`='{0}'", record["user_from"].ToString()), connection);
  586.                     SQLiteDataReader userInfo = getUserInfo.ExecuteReader();
  587.                     foreach (DbDataRecord info in userInfo)
  588.                     {
  589.  
  590.                         username = info["fullname"].ToString();
  591.                     }
  592.                 }
  593.                 row.Cells[0].Value = record["id"].ToString();
  594.                 row.Cells[1].Value = username;
  595.                 row.Cells[2].Value = record["theme"].ToString();
  596.                 row.Cells[3].Value = record["datetime"].ToString();
  597.                 allMessages_dataGrid.Rows.Add(row);
  598.             }
  599.             connection.Close();
  600.         }
  601.  
  602.         private void MessagesCenter_Load(object sender, EventArgs e)
  603.         {
  604.             refresh();
  605.         }
  606.  
  607.         private void btn_readMessage_Click(object sender, EventArgs e)
  608.         {
  609.             try
  610.             {
  611.                 // Для того, чтобы прочесть сообщение, необходимо сначала выбрать ID этого сообщения:
  612.                 string messageID = allMessages_dataGrid.CurrentRow.Cells[0].Value.ToString();
  613.  
  614.                 // Теперь надо открыть форму и показать внутри этой формы полученное сообщение:
  615.                 messageFull messageFullForm = new messageFull();
  616.                 messageFullForm.loadMessage(messageID);
  617.             }
  618.             catch
  619.             {
  620.                 MessageBox.Show("Пожалуйста, выберите сообщение!");
  621.             }
  622.         }
  623.  
  624.         // Действие происходит во время нажатия на кнопку "Удалить сообщение"
  625.         private void btn_deleteMessage_Click(object sender, EventArgs e)
  626.         {
  627.             try
  628.             {
  629.                 // Для того, чтобы удалить сообщение, необходимо сначала выбрать ID этого сообщения:
  630.                 string messageID = allMessages_dataGrid.CurrentRow.Cells[0].Value.ToString();
  631.  
  632.                 // Теперь надо открыть сделать запрос к БД на удаление:
  633.                 SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  634.                 connection.Open();
  635.                 SQLiteCommand deleteMessage = new SQLiteCommand(String.Format("DELETE FROM `messages` WHERE `id`='{0}'", messageID), connection);
  636.                 deleteMessage.ExecuteNonQuery();
  637.                 refresh();
  638.                 connection.Close();
  639.             }
  640.             catch
  641.             {
  642.                 MessageBox.Show("Пожалуйста, выберите сообщение!");
  643.             }
  644.         }
  645.     }
  646. }
  647.  
  648. //
  649. //
  650. // Код для просмотра и создания рейтинга
  651. //
  652. //
  653. using System;
  654. using System.Collections.Generic;
  655. using System.ComponentModel;
  656. using System.Data;
  657. using System.Drawing;
  658. using System.Linq;
  659. using System.Text;
  660. using System.Windows.Forms;
  661. using System.Data.Common;
  662. using System.Data.SQLite;
  663.  
  664. namespace DataBaseProject
  665. {
  666.     public partial class userSetRating : Form
  667.     {
  668.         public userSetRating()
  669.         {
  670.             InitializeComponent();
  671.         }
  672.  
  673.         private void btn_sendRate_Click(object sender, EventArgs e)
  674.         {
  675.             string rate = "-1";
  676.             if (radioButton1.Checked) rate = "1";
  677.             if (radioButton2.Checked) rate = "2";
  678.             if (radioButton3.Checked) rate = "3";
  679.             if (radioButton4.Checked) rate = "4";
  680.             if (radioButton5.Checked) rate = "5";
  681.  
  682.             if (rate == "-1")
  683.             {
  684.                 MessageBox.Show("Перед тем, как оставить отзыв, необходимо поставить оценку!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  685.                 return;
  686.             }
  687.  
  688.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  689.             connection.Open();
  690.             SQLiteCommand setRate = new SQLiteCommand(String.Format("INSERT INTO `rating` (`user_id`, `rating`, `comment`, `datetime`) VALUES ('{0}', '{1}', '{2}', '{3}')", StaticExp.sUserID, rate, comment_textBox.Text, DateTime.Now.ToString()), connection);
  691.             setRate.ExecuteNonQuery();
  692.             connection.Close();
  693.             MessageBox.Show("Оценка поставлена! Спасибо!");
  694.             refresh();
  695.         }
  696.  
  697.         private void userSetRating_Load(object sender, EventArgs e)
  698.         {
  699.             refresh();
  700.         }
  701.  
  702.         private void refresh()
  703.         {
  704.             allRatings_datagrid.Rows.Clear();
  705.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  706.             connection.Open();
  707.             SQLiteCommand getAllRates = new SQLiteCommand("SELECT * FROM `rating` ORDER BY `id` DESC", connection);
  708.             SQLiteDataReader allRates = getAllRates.ExecuteReader();
  709.             foreach (DbDataRecord record in allRates)
  710.             {
  711.                 DataGridViewRow row = (DataGridViewRow)allRatings_datagrid.Rows[0].Clone();
  712.                 SQLiteCommand getUserFullName = new SQLiteCommand(String.Format("SELECT `fullname` FROM `users` WHERE `id`='{0}'", record["user_id"].ToString()), connection);
  713.                 SQLiteDataReader userFullName = getUserFullName.ExecuteReader();
  714.                 foreach (DbDataRecord user in userFullName)
  715.                 {
  716.                     row.Cells[0].Value = user["fullname"].ToString();
  717.                 }
  718.                 row.Cells[1].Value = record["rating"].ToString();
  719.                 row.Cells[2].Value = record["comment"].ToString();
  720.                 row.Cells[3].Value = record["datetime"].ToString();
  721.                 allRatings_datagrid.Rows.Add(row);
  722.             }
  723.             connection.Close();
  724.         }
  725.     }
  726. }
  727.  
  728. //
  729. //
  730. // Код для просмотра и редактирования профиля пользователя
  731. //
  732. //
  733. using System;
  734. using System.Collections.Generic;
  735. using System.ComponentModel;
  736. using System.Data;
  737. using System.Drawing;
  738. using System.Linq;
  739. using System.Text;
  740. using System.Windows.Forms;
  741. using System.IO;
  742. using System.Data.Common;
  743. using System.Data.SQLite;
  744.  
  745. namespace DataBaseProject
  746. {
  747.     public partial class userProfileForm : Form
  748.     {
  749.         public userProfileForm()
  750.         {
  751.             InitializeComponent();
  752.         }
  753.  
  754.         private void btn_userChangePhoto_Click(object sender, EventArgs e)
  755.         {
  756.             if (openPictureFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  757.             {
  758.                 string pictureFilePath = openPictureFile.FileName;
  759.                 userPhoto.LoadAsync(pictureFilePath);
  760.             }
  761.         }
  762.  
  763.         private void btn_saveInfo_Click(object sender, EventArgs e)
  764.         {
  765.             // Проверяем заполненность полей:
  766.             if (String.IsNullOrEmpty(userfullname_textBox.Text) || String.IsNullOrEmpty(userPhoneNumber_textBox.Text))
  767.             {
  768.                 MessageBox.Show("Поля 'Ф.И.О' и 'Номер телефона' обязательны к заполнению!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
  769.                 return;
  770.             }
  771.             // Начинаем сохранение данных:
  772.             string base64StringOfImage = null;
  773.             using (MemoryStream ms = new MemoryStream())
  774.             {
  775.                 userPhoto.Image.Save(ms, userPhoto.Image.RawFormat);
  776.                 // Конвертируем байты в base64
  777.                 base64StringOfImage = Convert.ToBase64String(ms.ToArray());
  778.             }
  779.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  780.             connection.Open();
  781.             SQLiteCommand updateRequest = new SQLiteCommand(String.Format("UPDATE `user_additional` SET `photo`='{0}', `address`='{2}', `email`='{3}', `passport`='{4}', `IIN`='{5}', `getBy`='{6}' WHERE `id`='{1}'", base64StringOfImage, StaticExp.sUserID, userAddress_TextBox.Text, userEmail_textBox.Text, userPassport_textBox.Text, IIN_textBox.Text, getBy_textBox.Text), connection);
  782.             updateRequest.ExecuteNonQuery();
  783.             SQLiteCommand updateMainRequest = new SQLiteCommand(String.Format("UPDATE `users` SET `fullname`='{0}', `phone`='{1}' WHERE `id`='{2}'", userfullname_textBox.Text, userPhoneNumber_textBox.Text, StaticExp.sUserID), connection);
  784.             updateMainRequest.ExecuteNonQuery();
  785.             MessageBox.Show("Изменение данных прошло успешно!");
  786.             connection.Close();
  787.         }
  788.  
  789.         // Действие выполняется, когда открывается данное окошко(изменение профиля)
  790.         private void userProfileForm_Load(object sender, EventArgs e)
  791.         {
  792.             SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
  793.             connection.Open();
  794.             SQLiteCommand getAllInfo = new SQLiteCommand(String.Format("SELECT * FROM `user_additional` WHERE `id`='{0}'", StaticExp.sUserID), connection);
  795.             SQLiteDataReader allInfo = getAllInfo.ExecuteReader();
  796.             foreach (DbDataRecord record in allInfo)
  797.             {
  798.                 if (!String.IsNullOrEmpty(record["photo"].ToString()))
  799.                 {
  800.                     byte[] imageBytes = Convert.FromBase64String(record["photo"].ToString());
  801.                     // Сначала получаем фотографию нашего пользователя:
  802.                     MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
  803.                     Image memImage = Image.FromStream(ms, true);
  804.                     userPhoto.Image = memImage;
  805.                 }
  806.                 // Теперь адрес пользователя:
  807.                 userAddress_TextBox.Text = record["address"].ToString();
  808.  
  809.                 // Теперь e-mail пользователя:
  810.                 userEmail_textBox.Text = record["email"].ToString();
  811.  
  812.                 // Теперь номер удостоверения личности:
  813.                 userPassport_textBox.Text = record["passport"].ToString();
  814.  
  815.                 // Теперь ИИН:
  816.                 IIN_textBox.Text = record["IIN"].ToString();
  817.  
  818.                 // Кем выдан:
  819.                 getBy_textBox.Text = record["getBy"].ToString();
  820.             }
  821.  
  822.             SQLiteCommand getMainInfo = new SQLiteCommand(String.Format("SELECT * FROM `users` WHERE `id`='{0}'", StaticExp.sUserID), connection);
  823.             SQLiteDataReader mainInfo = getMainInfo.ExecuteReader();
  824.             foreach(DbDataRecord record in mainInfo)
  825.             {
  826.                 userfullname_textBox.Text = record["fullname"].ToString();
  827.                 userBirthday_datepicker.Value = DateTime.Parse(record["birthday"].ToString());
  828.                 userPhoneNumber_textBox.Text = record["phone"].ToString();
  829.             }
  830.             connection.Close();
  831.         }
  832.  
  833.         private void btn_changePassword_Click(object sender, EventArgs e)
  834.         {
  835.             ChangePassword changePassword = new ChangePassword();
  836.             changePassword.ShowDialog();
  837.         }
  838.     }
  839. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement