Демонстрація інтерфейсу ПЗ (програмного забезпечення)
Розмір колонок та рядків також можна довільно змінювати; Функция парсинга указаных страниц по их url адресах. Функция парсинга одной страницы по ее url адресу. This. dgv_ExchangeRate.Columns.AddRange (new System.Windows.Forms.DataGridViewColumn {. StreamReader sr = new StreamReader (responce.GetResponseStream (), Encoding. Default); Считываем ответ и переводим его в string формат… Читать ещё >
Демонстрація інтерфейсу ПЗ (програмного забезпечення) (реферат, курсовая, диплом, контрольная)
Програма має небагато елементів, серед них:
- 1) Button btn_Parse, що викликає функцію парсингу
- 2) DataGridView dgv_ExchangeRate, я вку записуються дані щодо курсів валют
- 3) DataGridViewTextBoxColumn bankName — назва банку
- 4) DataGridViewTextBoxColumn usdBuy (колонка) — купівля долару
- 5) DataGridViewTextBoxColumn usdSale (колонка) — продаж долару
- 6) DataGridViewTextBoxColumn eurBuy (колонка) — купівля євро
- 7) DataGridViewTextBoxColumn eurSale (колонка) — продаж євро
- 8) DataGridViewTextBoxColumn rubBuy (колонка) — купівля рубля
- 9) DataGridViewTextBoxColumn rubSale (колонка) — продаж рубля
Мал.2 Вікно, заповнене даними
- 1)Для відображення даних потрібен прямий доступ до мережі Інтернет;
- 2)Розмір вікна програми можна змінювати;
- 3)Розмір колонок та рядків також можна довільно змінювати;
Програмний код
IParsingService.cs
using System;
using System.Collections.Generic;
using System. Linq;
using System.Runtime.Serialization;
using System. ServiceModel;
using System. Text;
namespace ParsingService.
{.
// NOTE: You can use the «Rename» command on the «Refactor» menu to change the interface name «IParsingService» in both code and config file together.
[ServiceContract].
public interface IParsingService.
{.
[OperationContract].
List ParseThePages (List urls);
}.
}.
ParsingService.cs
using System;
using System.Collections.Generic;
using System. Linq;
using System.Runtime.Serialization;
using System. ServiceModel;
using System. Text;
using HtmlAgilityPack;
using System.Net;
using System. IO;
namespace ParsingService.
{.
// NOTE: You can use the «Rename» command on the «Refactor» menu to change the class name «ParsingService» in both code and config file together.
public class ParsingService: IParsingService.
{.
//функция парсинга указаных страниц по их url адресах.
public List ParseThePages (List urls).
{.
List lstOfBanks = new List ();
foreach (var bankUrl in urls).
{.
lstOfBanks.Add (ParseTheCurrentPage (bankUrl));
}.
return lstOfBanks;
}.
//функция парсинга одной страницы по ее url адресу.
private static Bank ParseTheCurrentPage (string url).
{.
var html = GetHtml (url);
HtmlDocument doc = new HtmlDocument ();
doc.LoadHtml (html);
return GetBank (doc);
}.
//функция получения обьекта Банка по указаному HTML документу.
private static Bank GetBank (HtmlDocument doc).
{.
//информация о валюте в формате строки.
string info = «» ;
//информация о валюте ы формате масива строк.
string[] kursInfo = new string[7];
//получение нужной нам таблицы с HTML страницы.
var table = doc.DocumentNode.SelectNodes («//table»)[0];
//получаем имя банка.
info = doc.DocumentNode.SelectNodes («//title»)[0]. InnerText. Substring (11);
info = info. Replace (««, «;»);
//перебираем все валюты в таблице.
foreach (var tr_element in table. ChildNodes).
{.
if (tr_element.Name == «tr»).
{.
//Проверка на соответствие тега.
if (tr_element.ChildNodes[1]. Name == «td»).
{.
//добавляем инфомацмию о покупке валюты.
info += tr_element.ChildNodes[3]. FirstChild. InnerText + «;» ;
//добавляем инфомацмию о продаже валюты.
info += tr_element.ChildNodes[5]. FirstChild. InnerText + «;» ;
}.
}.
}.
//разбиваем строку с информацией о банке в масив строк для удобного создания обьекта Банка.
if (info ≠ «»).
kursInfo = info. Split (';');
//возращаем обьект Банка.
return new Bank ().
{.
Name = kursInfo[0],.
UsdBuy = kursInfo[1],.
UsdSale = kursInfo[2],.
EurBuy = kursInfo[3],.
EurSale = kursInfo[4],.
RubBuy = kursInfo[5],.
RubSale = kursInfo[6].
};
}.
//Функция для получения HTML страницы.
private static string GetHtml (string url).
{.
//Делаем запрос по указаному url.
HttpWebRequest request = HttpWebRequest. Create (url) as HttpWebRequest;
//Получаем ответ по запросу.
HttpWebResponse responce = request. GetResponse () as HttpWebResponse;
//Считываем ответ и переводим его в string формат.
StreamReader sr = new StreamReader (responce.GetResponseStream (), Encoding. Default);
var html = sr. ReadToEnd ();
sr.Close ();
return html;
}.
}.
}.
Bank.cs
using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
namespace ParsingService.
{.
public class Bank.
{.
public string Name { get; set; }.
public string UsdBuy { get; set; }.
public string UsdSale { get; set; }.
public string EurBuy { get; set; }.
public string EurSale { get; set; }.
public string RubBuy { get; set; }.
public string RubSale { get; set; }.
}.
}.
App.config
FormMain.cs
using System;
using System.Collections.Generic;
using System. ComponentModel;
using System. Data;
using System. Drawing;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ParserClient. ParserService;
namespace ParserClient.
{.
public partial class FormMain: Form.
{.
ParsingServiceClient _client;
private List _bankUrls = new List ().
{.
" http://finance.i.ua/bank/73/" ,.
" http://finance.i.ua/bank/29/" ,.
" http://finance.i.ua/bank/2/" ,.
" http://finance.i.ua/bank/79/" ,.
" http://finance.i.ua/bank/26/" ,.
" http://finance.i.ua/bank/9/" ,.
" http://finance.i.ua/bank/8/" ,.
" http://finance.i.ua/bank/4/" ,.
" http://finance.i.ua/bank/23/" ,.
" http://finance.i.ua/bank/13/" ,.
" http://finance.i.ua/bank/12/" ,.
" http://finance.i.ua/bank/30/" ,.
" http://finance.i.ua/bank/52/" .
};
public FormMain ().
{.
InitializeComponent ();
_client = new ParsingServiceClient («BasicHttpBinding_IParsingService»);
}.
private void btn_Parse_Click (object sender, EventArgs e).
{.
//парсим указаный масив url адресов и получаем масив банков. конвертировали в список.
List banks = _client.ParseThePages (_bankUrls.ToArray ()).ToList ();
//вычесляем количество строк таблицы.
dgv_ExchangeRate.RowCount = banks. Count;
//заполняем таблицу информацией о банках.
FillTheDataGridView (banks);
}.
private void FillTheDataGridView (List banks).
{.
for (int i = 0; i < dgv_ExchangeRate.RowCount; i++).
{.
dgv_ExchangeRate[0, i]. Value = banks[i]. Name;
dgv_ExchangeRate[1, i]. Value = banks[i]. UsdBuy;
dgv_ExchangeRate[2, i]. Value = banks[i]. UsdSale;
dgv_ExchangeRate[3, i]. Value = banks[i]. EurBuy;
dgv_ExchangeRate[4, i]. Value = banks[i]. EurSale;
dgv_ExchangeRate[5, i]. Value = banks[i]. RubBuy;
dgv_ExchangeRate[6, i]. Value = banks[i]. RubSale;
}.
}.
}.
}.
MyParsingService.cs
using System;
using System.Collections.Generic;
using System. ComponentModel;
using System. Data;
using System. Diagnostics;
using System. Linq;
using System. ServiceModel;
using System.ServiceModel.Description;
using System. ServiceProcess;
using System. Text;
using System.Threading.Tasks;
namespace WinParsingService.
{.
public partial class MyParsingService: ServiceBase.
{.
private ServiceHost _host = null;
public MyParsingService ().
{.
InitializeComponent ();
}.
protected override void OnStart (string[] args).
{.
if (_host ≠ null).
_host.Close ();
_host = new ServiceHost (typeof (ParsingService.ParsingService));
_host.Open ();
}.
protected override void OnStop ().
{.
if (_host ≠ null).
{.
_host.Close ();
_host = null;
}.
}.
}.
}.
MyParsingService.Designer.cs
namespace WinParsingService.
{.
partial class MyParsingService.
{.
/// Required designer variable.
private System.ComponentModel.IContainer components = null;
/// Clean up any resources being used.
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose (bool disposing).
{.
if (disposing && (components ≠ null)).
{.
components.Dispose ();
}.
base.Dispose (disposing);
}.
#region Component Designer generated code.
/// Required method for Designer support — do not modify.
/// the contents of this method with the code editor.
private void InitializeComponent ().
{.
components = new System.ComponentModel.Container ();
this.ServiceName = «ParsingService» ;
}.
#endregion.
}.
}.
namespace ParserClient.
{.
partial class FormMain.
{.
/// Required designer variable.
private System.ComponentModel.IContainer components = null;
/// Clean up any resources being used.
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose (bool disposing).
{.
if (disposing && (components ≠ null)).
{.
components.Dispose ();
}.
base.Dispose (disposing);
}.
#region Windows Form Designer generated code.
/// Required method for Designer support — do not modify.
/// the contents of this method with the code editor.
private void InitializeComponent ().
{.
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager (typeof (FormMain));
this.btn_Parse = new System.Windows.Forms.Button ();
this.dgv_ExchangeRate = new System.Windows.Forms.DataGridView ();
this.bankName = new System.Windows.Forms.DataGridViewTextBoxColumn ();
this.usdBuy = new System.Windows.Forms.DataGridViewTextBoxColumn ();
this.usdSale = new System.Windows.Forms.DataGridViewTextBoxColumn ();
this.eurBuy = new System.Windows.Forms.DataGridViewTextBoxColumn ();
this.eurSale = new System.Windows.Forms.DataGridViewTextBoxColumn ();
this.rubBuy = new System.Windows.Forms.DataGridViewTextBoxColumn ();
this.rubSale = new System.Windows.Forms.DataGridViewTextBoxColumn ();
((System.ComponentModel.ISupportInitialize)(this.dgv_ExchangeRate)).BeginInit ();
this.SuspendLayout ();
// btn_Parse.
this.btn_Parse.Location = new System.Drawing.Point (658, 12);
this.btn_Parse.Name = «btn_Parse» ;
this.btn_Parse.Size = new System.Drawing.Size (101, 36);
this.btn_Parse.TabIndex = 0;
this.btn_Parse.Text = «Вывести курсы валют» ;
this.btn_Parse.UseVisualStyleBackColor = true;
this.btn_Parse.Click += new System. EventHandler (this.btn_Parse_Click);
// dgv_ExchangeRate.
this.dgv_ExchangeRate.AllowUserToAddRows = false;
this.dgv_ExchangeRate.AllowUserToDeleteRows = false;
this.dgv_ExchangeRate.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgv_ExchangeRate.Columns.AddRange (new System.Windows.Forms.DataGridViewColumn[] {.
this.bankName,.
this.usdBuy,.
this.usdSale,.
this.eurBuy,.
this.eurSale,.
this.rubBuy,.
this.rubSale});
this.dgv_ExchangeRate.Location = new System.Drawing.Point (12, 12);
this.dgv_ExchangeRate.Name = «dgv_ExchangeRate» ;
this.dgv_ExchangeRate.ReadOnly = true;
this.dgv_ExchangeRate.RowHeadersVisible = false;
this.dgv_ExchangeRate.Size = new System.Drawing.Size (623, 322);
this.dgv_ExchangeRate.TabIndex = 1;
// bankName.
this.bankName.HeaderText = «Банк» ;
this.bankName.Name = «bankName» ;
this.bankName.ReadOnly = true;
this.bankName.Width = 200;
// usdBuy.
this.usdBuy.HeaderText = «USD Покупка» ;
this.usdBuy.Name = «usdBuy» ;
this.usdBuy.ReadOnly = true;
this.usdBuy.Width = 70;
// usdSale.
this.usdSale.HeaderText = «USD Продажа» ;
this.usdSale.Name = «usdSale» ;
this.usdSale.ReadOnly = true;
this.usdSale.Width = 70;
// eurBuy.
this.eurBuy.HeaderText = «EUR Покупка» ;
this.eurBuy.Name = «eurBuy» ;
this.eurBuy.ReadOnly = true;
this.eurBuy.Width = 70;
// eurSale.
this.eurSale.HeaderText = «EUR Продажа» ;
this.eurSale.Name = «eurSale» ;
this.eurSale.ReadOnly = true;
this.eurSale.Width = 70;
// rubBuy.
this.rubBuy.HeaderText = «RUB Покупка» ;
this.rubBuy.Name = «rubBuy» ;
this.rubBuy.ReadOnly = true;
this.rubBuy.Width = 70;
// rubSale.
this.rubSale.HeaderText = «RUB Продажа» ;
this.rubSale.Name = «rubSale» ;
this.rubSale.ReadOnly = true;
this.rubSale.Width = 70;
// FormMain.
this.AutoScaleDimensions = new System.Drawing.SizeF (6 °F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size (774, 362);
this.Controls.Add (this.dgv_ExchangeRate);
this.Controls.Add (this.btn_Parse);
this.Icon = ((System.Drawing.Icon)(resources.GetObject («$this.Icon»)));
this.MaximumSize = new System.Drawing.Size (790, 1000);
this.MinimumSize = new System.Drawing.Size (790, 400);
this.Name = «FormMain» ;
this.Text = «Курсы валют» ;
((System.ComponentModel.ISupportInitialize)(this.dgv_ExchangeRate)).EndInit ();
this.ResumeLayout (false);
}.
#endregion.
private System.Windows.Forms.Button btn_Parse;
private System.Windows.Forms.DataGridView dgv_ExchangeRate;
private System.Windows.Forms.DataGridViewTextBoxColumn bankName;
private System.Windows.Forms.DataGridViewTextBoxColumn usdBuy;
private System.Windows.Forms.DataGridViewTextBoxColumn usdSale;
private System.Windows.Forms.DataGridViewTextBoxColumn eurBuy;
private System.Windows.Forms.DataGridViewTextBoxColumn eurSale;
private System.Windows.Forms.DataGridViewTextBoxColumn rubBuy;
private System.Windows.Forms.DataGridViewTextBoxColumn rubSale;
}.
}.