Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.71 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Xml;
  11. using System.IO;
  12. using Word = Microsoft.Office.Interop.Word;
  13. using System.Runtime.InteropServices.ComTypes;
  14. using System.Reflection;
  15. using System.Data.SQLite;
  16. // !!! НАЗВАНИЕ документа должно совпадать с названием вершины и с названием столбцы в бд name_srs.
  17. // !!! Для того, чтобы лаб.работы открылась нужно чтобы в названии вершины дерева содержалось "Лаб"
  18. namespace Programm
  19. {
  20.  
  21.     public partial class TV : Form
  22.     {
  23.         SQLiteConnection sCon;
  24.         public string name_srs = ""; //нужен для того, чтобы при переходе между срс варианты не менялись
  25.  
  26.         MainWindow _MainWindowForm; //для кнопки назад
  27.  
  28.         public TV(MainWindow MainWindowForm)
  29.         {
  30.             InitializeComponent();
  31.             StartConnection();
  32.             TreeNodeMouseClickEventArgs e = null;
  33.  
  34.             _MainWindowForm = MainWindowForm; //для кнопки назад
  35.  
  36.             string fileName = "example.xml";
  37.             //XmlTextReader reader = new XmlTextReader(fileName);
  38.             Add(sender,"example.xml",e);
  39.            
  40.         }
  41.  
  42.         private bool StartConnection() //Подключение к БД
  43.         {
  44.             String StringConnection = @"Data Source = DataBase.sqlite;Version=3;";
  45.             sCon = new SQLiteConnection(StringConnection);
  46.             try
  47.             {
  48.                 sCon.Open();
  49.                 return true;
  50.             }
  51.             catch
  52.             {
  53.                 MessageBox.Show("Not opened");
  54.                 return false;
  55.             }
  56.         }
  57.  
  58.         public void Add(object sender, String fileName, EventArgs e)
  59.         {
  60.             ClassesTreeView.Nodes.Clear(); //почистили treeview чтобы открыть другой
  61.  
  62.             XmlTextReader reader = new XmlTextReader(fileName);
  63.  
  64.             try
  65.             {
  66.                 ClassesTreeView.BeginUpdate();
  67.                 TreeNode parentNode = null;
  68.  
  69.                 while (reader.Read()) //пока идет считывание
  70.                 {
  71.                     if (reader.NodeType == XmlNodeType.Element)
  72.                     {
  73.                         if (reader.Name == "Вершина")
  74.                         {
  75.                             TreeNode newNode = new TreeNode();
  76.                             bool isEmptyElement = reader.IsEmptyElement;
  77.                             int attributeCount = reader.AttributeCount;
  78.                             if (attributeCount > 0)
  79.                             {
  80.                                 for (int i = 0; i < attributeCount; i++)
  81.                                 {
  82.                                     if (i == 0)
  83.                                     {
  84.                                         reader.MoveToAttribute(i);
  85.                                         newNode.Text = reader.Value;
  86.                                     }
  87.                                     else
  88.                                     {
  89.                                         reader.MoveToAttribute(i);
  90.                                         newNode.Tag = reader.Value;
  91.                                     }
  92.  
  93.                                 }
  94.                             }
  95.                             // add new node to Parent Node or TreeView
  96.                             if (parentNode != null) parentNode.Nodes.Add(newNode);
  97.                             else ClassesTreeView.Nodes.Add(newNode);
  98.  
  99.                             // making current node 'ParentNode' if its not empty
  100.                             if (!isEmptyElement)
  101.                             {
  102.                                 parentNode = newNode;
  103.                             }
  104.                         }
  105.    
  106.                     }
  107.  
  108.                     else if (reader.NodeType == XmlNodeType.EndElement)
  109.                     {
  110.                         if (reader.Name == "Вершина")
  111.                         {
  112.                             parentNode = parentNode.Parent;
  113.                         }
  114.                     }
  115.  
  116.  
  117.                     else if (reader.NodeType == XmlNodeType.XmlDeclaration)
  118.                     {
  119.                         //Ignore Xml Declaration                    
  120.                     }
  121.                     else if (reader.NodeType == XmlNodeType.None)
  122.                     {
  123.                         return;
  124.                     }
  125.                     else if (reader.NodeType == XmlNodeType.Text)
  126.                     {
  127.                         parentNode.Nodes.Add(reader.Value);
  128.                     }
  129.  
  130.                     // moving up to in TreeView if end tag is encountered
  131.  
  132.                 }
  133.             }
  134.             finally
  135.             {
  136.                 // enabling redrawing of treeview after all nodes are added
  137.                 ClassesTreeView.EndUpdate();
  138.                 reader.Close();
  139.             }
  140.         }
  141.  
  142.         public void ClassesTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) // открытие ворда по нажатию на узел
  143.         {
  144.             TV_Word word_text = new TV_Word();
  145.             TheoryText.Text = word_text.ShowWord(e.Node.Text); //возращает totaltext, где хранится весь текст ворда
  146.             GetData(e);
  147.         }
  148.  
  149.         public void GetData(TreeNodeMouseClickEventArgs e) //выводим данные из БД
  150.         {
  151.             string srs;
  152.             try
  153.             {
  154.                 srs = e.Node.Text; // запоминаем узел, который щелкнули
  155.             }
  156.             catch
  157.             {
  158.                 MessageBox.Show("Кажется что-то пошло не так...");
  159.                 return;
  160.             }
  161.             if (srs.IndexOf("Лаб") != -1) //Если есть фраза "Лаб", то обращаемся к БД
  162.             {
  163.                
  164.                 // считаем количество вариантов, которые относятся в выбранной Срс
  165.                 string queryCount = @"select count(var) from CRC where name_srs= @name_srs_list";
  166.                 SQLiteCommand commandCount = new SQLiteCommand(queryCount, sCon);
  167.                 commandCount.Parameters.Add(new SQLiteParameter("@name_srs_list", srs));
  168.                 int Count = Convert.ToInt32(commandCount.ExecuteScalar());
  169.                 int x;
  170.                 if (Count != 0)
  171.                 {
  172.                     Random rand = new Random();
  173.                     int RandomCount = rand.Next(1, Count + 1); //выбираем случайный варинт для данной срс
  174.                     // Выводим  случайны вариант, выбранной срс на экран
  175.                     string query = @"select text_srs FROM CRC WHERE name_srs= @name_srs_list and var=@number_var";
  176.                     SQLiteCommand command = new SQLiteCommand(query, sCon);
  177.  
  178.                     command.Parameters.Add(new SQLiteParameter("@name_srs_list", srs));
  179.                     command.Parameters.Add(new SQLiteParameter("@number_var", RandomCount));
  180.                     SQLiteDataReader reader = command.ExecuteReader();
  181.                     //Считываем лабу из БД
  182.                     if (LabText.Text == "")
  183.                     {
  184.                         name_srs = srs;
  185.  
  186.                         while (reader.Read())
  187.                         {
  188.                             LabText.Text += reader["text_srs"] + "\n";
  189.                         }
  190.                     }
  191.                     //Пересчитываем, только если название лабы сменилось.
  192.                     if (name_srs != srs)
  193.                     {
  194.                         name_srs = srs;
  195.                         LabText.Clear();
  196.                         while (reader.Read())
  197.                         {
  198.                             LabText.Text += reader["text_srs"] + "\n";
  199.                         }
  200.                     }
  201.                 }
  202.             }
  203.            
  204.         }
  205.  
  206.         private void btnOpen_Click(object sender, EventArgs e)//выбор XML
  207.         {
  208.             if (openFileDialog1.ShowDialog() == DialogResult.OK)
  209.             {
  210.                 Add(sender, openFileDialog1.FileName, e);
  211.             }
  212.         }
  213.  
  214.        private void btnClose_Click(object sender, EventArgs e)//кнопка назад
  215.         {
  216.             //this.Hide();
  217.             //_MainWindowForm.Show();
  218.         }
  219.  
  220.         private void LoadSolution_Click(object sender, EventArgs e)
  221.         {
  222.             MessageBox.Show("Coming soon", "Oooops", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  223.         }
  224.  
  225.         private void button1_Click(object sender, EventArgs e)
  226.         {
  227.             MessageBox.Show("Coming soon", "Oooops", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  228.         }
  229.  
  230.         private void tabs_Selecting(object sender, TabControlCancelEventArgs e)
  231.         {
  232.             int temp_tab = tabs.SelectedIndex;
  233.             // НАДО СДЕЛАТЬ В названии срс ОБЯЗАТЕЛЬНО должна содержаться фраза "Лаб" столбец name_srs, иначе к БД программа не будет обращаться
  234.            
  235.             if (tabs.SelectedIndex == 2) //тест
  236.             {
  237.                 //уведомление о переходе
  238.                 const string message = "Вы уверены, что хотете перейти к тесту? Теория будет недоступна";
  239.                 const string caption = "Error Detected in Input";
  240.                 var result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  241.                 if (result == DialogResult.No) e.Cancel=true;
  242.                 else
  243.                 {
  244.                     tabs.TabPages[0].Parent = null; //закрыли теорию
  245.                     tabs.TabPages[0].Parent = null; //закрыли лабу
  246.                    
  247.                 }
  248.             }
  249.         }
  250.  
  251.         private void pictureBox1_Click(object sender, EventArgs e)
  252.         {
  253.             this.Hide();
  254.             _MainWindowForm.Show();
  255.  
  256.         }
  257.  
  258.         private void btnCopy_Click(object sender, EventArgs e)
  259.         {
  260.             MessageBox.Show("Coming soon", "Oooops", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  261.         }
  262.  
  263.    
  264.  
  265.     }
  266. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement