Advertisement
Guest User

Untitled

a guest
Mar 25th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.68 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.IO;
  6. using System.Drawing;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using System.Data.SqlClient;
  10. using MySql.Data.MySqlClient;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using System.Windows.Forms;
  14.  
  15.  
  16. namespace БД_Мессенджера
  17. {
  18.    
  19.     public partial class admin_form : Form
  20.     {
  21.         public admin_form()
  22.         {
  23.             InitializeComponent();
  24.         }
  25.        
  26.         private void admin_form_Load(object sender, EventArgs e)
  27.         {
  28.             ConnectionWork.AddConnectionString("Server = localhost; database = messenger; UID = admin; password = randomlycreatedpassword; Integrated Security = True");
  29.             ConnectionWork.AddConnectionString("Server = localhost; database = messenger; UID = manager; password = randomlygivenpasswordformanager; Integrated Security = True");
  30.             ConnectionWork.AddConnectionString("Server = localhost; database = messenger; UID = user; password = randomlygivenpasswordforuser; Integrated Security = True");
  31.                 ConnectionWork.SetConnection(2);
  32.  
  33.             SqlWorker _SqlWorker = new SqlWorker();
  34.             try
  35.             {
  36.                 _SqlWorker.Work("Connect", "Проверка работоспособности с MySQL сервером прошла успешно...");
  37.             }
  38.             catch
  39.             {
  40.                 Debug.LoadLogSrting("При проверке соединения к серверу возникли проблеммы!");
  41.             }
  42.  
  43.             //_SqlWorker.Work("Connect", "Идёт подключение к SQLServer. Пожалуйста подождите...");
  44.             _SqlWorker.Work("FillTable", "Идёт заполнение таблицы из базы данных praktika");
  45.         }
  46.  
  47.        
  48.        
  49.             static class Debug
  50.         {
  51.             private static string NameLog = "Нет никаких процессов...";
  52.             public static string Log(string s = "")
  53.             {
  54.                 s = NameLog;
  55.                 return s;
  56.             }
  57.             public static void LoadLogSrting(string s)
  58.             {
  59.                 NameLog = s;
  60.                 using (var writer = new StreamWriter("LogFile.txt", true))
  61.                 {
  62.                     writer.WriteLine(s + "   (" + DateTime.Now.ToString("День: dd MMMM yyyy |Час: HH:mm:ss") + ")");
  63.                 }
  64.             }
  65.             public static string Blocket(string s = "Эта функция на данный момент заблокирована!")
  66.             {
  67.                 return s;
  68.             }
  69.             public static void OpenLog()
  70.             {
  71.                 Process.Start("LogFile.txt");
  72.             }
  73.         }
  74.      
  75.         class SqlConnector: admin_form
  76.             {
  77.  
  78.             protected string connectionString = ConnectionWork.CurrentConnection;
  79.             //protected string connectionString = "Server=localhost; database=messenger; UID=admin; password=randomlycreatedpassword; Integrated Security=True";
  80.             DataSet ds = new DataSet();
  81.                 SqlDataAdapter adapter = new SqlDataAdapter();
  82.                 DataTable dataTable = new DataTable();
  83.                 MySqlConnection conn;
  84.                 MySqlCommand cmd;
  85.                 MySqlDataAdapter adptr;
  86.                 protected void Connection(string s)
  87.                 {
  88.                     try
  89.                     {
  90.                     if (admin == true)
  91.                     {
  92.                         manager = false;
  93.                         user = false;
  94.                         string connectionString = "Server=localhost; database=messenger; UID=admin; password=randomlycreatedpassword; Integrated Security=True";
  95.                     }
  96.                     if (manager == true)
  97.                     {
  98.                         admin = false;
  99.                         user = false;
  100.                         string connectionString = "Server=localhost; database=messenger; UID=manager; password=randomlygivenpasswordformanager; Integrated Security=True";
  101.                     }
  102.                     if (user == true)
  103.                     {
  104.                         manager = false;
  105.                         admin = false;
  106.                         string connectionString = "Server=localhost; database=messenger; UID=user; password=randomlygivenpasswordforuser; Integrated Security=True";
  107.  
  108.                     }
  109.                     conn = new MySqlConnection(connectionString);
  110.                         cmd = new MySqlCommand();
  111.                         cmd.Connection = conn;
  112.                         cmd.CommandText = s;
  113.  
  114.                         Debug.LoadLogSrting("Идёт заполнение Адаптера...");
  115.                         adptr = new MySqlDataAdapter(cmd);
  116.                         adptr.Fill(ds);
  117.  
  118.                         Debug.LoadLogSrting("Подключение к MySQL серверу прошло успешно...");
  119.                         adptr.Fill(dataTable);
  120.                     }
  121.                     catch (MySqlException ex)
  122.                     {
  123.                         Debug.LoadLogSrting("Подключение к MySQL серверу провалилось :(");
  124.                         MessageBox.Show(ex.Message);
  125.                     }
  126.                 }
  127.                 protected void delete()
  128.                 {
  129.                 string s;
  130.                 string connectionString = "Server=localhost; database=messenger; UID=admin; password=randomlycreatedpassword; Integrated Security=True";
  131.                 conn = new MySqlConnection(connectionString);
  132.                 s = (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentCell.Value.ToString();
  133.                 MySqlCommand cmd = new MySqlCommand();
  134.                 cmd.Connection = conn;
  135.                 conn.Open();
  136.                 cmd.CommandText = "delete from user_table where id= " + s;
  137.                 cmd.ExecuteNonQuery();
  138.                 conn.Close();
  139.             }
  140.                 protected void update()
  141.                 {
  142.  
  143.                 }
  144.  
  145.                 protected void create()
  146.             {
  147.                 try
  148.                 {if (admin)
  149.                     {
  150.                         manager = false;
  151.                         user = false;
  152.                         ConnectionWork.SetConnection(0);
  153.                     }
  154.                 if (manager == true)
  155.                     {
  156.                         admin = false;
  157.                         user = false;
  158.                         ConnectionWork.SetConnection(1);
  159.                     }
  160.                 if (user ==true)
  161.                     {
  162.                         manager = false;
  163.                         admin = false;
  164.                         ConnectionWork.SetConnection(2);
  165.                     }
  166.                     conn = new MySqlConnection(connectionString);
  167.                     MySqlCommand cmd = new MySqlCommand();
  168.                     cmd.Connection = conn;
  169.                     conn.Open();
  170.  
  171.                     cmd.CommandText = "insert into `messenger`.`user_table`(id,name,surname,age,about,position,password) values(" +
  172.                 (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["id"].Value + ",'" + (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["name"].Value + "','" +
  173.                 (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["surname"].Value + "'" + ",'" + (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["age"].Value +
  174.                  "','" + (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["about"].Value + "','" + (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["position"].Value + "','" +
  175.                  (Application.OpenForms[0] as admin_form).bunifuCustomDataGrid2.CurrentRow.Cells["password"].Value + "');";
  176.                     cmd.ExecuteNonQuery();
  177.                 }
  178.                 catch(MySqlException ex) { MessageBox.Show("У Вас нет необходимых прав доступа","Ошибка",MessageBoxButtons.OK, MessageBoxIcon.Error); }
  179.                
  180.                 conn.Close();
  181.  
  182.             }
  183.                 protected virtual void FillT()
  184.                 {
  185.                     int a = Application.OpenForms.Count - 1;
  186.  
  187.                     try
  188.                     {
  189.                         (Application.OpenForms[a] as admin_form).bunifuCustomDataGrid2.DataSource = ds.Tables[0];
  190.                         Debug.LoadLogSrting("Таблица была успешно заполнена.");
  191.                     }
  192.                     catch
  193.                     {
  194.                         Debug.LoadLogSrting("Заполнение таблицы провалилось...");
  195.                         MessageBox.Show("Ошибка, заполнение таблицы прерванно!");
  196.                     }
  197.                 }
  198.                 protected void Disconnect()
  199.                 {
  200.                     try
  201.                     {
  202.                         conn.Close();
  203.                         Debug.LoadLogSrting("Закрытие соединения с MySQL сервером прошло успешно...");
  204.                     }
  205.                     catch
  206.                     {
  207.                         Debug.LoadLogSrting("Закрытие соединения с MySQL провалилось...");
  208.                         MessageBox.Show("При закрытии соединения с сервером произошла ошибка, возможно какойто процесс остался не завершённым");
  209.                     }
  210.                 }
  211.  
  212.             }
  213.             class SqlWorker : SqlConnector
  214.             {
  215.  
  216.                 public void Work(string element, string log, string s = "SELECT * FROM messenger.user_table;")
  217.                 {
  218.                     switch (element)
  219.                     {
  220.                         case "Connect":
  221.                             Debug.LoadLogSrting(log);
  222.                             Connection(s);
  223.                             break;
  224.                         case "Disconnect":
  225.                             Debug.LoadLogSrting(log);
  226.                             Disconnect();
  227.                             break;
  228.                         case "delete":
  229.                             delete();
  230.                             break;
  231.                         case "FillTable":
  232.                             Debug.LoadLogSrting(log);
  233.                             FillT();
  234.                             break;
  235.                         case "update":
  236.                             update();
  237.                             break;
  238.                         case "create":
  239.                             create();
  240.                             break;
  241.                         default:
  242.                             Debug.LoadLogSrting("Ошибка, Класс SqlWorker не может работать с таким элементом :(");
  243.                             MessageBox.Show("Мастер подключения приостановлен \"" + element + "\" не является обрабатываемым элементом мастера!");
  244.                             break;
  245.  
  246.                     }
  247.                 }
  248.  
  249.                 private void button1_Click(object sender, EventArgs e)
  250.                 {
  251.                     string connectionString = "Server=localhost; database=messenger; UID=admin; password=randomlycreatedpassword; Integrated Security=True";
  252.                 SqlConnector sql1 = new SqlConnector();
  253.                     MySqlConnection connect = new MySqlConnection(connectionString);
  254.                     string s = "SELECT * FROM messenger.user_info;";
  255.                     MySqlCommand com = new MySqlCommand(s, connect);
  256.                     DataSet ds = new DataSet();
  257.                 }
  258.             }
  259.  
  260.         private void button2_Click(object sender, EventArgs e)
  261.         {
  262.             this.timer1.Start();
  263.             SqlWorker _SqlWorker1 = new SqlWorker();
  264.             _SqlWorker1.Work("Connect", "Идёт подключение к SQLServer. Пожалуйста подождите...", "SELECT * FROM messenger.user_message;");
  265.             _SqlWorker1.Work("FillTable", "Идёт заполнение таблицы из базы данных praktika");
  266.          
  267.         }
  268.  
  269.         private void timer1_Tick(object sender, EventArgs e)
  270.         {
  271.             if (bunifuProgressBar1.Value == 750)
  272.             {
  273.                 timer1.Stop();
  274.                 bunifuProgressBar1.Value = -250;
  275.             }
  276.             bunifuProgressBar1.Value += 250;
  277.            
  278.         }
  279.  
  280.         private void button3_Click(object sender, EventArgs e)
  281.         {
  282.             SqlWorker _SqlWorker1 = new SqlWorker();
  283.             _SqlWorker1.Work("create", "");
  284.         }
  285.  
  286.         private void button4_Click(object sender, EventArgs e)
  287.         {
  288.             SqlWorker _SqlWorker1 = new SqlWorker();
  289.             _SqlWorker1.Work("delete", "");
  290.  
  291.         }
  292.        public bool admin;
  293.        public bool manager;
  294.        public bool user=true;
  295.         private void авторизацияToolStripMenuItem_Click(object sender, EventArgs e)
  296.         {  
  297.             Authorization form = new Authorization();
  298.             form.ShowDialog();
  299.          
  300.         }
  301.  
  302.         private void выходToolStripMenuItem_Click(object sender, EventArgs e)
  303.         {
  304.             Application.Exit();
  305.         }
  306.  
  307.         private void button6_Click(object sender, EventArgs e)
  308.         {
  309.             SqlWorker _sqlworker = new SqlWorker();
  310.             _sqlworker.Work("Connect", "Заполнение таблицой user_table", "select * from messenger.user_table");
  311.             _sqlworker.Work("FillTable", " ");
  312.         }
  313.  
  314.         private void button7_Click(object sender, EventArgs e)
  315.         {
  316.             SqlWorker _sqlworker = new SqlWorker();
  317.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.status");
  318.             _sqlworker.Work("FillTable", " ");
  319.         }
  320.  
  321.         private void button10_Click(object sender, EventArgs e)
  322.         {
  323.             SqlWorker _sqlworker = new SqlWorker();
  324.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.reports");
  325.             _sqlworker.Work("FillTable", " ");
  326.         }
  327.  
  328.         private void button9_Click(object sender, EventArgs e)
  329.         {
  330.             SqlWorker _sqlworker = new SqlWorker();
  331.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.participants");
  332.             _sqlworker.Work("FillTable", " ");
  333.         }
  334.  
  335.         private void button8_Click(object sender, EventArgs e)
  336.         {
  337.             SqlWorker _sqlworker = new SqlWorker();
  338.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.messages");
  339.             _sqlworker.Work("FillTable", " ");
  340.         }
  341.  
  342.         private void button13_Click(object sender, EventArgs e)
  343.         {
  344.             SqlWorker _sqlworker = new SqlWorker();
  345.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.contact_inf");
  346.             _sqlworker.Work("FillTable", " ");
  347.         }
  348.  
  349.         private void button12_Click(object sender, EventArgs e)
  350.         {
  351.             SqlWorker _sqlworker = new SqlWorker();
  352.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.chats");
  353.             _sqlworker.Work("FillTable", " ");
  354.         }
  355.  
  356.         private void button11_Click(object sender, EventArgs e)
  357.         {
  358.             SqlWorker _sqlworker = new SqlWorker();
  359.             _sqlworker.Work("Connect", "Заполнение таблицой status", "select * from messenger.black_list");
  360.             _sqlworker.Work("FillTable", " ");
  361.         }
  362.     }
  363.     }
  364.     public static class ConnectionWork
  365.     {
  366.         static string _currentconnection;
  367.         private static List<string> Connection = new List<string>();
  368.  
  369.         public static void AddConnectionString(string _connection)
  370.         {
  371.             Connection.Add(_connection);
  372.         }
  373.  
  374.         public static void SetConnection(int index)
  375.         {
  376.             CurrentConnection = Connection[index];
  377.         }
  378.         public static string CurrentConnection
  379.         {
  380.             get
  381.             {
  382.                 return _currentconnection;
  383.             }
  384.             set
  385.             {
  386.                 _currentconnection = value;
  387.             }
  388.         }
  389.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement