Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Net;
- using System.Windows.Forms;
- using System.Text.RegularExpressions;
- using MySql.Data.MySqlClient;
- namespace Laba_6
- {
- public partial class Form1 : Form
- {
- public static int Count = 0;
- public Form1()
- {
- InitializeComponent();
- }
- public static string GetHtmlPage(string url) //Функция получения html кода
- страницы по ссылке
- {
- string HtmlText;
- Uri myUri = new Uri(url);
- HttpWebRequest myHttwebrequest = (HttpWebRequest)WebRequest.Create(myUri);
- HttpWebResponse myHttpWebresponse =
- (HttpWebResponse)myHttwebrequest.GetResponse();
- // ReSharper disable once AssignNullToNotNullAttribute
- StreamReader strm = new StreamReader(myHttpWebresponse.GetResponseStream());
- HtmlText = strm.ReadToEnd();
- return HtmlText;
- }
- private bool Get_News(string element) //Получает RSS ленту, обрабатывает ее и
- записывает в базу
- {
- string title;
- string link;
- string description;
- string date;
- string[] stitle = new[] { "<title>", "</title>" }; //разделители
- title = element.Split(stitle,
- StringSplitOptions.RemoveEmptyEntries)
- [1]; //записываем поле, как второй элемент массив разделенных строк (0 и
- 3 - пустые строки)
- string[] slink = new[] { "<link>", "</link>" }; //разделители
- link = element.Split(slink, StringSplitOptions.RemoveEmptyEntries)[1];
- string[] sdescription = new[] { "<description>", "</description>" };
- //разделители
- description = element.Split(sdescription,
- StringSplitOptions.RemoveEmptyEntries)[1];
- //использование регулярных выражений для отсеивания мусора
- string regex = "(<i)[^а-яА-Я]*(/>)";
- description = Regex.Replace(description, regex, String.Empty);
- regex = @"(![^а-яА-Я]*\[)";
- description = Regex.Replace(description, regex, String.Empty);
- regex = @"<?br>";
- description = Regex.Replace(description, regex, " ");
- regex = @"\s*<\s*[^а-яА-Я]+>?";
- description = Regex.Replace(description, regex, String.Empty);
- regex = @"\s*<\s*";
- description = Regex.Replace(description, regex, String.Empty);
- regex = @"\s*]]>\s*";
- description = Regex.Replace(description, regex, String.Empty);
- regex = "&[^а-яА-Я]*;";
- description = Regex.Replace(description, regex, String.Empty);
- string[] sdate = new[] { "<pubDate>", "</pubDate>" };
- date = element.Split(sdate, StringSplitOptions.RemoveEmptyEntries)[1];
- //запись в текстбокс
- richTextBox1.Text +=
- title + "\n" + date + "\n" + description + "\n" + link + "\n" + "\n";
- //вывод на экран
- label4.Text = "Попытка записи в БД...";
- //процесс записи в БД
- //строка подключения к БД
- string connStr =
- "server=localhost;user=root;database=people;password=password; CharSet=utf8";
- //создвем объект для подключения к БД
- MySqlConnection conn = new MySqlConnection(connStr);
- //устанавливаем соединение с БД
- try
- {
- conn.Open();
- }
- catch
- {
- label4.Text = "Не удалось подключиться к БД";
- return false;
- }
- string sql; //строка запросов
- MySqlCommand command;
- if (Count == 0) //если первый запуск, то надо удалить базу и обнулить
- автоинкремент
- {
- sql = "DELETE FROM rss WHERE 1";
- command = new MySqlCommand(sql, conn);
- command.ExecuteNonQuery();
- sql = "ALTER TABLE rss AUTO_INCREMENT=0";
- command = new MySqlCommand(sql, conn);
- command.ExecuteNonQuery();
- }
- //Вставка в БД
- sql = "INSERT INTO rss(name1, data1, ds, hl) VALUES('" + title + "', '" +
- date + "', '" + description + "', '" + link + "')";
- command = new MySqlCommand(sql, conn);
- command.ExecuteNonQuery();
- return true;
- }
- private void button1_Click(object sender, EventArgs e) //получить новости (в
- первый раз)
- {
- Count = 0; //считает вывод новостей (спасает от переполнения окна)
- richTextBox1.Text = String.Empty; //очистка окна
- label3.Text = "Выполняется запрос. Пожалуйста, подождите...";
- bool bd = true; //определяет, открыта ли бд
- bool ik = true; //определяет есть ли интернет соединение
- string rss = String.Empty; //содержит код страницы
- try
- {
- rss = GetHtmlPage(textBox1.Text); //берет код по ссылке
- }
- catch
- {
- richTextBox1.Text = String.Empty; //очистка окна
- label3.Text = "Отсутствует интернет подключение либо ссылка введена
- неверно";
- ik = false;
- }
- if (ik != true) return; //если нет интернета то стоп
- string[] snews = new[] { "<item>", "</item>" }; //разделители
- string[] news = rss.Split(snews, StringSplitOptions.RemoveEmptyEntries);
- //делит код страницы на отдельные новости
- foreach (string element in news) //перебираем все новости
- {
- //проверяет количество новостей
- try
- {
- if ((Count == Convert.ToInt32(textBox2.Text)) ||
- (Convert.ToInt32(textBox2.Text) == 0)) break;
- }
- catch
- {
- return;
- }
- //попытка получения новости
- try
- {
- bd = Get_News(element);
- }
- catch
- {
- continue;
- }
- Count++;
- }
- if (bd == true) label4.Text = "Запись в БД прошла успешно";
- label3.Text = "Новости получены успешно";
- }
- private void textBox2_KeyPress(object sender, KeyPressEventArgs e) //позволяет
- ограничить ввод только цифрами и Backspace
- {
- char number = e.KeyChar;
- if (!Char.IsDigit(number) && number != 8)
- {
- e.Handled = true;
- }
- }
- private void textBox3_KeyPress(object sender, KeyPressEventArgs e) //позволяет
- ограничить ввод только цифрами и Backspace
- {
- char number = e.KeyChar;
- if (!Char.IsDigit(number) && number != 8)
- {
- e.Handled = true;
- }
- }
- private void button2_Click(object sender, EventArgs e) //получить больше новостей
- {
- int k = 0; //счетчик новостей от текущей новости
- richTextBox1.Text = String.Empty; //очистка окна
- label3.Text = "Выполняется запрос. Пожалуйста, подождите...";
- bool bd = true; //определяет, открыта ли бд
- bool ik = true; //определяет есть ли интернет соединение
- string rss = String.Empty; //содержит код страницы
- try
- {
- rss = GetHtmlPage(textBox1.Text); //берет код по ссылке
- }
- catch
- {
- richTextBox1.Text = String.Empty; //очистка окна
- label3.Text = "Отсутствует интернет подключение либо ссылка введена
- неверно";
- ik = false;
- }
- if (ik != true) return; //если нет интернета то стоп
- string[] snews = new[] { "<item>", "</item>" }; //разделители
- string[] news = rss.Split(snews, StringSplitOptions.RemoveEmptyEntries);
- //делит код страницы на отдельные новости
- foreach (string element in news) //перебираем все новости
- {
- //проверяет количество новостей
- try
- {
- if ((k == Count + Convert.ToInt32(textBox3.Text)) ||
- (Convert.ToInt32(textBox3.Text) == 0)) break; //спасает от переполнения
- }
- catch
- {
- return;
- }
- //пропуск уже показанных новостей
- if (k < Count)
- {
- k++;
- continue;
- }
- //попытка получения новости
- try
- {
- bd = Get_News(element);
- }
- catch
- {
- continue;
- }
- k++;
- }
- if (bd == true) label4.Text = "Запись в БД прошла успешно";
- label3.Text = "Новости получены успешно";
- Count += k; //увеличивает count для повторного использования кнопки
- }
- private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
- //позволяет открывать ссылки из текстбокса
- {
- System.Diagnostics.Process.Start(e.LinkText);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement