Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
курсовая_Ткачук (1).docx
Скачиваний:
10
Добавлен:
30.04.2015
Размер:
216.84 Кб
Скачать

5. Демонстрація інтерфейсу пз (програмного забезпечення)

Мал.1 Робоче вікно програми

Програма має небагато елементів, серед них:

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)Розмір колонок та рядків також можна довільно змінювати;

6.Програмний код

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<Bank> ParseThePages(List<string> 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<Bank> ParseThePages(List<string> urls)

{

List<Bank> lstOfBanks = new List<Bank>();

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("&nbsp;", ";");

//перебираем все валюты в таблице

foreach (var tr_element in table.ChildNodes)

{

if (tr_element.Name == "tr")

{

//Проверка на соответствие тега <td>

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

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<startup>

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />

</startup>

<system.serviceModel>

<services>

<service name="ParsingService.ParsingService" behaviorConfiguration="mexBehavior">

<endpoint address="ParsingService" binding="basicHttpBinding" contract="ParsingService.IParsingService"></endpoint>

<endpoint address="ParsingService" binding="netTcpBinding" contract="ParsingService.IParsingService"></endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>

<host>

<baseAddresses>

<add baseAddress="http://localhost:9001/ParsingService"/>

<add baseAddress="net.tcp://localhost:9002/ParsingService"/>

</baseAddresses>

</host>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="mexBehavior">

<serviceMetadata httpGetEnabled="true"/>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

</configuration>

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<string> _bankUrls = new List<string>()

{

"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<Bank> banks = _client.ParseThePages(_bankUrls.ToArray<string>()).ToList<Bank>();

//вычесляем количество строк таблицы

dgv_ExchangeRate.RowCount = banks.Count;

//заполняем таблицу информацией о банках

FillTheDataGridView(banks);

}

private void FillTheDataGridView(List<Bank> 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

{

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.IContainer components = null;

/// <summary>

/// Clean up any resources being used.

/// </summary>

/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

protected override void Dispose(bool disposing)

{

if (disposing && (components != null))

{

components.Dispose();

}

base.Dispose(disposing);

}

#region Component Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

components = new System.ComponentModel.Container();

this.ServiceName = "ParsingService";

}

#endregion

}

}

namespace ParserClient

{

partial class FormMain

{

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.IContainer components = null;

/// <summary>

/// Clean up any resources being used.

/// </summary>

/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

protected override void Dispose(bool disposing)

{

if (disposing && (components != null))

{

components.Dispose();

}

base.Dispose(disposing);

}

#region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

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(6F, 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;

}

}