Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- //
- // Код для основной панели пользователя
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- namespace DataBaseProject
- {
- public partial class MainPanel : Form
- {
- public MainPanel()
- {
- InitializeComponent();
- }
- private void MainPanel_Load(object sender, EventArgs e)
- {
- // После авторизации нам необходимо заполнить всю информацию для пользователя
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand allInfoOfUserRequest = new SQLiteCommand(String.Format("SELECT * FROM `users` WHERE `id`='{0}'", StaticExp.sUserID), connection);
- SQLiteDataReader allInfoOfUser = allInfoOfUserRequest.ExecuteReader();
- foreach (DbDataRecord record in allInfoOfUser)
- {
- StaticExp.sUserLogin = record["username"].ToString();
- StaticExp.sUserFullName = record["fullname"].ToString();
- }
- connection.Close();
- userNameDisplay.Text = StaticExp.sUserFullName;
- }
- private void MainPanel_FormClosed(object sender, FormClosedEventArgs e)
- {
- Application.ExitThread();
- Application.Exit();
- }
- private void btn_myProfile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- userProfileForm myProfileForm = new userProfileForm();
- myProfileForm.ShowDialog();
- }
- private void btn_newRequest_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- NewRequest newRequestForm = new NewRequest();
- newRequestForm.ShowDialog();
- }
- private void btn_myRequests_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- allMyRequests allMyRequestsForm = new allMyRequests();
- allMyRequestsForm.ShowDialog();
- }
- private void btn_restartApp_Click(object sender, EventArgs e)
- {
- Application.Restart();
- }
- private void btn_MessageCenter_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- MessagesCenter messagesCenterForm = new MessagesCenter();
- messagesCenterForm.ShowDialog();
- }
- private void btn_newRate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- userSetRating rateForm = new userSetRating();
- rateForm.ShowDialog();
- }
- private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- NewRequest newRequestForm = new NewRequest();
- newRequestForm.ShowDialog();
- }
- }
- }
- //
- //
- // Код для регистации пользователя
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- namespace DataBaseProject
- {
- public partial class RegisterForm : Form
- {
- private int CAPTCHA_firstNumber = 0;
- private int CAPTCHA_secondNumber = 0;
- private int CAPTCHA_result = 0;
- public RegisterForm()
- {
- InitializeComponent();
- }
- private void RegisterForm_Load(object sender, EventArgs e)
- {
- Random generator = new Random();
- CAPTCHA_firstNumber = generator.Next(0, 100);
- CAPTCHA_secondNumber = generator.Next(0, 100);
- CAPTCHA.Text = CAPTCHA_firstNumber + " + " + CAPTCHA_secondNumber + " = ?";
- CAPTCHA_result = CAPTCHA_firstNumber + CAPTCHA_secondNumber;
- }
- private void go_register_Click(object sender, EventArgs e)
- {
- // Сначала проверяем наши поля на введённость данных:
- if (String.IsNullOrEmpty(username_textbox.Text))
- {
- MessageBox.Show("Поле 'Логин' не может быть пустым!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (String.IsNullOrEmpty(password_textbox.Text))
- {
- MessageBox.Show("Поле 'Пароль' не может быть пустым!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (password_textbox.Text != password_confirm_textbox.Text)
- {
- MessageBox.Show("Пароли не совпадают, введите пароли заново!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (String.IsNullOrEmpty(fullname_textbox.Text))
- {
- MessageBox.Show("Поле 'Ф.И.О' не заполнено. Заполните, пожалуйста.", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (String.IsNullOrEmpty(phoneNumber_textbox.Text) || phoneNumber_textbox.Text == "+7")
- {
- MessageBox.Show("Поле 'Номер телефона' не заполнено. Заполните, пожалуйста.", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (captcha_textbox.Text != CAPTCHA_result.ToString())
- {
- MessageBox.Show("Вы неверно ответили на вопрос. Пожалуйста, перепроверьте!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- /// После того, как данные проверены, мы должны проверить, нет ли такого пользователя у нас в базе данных:
- // Сначала преобразуем все символы логина в маленькие буквы:
- username_textbox.Text = username_textbox.Text.ToLower();
- // Сначала создаём подключение к базе данных:
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- // Открываем соединение к базе данных:
- connection.Open();
- // Создаём запрос:
- SQLiteCommand request = new SQLiteCommand(String.Format("SELECT COUNT(*) AS cnt FROM `users` WHERE `username` = '{0}'", username_textbox.Text), connection);
- // Теперь выполняем запрос и результат ложим в reader:
- SQLiteDataReader reader = request.ExecuteReader();
- // Проверяем, есть ли у нас такой пользователь:
- int count = 1;
- foreach (DbDataRecord record in reader)
- {
- count = int.Parse(record[0].ToString());
- }
- // Если пользователь с таким логином существует - выводим ошибку:
- if (count > 0)
- {
- MessageBox.Show("Пользователь с таким логином уже существует. Пожалуйста, выберите другой логин.", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- // Если же пользователя с таким логином нет - создаём запрос для записи в базу данных:
- 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);
- // Выполняем запрос к базе данных:
- addUserRequest.ExecuteNonQuery();
- SQLiteCommand getUserIDByLogin = new SQLiteCommand(String.Format("SELECT `id` FROM `users` WHERE `username`='{0}'", username_textbox.Text), connection);
- SQLiteDataReader userIDResult = getUserIDByLogin.ExecuteReader();
- string userID = null;
- foreach (DbDataRecord record in userIDResult)
- {
- userID = record["id"].ToString();
- }
- SQLiteCommand addAdditionalUserInfoRequest = new SQLiteCommand(String.Format("INSERT INTO `user_additional` (`id`, `photo`, `address`, `email`) VALUES ('{0}','','','')", userID), connection);
- addAdditionalUserInfoRequest.ExecuteNonQuery();
- // Выводим сообщение о завершении регистрации:
- MessageBox.Show("Регистрация завершена!");
- // Закрываем соединение:
- connection.Close();
- // Закрываем окно:
- this.Hide();
- }
- }
- }
- //
- //
- // Код для входа пользователя
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- using System.IO;
- namespace DataBaseProject
- {
- public partial class LoginForm : Form
- {
- public LoginForm()
- {
- InitializeComponent();
- }
- private void LoginForm_Load(object sender, EventArgs e)
- {
- if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/database.db")) // Если база данных не существует, то:
- {
- MessageBox.Show("База данных не существует. Приложение аварийно прекращает работу!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- Application.ExitThread();
- Application.Exit();
- }
- }
- private void btn_Register_Click(object sender, EventArgs e)
- {
- RegisterForm registerForm = new RegisterForm();
- registerForm.ShowDialog();
- }
- // Метод выполняется когда мы нажимаем на кнопку "Войти":
- private void btn_Auth_Click(object sender, EventArgs e)
- {
- // Проверяем, ввёл ли пользователь какие-нибудь данные:
- if (String.IsNullOrEmpty(username_textBox.Text) || String.IsNullOrEmpty(password_textBox.Text))
- {
- MessageBox.Show("Поле 'Логин' или 'Пароль' пустое!", "Ошибка входа", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- // Приводим логин в нижний регистр:
- username_textBox.Text = username_textBox.Text.ToLower();
- // Для того, чтобы выполнить вход нам необходимо проверить правильность ввода информации, для этого подключаемся к базе данных:
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- // Открываем соединение:
- connection.Open();
- // Создаём запрос на выборку по логину:
- SQLiteCommand selectUserByLogin = new SQLiteCommand(String.Format("SELECT `id`, `password` FROM `users` WHERE `username`='{0}'", username_textBox.Text), connection);
- // Выполняем запрос:
- SQLiteDataReader selectedResult = selectUserByLogin.ExecuteReader();
- // Сохраняем пароль в переменную password:
- string userID = "0";
- string password = "";
- foreach (DbDataRecord reader in selectedResult)
- {
- // Сохраняем результат в переменные:
- userID = reader["id"].ToString();
- password = reader["password"].ToString();
- }
- // Сравниваем пароль, тот который в базе и тот, который ввёл пользователь:
- if ((password != password_textBox.Text) || int.Parse(userID) < 0 )
- {
- MessageBox.Show("Неверный логин или пароль!", "Ошибка входа", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- else
- {
- StaticExp.sUserID = userID;
- MainPanel panelForm = new MainPanel();
- panelForm.Show();
- this.Hide();
- }
- // Закрываем соединение:
- connection.Close();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- AdminLogin adminLoginForm = new AdminLogin();
- adminLoginForm.Show();
- this.Hide();
- }
- }
- }
- //
- //
- // Код для создания новой заявки
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- namespace DataBaseProject
- {
- public partial class NewRequest : Form
- {
- public NewRequest()
- {
- InitializeComponent();
- }
- string priceOfSelectedItem = null;
- // Событие происходит, когда загружается форма
- private void NewRequest_Load(object sender, EventArgs e)
- {
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getServiceTypes = new SQLiteCommand("SELECT `name` FROM `service_types`", connection);
- SQLiteDataReader allServiceTypes = getServiceTypes.ExecuteReader();
- foreach (DbDataRecord record in allServiceTypes)
- {
- serviceTypes_comboBox.Items.Add(record["name"].ToString());
- }
- connection.Close();
- }
- // Событие происходит, когда пользователь нажимает на кнопку отправить запрос
- private void btn_sendRequest_Click(object sender, EventArgs e)
- {
- // Если вдруг услуга не выбрана, то просим пользователя сделать это
- if (String.IsNullOrEmpty(serviceTypes_comboBox.Text))
- {
- MessageBox.Show("Пожалуйста, выберите тип услуги!", "Ошибка создания заявки", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (Double.Parse(allMounthesPrice.Text) <= 0.00)
- {
- MessageBox.Show("Дата окончания заявки не может быть раньше сегодняшней!", "Ошибка создания заявки", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- // Теперь отправляем запрос в базу данных:
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- string datetime = DateTime.Now.ToString();
- 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);
- sendRequest.ExecuteNonQuery();
- MessageBox.Show("Заявка отправлена! Вы можете посмореть её в меню 'Все заявки'!");
- this.Hide();
- }
- private void serviceTypes_comboBox_SelectedIndexChanged(object sender, EventArgs e)
- {
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getServicePrice = new SQLiteCommand(String.Format("SELECT `price` FROM `service_types` WHERE `name`='{0}'", serviceTypes_comboBox.Text), connection);
- SQLiteDataReader priceOfService = getServicePrice.ExecuteReader();
- foreach (DbDataRecord record in priceOfService)
- {
- pricePerMonth_label.Text = record["price"] + " тг/мес";
- priceOfSelectedItem = record["price"].ToString();
- TimeSpan interval = userServiceTo_datetime.Value - DateTime.Today;
- allMounthesPrice.Text = Math.Round((int.Parse(record["price"].ToString()) * (interval.TotalDays / 31)), 2).ToString();
- }
- connection.Close();
- }
- private void userServiceTo_datetime_ValueChanged(object sender, EventArgs e)
- {
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getServicePrice = new SQLiteCommand(String.Format("SELECT `price` FROM `service_types` WHERE `name`='{0}'", serviceTypes_comboBox.Text), connection);
- SQLiteDataReader priceOfService = getServicePrice.ExecuteReader();
- foreach (DbDataRecord record in priceOfService)
- {
- pricePerMonth_label.Text = record["price"] + " тг/мес";
- priceOfSelectedItem = record["price"].ToString();
- TimeSpan interval = userServiceTo_datetime.Value - DateTime.Today;
- allMounthesPrice.Text = Math.Round((int.Parse(record["price"].ToString()) * (interval.TotalDays / 31)), 2).ToString();
- }
- connection.Close();
- }
- }
- }
- //
- //
- // Код просмотра всех заявок пользователя
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- namespace DataBaseProject
- {
- public partial class allMyRequests : Form
- {
- public allMyRequests()
- {
- InitializeComponent();
- }
- // Событие происходит, когда загружается форма
- private void allMyRequests_Load(object sender, EventArgs e)
- {
- refresh();
- }
- // Действие для кнопки "удалить выбранную заявку"
- private void btn_deleteSelectedItem_Click(object sender, EventArgs e)
- {
- string id = "0";
- try
- {
- id = allRequests_DataGrid.CurrentRow.Cells[0].Value.ToString();
- }
- catch
- {
- MessageBox.Show("Пожалуйста, выберите запись!");
- }
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand checkRequestStatus = new SQLiteCommand(String.Format("SELECT `status` FROM `requests` WHERE `id`='{0}'", id), connection);
- SQLiteDataReader requestStatus = checkRequestStatus.ExecuteReader();
- foreach (DbDataRecord record in requestStatus)
- {
- if (int.Parse(record["status"].ToString()) > 1)
- {
- MessageBox.Show("Извините, текущую заявку удалить нельзя, так как она уже проходит обработку или действует!", "Ошибка удаления", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- else
- {
- SQLiteCommand deleteSelectedRequest = new SQLiteCommand(String.Format("DELETE FROM `requests` WHERE `id`='{0}'", id), connection);
- deleteSelectedRequest.ExecuteNonQuery();
- }
- }
- connection.Close();
- refresh();
- }
- private void refresh()
- {
- allRequests_DataGrid.Rows.Clear();
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getMyRequests = new SQLiteCommand(String.Format("SELECT * FROM `requests` WHERE `user_id`='{0}'", StaticExp.sUserID), connection);
- SQLiteDataReader allMyRequests = getMyRequests.ExecuteReader();
- foreach (DbDataRecord record in allMyRequests)
- {
- DataGridViewRow row = (DataGridViewRow)allRequests_DataGrid.Rows[0].Clone();
- row.Cells[0].Value = record["id"].ToString();
- row.Cells[1].Value = record["service"].ToString();
- row.Cells[2].Value = record["comment"].ToString();
- // Не просмотрена = 0
- // Просмотрена = 1
- // В обработке = 2
- // Принята = 3
- // Отвергнута = 4
- if (record["status"].ToString() == "0")
- {
- row.Cells[3].Value = "Заявка не просмотрена!";
- }
- else if (record["status"].ToString() == "1")
- {
- row.Cells[3].Value = "Заявка просмотрена!";
- }
- else if (record["status"].ToString() == "2")
- {
- row.Cells[3].Value = "Заявка в обработке!";
- }
- else if (record["status"].ToString() == "3")
- {
- row.Cells[3].Value = "Заявка принята!";
- }
- else if (record["status"].ToString() == "4")
- {
- row.Cells[3].Value = "Заявка отклонена!";
- }
- else
- {
- row.Cells[3].Value = "Неизвестное состояние!";
- }
- row.Cells[4].Value = record["datetime"].ToString();
- row.Cells[5].Value = record["end_time"].ToString();
- row.Cells[6].Value = record["price"].ToString();
- allRequests_DataGrid.Rows.Add(row);
- }
- connection.Close();
- }
- }
- }
- //
- //
- // Код для просмотра всех сообщений
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- using System.IO;
- namespace DataBaseProject
- {
- public partial class MessagesCenter : Form
- {
- public MessagesCenter()
- {
- InitializeComponent();
- }
- private void btn_newMessage_Click(object sender, EventArgs e)
- {
- NewMessage newMessageForm = new NewMessage();
- newMessageForm.ShowDialog();
- }
- private void refresh()
- {
- allMessages_dataGrid.Rows.Clear();
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getMyMessages = new SQLiteCommand(String.Format("SELECT * FROM `messages` WHERE `user_to`='{0}' ORDER BY `id` DESC", StaticExp.sUserID), connection);
- SQLiteDataReader messages = getMyMessages.ExecuteReader();
- foreach (DbDataRecord record in messages)
- {
- DataGridViewRow row = (DataGridViewRow)allMessages_dataGrid.Rows[0].Clone();
- string username = "";
- if (record["user_from"].ToString() == "0")
- {
- username = "Администрация";
- }
- else
- {
- SQLiteCommand getUserInfo = new SQLiteCommand(String.Format("SELECT * FROM `users` WHERE `id`='{0}'", record["user_from"].ToString()), connection);
- SQLiteDataReader userInfo = getUserInfo.ExecuteReader();
- foreach (DbDataRecord info in userInfo)
- {
- username = info["fullname"].ToString();
- }
- }
- row.Cells[0].Value = record["id"].ToString();
- row.Cells[1].Value = username;
- row.Cells[2].Value = record["theme"].ToString();
- row.Cells[3].Value = record["datetime"].ToString();
- allMessages_dataGrid.Rows.Add(row);
- }
- connection.Close();
- }
- private void MessagesCenter_Load(object sender, EventArgs e)
- {
- refresh();
- }
- private void btn_readMessage_Click(object sender, EventArgs e)
- {
- try
- {
- // Для того, чтобы прочесть сообщение, необходимо сначала выбрать ID этого сообщения:
- string messageID = allMessages_dataGrid.CurrentRow.Cells[0].Value.ToString();
- // Теперь надо открыть форму и показать внутри этой формы полученное сообщение:
- messageFull messageFullForm = new messageFull();
- messageFullForm.loadMessage(messageID);
- }
- catch
- {
- MessageBox.Show("Пожалуйста, выберите сообщение!");
- }
- }
- // Действие происходит во время нажатия на кнопку "Удалить сообщение"
- private void btn_deleteMessage_Click(object sender, EventArgs e)
- {
- try
- {
- // Для того, чтобы удалить сообщение, необходимо сначала выбрать ID этого сообщения:
- string messageID = allMessages_dataGrid.CurrentRow.Cells[0].Value.ToString();
- // Теперь надо открыть сделать запрос к БД на удаление:
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand deleteMessage = new SQLiteCommand(String.Format("DELETE FROM `messages` WHERE `id`='{0}'", messageID), connection);
- deleteMessage.ExecuteNonQuery();
- refresh();
- connection.Close();
- }
- catch
- {
- MessageBox.Show("Пожалуйста, выберите сообщение!");
- }
- }
- }
- }
- //
- //
- // Код для просмотра и создания рейтинга
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Data.SQLite;
- namespace DataBaseProject
- {
- public partial class userSetRating : Form
- {
- public userSetRating()
- {
- InitializeComponent();
- }
- private void btn_sendRate_Click(object sender, EventArgs e)
- {
- string rate = "-1";
- if (radioButton1.Checked) rate = "1";
- if (radioButton2.Checked) rate = "2";
- if (radioButton3.Checked) rate = "3";
- if (radioButton4.Checked) rate = "4";
- if (radioButton5.Checked) rate = "5";
- if (rate == "-1")
- {
- MessageBox.Show("Перед тем, как оставить отзыв, необходимо поставить оценку!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- 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);
- setRate.ExecuteNonQuery();
- connection.Close();
- MessageBox.Show("Оценка поставлена! Спасибо!");
- refresh();
- }
- private void userSetRating_Load(object sender, EventArgs e)
- {
- refresh();
- }
- private void refresh()
- {
- allRatings_datagrid.Rows.Clear();
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getAllRates = new SQLiteCommand("SELECT * FROM `rating` ORDER BY `id` DESC", connection);
- SQLiteDataReader allRates = getAllRates.ExecuteReader();
- foreach (DbDataRecord record in allRates)
- {
- DataGridViewRow row = (DataGridViewRow)allRatings_datagrid.Rows[0].Clone();
- SQLiteCommand getUserFullName = new SQLiteCommand(String.Format("SELECT `fullname` FROM `users` WHERE `id`='{0}'", record["user_id"].ToString()), connection);
- SQLiteDataReader userFullName = getUserFullName.ExecuteReader();
- foreach (DbDataRecord user in userFullName)
- {
- row.Cells[0].Value = user["fullname"].ToString();
- }
- row.Cells[1].Value = record["rating"].ToString();
- row.Cells[2].Value = record["comment"].ToString();
- row.Cells[3].Value = record["datetime"].ToString();
- allRatings_datagrid.Rows.Add(row);
- }
- connection.Close();
- }
- }
- }
- //
- //
- // Код для просмотра и редактирования профиля пользователя
- //
- //
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Data.Common;
- using System.Data.SQLite;
- namespace DataBaseProject
- {
- public partial class userProfileForm : Form
- {
- public userProfileForm()
- {
- InitializeComponent();
- }
- private void btn_userChangePhoto_Click(object sender, EventArgs e)
- {
- if (openPictureFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- string pictureFilePath = openPictureFile.FileName;
- userPhoto.LoadAsync(pictureFilePath);
- }
- }
- private void btn_saveInfo_Click(object sender, EventArgs e)
- {
- // Проверяем заполненность полей:
- if (String.IsNullOrEmpty(userfullname_textBox.Text) || String.IsNullOrEmpty(userPhoneNumber_textBox.Text))
- {
- MessageBox.Show("Поля 'Ф.И.О' и 'Номер телефона' обязательны к заполнению!", "Ошибка приложения", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- // Начинаем сохранение данных:
- string base64StringOfImage = null;
- using (MemoryStream ms = new MemoryStream())
- {
- userPhoto.Image.Save(ms, userPhoto.Image.RawFormat);
- // Конвертируем байты в base64
- base64StringOfImage = Convert.ToBase64String(ms.ToArray());
- }
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- 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);
- updateRequest.ExecuteNonQuery();
- 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);
- updateMainRequest.ExecuteNonQuery();
- MessageBox.Show("Изменение данных прошло успешно!");
- connection.Close();
- }
- // Действие выполняется, когда открывается данное окошко(изменение профиля)
- private void userProfileForm_Load(object sender, EventArgs e)
- {
- SQLiteConnection connection = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/database.db");
- connection.Open();
- SQLiteCommand getAllInfo = new SQLiteCommand(String.Format("SELECT * FROM `user_additional` WHERE `id`='{0}'", StaticExp.sUserID), connection);
- SQLiteDataReader allInfo = getAllInfo.ExecuteReader();
- foreach (DbDataRecord record in allInfo)
- {
- if (!String.IsNullOrEmpty(record["photo"].ToString()))
- {
- byte[] imageBytes = Convert.FromBase64String(record["photo"].ToString());
- // Сначала получаем фотографию нашего пользователя:
- MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
- Image memImage = Image.FromStream(ms, true);
- userPhoto.Image = memImage;
- }
- // Теперь адрес пользователя:
- userAddress_TextBox.Text = record["address"].ToString();
- // Теперь e-mail пользователя:
- userEmail_textBox.Text = record["email"].ToString();
- // Теперь номер удостоверения личности:
- userPassport_textBox.Text = record["passport"].ToString();
- // Теперь ИИН:
- IIN_textBox.Text = record["IIN"].ToString();
- // Кем выдан:
- getBy_textBox.Text = record["getBy"].ToString();
- }
- SQLiteCommand getMainInfo = new SQLiteCommand(String.Format("SELECT * FROM `users` WHERE `id`='{0}'", StaticExp.sUserID), connection);
- SQLiteDataReader mainInfo = getMainInfo.ExecuteReader();
- foreach(DbDataRecord record in mainInfo)
- {
- userfullname_textBox.Text = record["fullname"].ToString();
- userBirthday_datepicker.Value = DateTime.Parse(record["birthday"].ToString());
- userPhoneNumber_textBox.Text = record["phone"].ToString();
- }
- connection.Close();
- }
- private void btn_changePassword_Click(object sender, EventArgs e)
- {
- ChangePassword changePassword = new ChangePassword();
- changePassword.ShowDialog();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement