.NET 4.x Необходимо Ваше мнение - C#
Формулировка задачи:
Здравствуйте. На данный момент изучаю C# и параллельно пишу для себя небольшую программу.
Хотелось бы узнать ваше мнение касаемо говнокодства в моем исполнении. Готов выслушать всю критику.
Структура - проект состоит из двух компонентов.
Первый - форма на которой пока есть прогресс бар и кнопка, данная форма будет использоваться в основном для визуализации.
Второй - библиотека dll, в которой я пишу функции и разместил все переменные.
Соответственно библиотека подключена к форме и я вызываю функции из нее.
Вот собственно код библиотеки:
А вот код формы:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using HtmlAgilityPack;
using hap = HtmlAgilityPack;
using System.Text.RegularExpressions;
namespace fmbt
{
public class functions
{
public static string d { get; set; }
public static string html { get; set; }
public static string auth { get; set; }
public static string lang { get; set; }
public static string remember { get; set; }
public static string[] sceneimages = new string[12];
public static string[] sceneimagesname = new string[12];
public static string scenevideourl { get; set; }
//
public static void prequest(string url)
{
byte[] buffer = Encoding.UTF8.GetBytes("act=login&id=&username=Rotblonder&password=Rotblond&remember_me=on&x=162&y=15");
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
CookieContainer cookies = new CookieContainer();
WebReq.CookieContainer = cookies;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
string html = new StreamReader(WebResp.GetResponseStream(), Encoding.UTF8).ReadToEnd();
WebResp.Close();
foreach (Cookie c in cookies.GetCookies(WebReq.RequestUri))
{
switch (c.Name)
{
case "auth":
auth = c.Value;
break;
case "lang":
lang = c.Value;
break;
case "remember_me":
remember = c.Value;
break;
}
Console.WriteLine(c.Name + "--->" + c.Value);
}
}
public static void grequest(string url, bool type) //true - page with sites in refer; false - main page of site in refer
{
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.UserAgent = "Mozilla/5.0 (PLAYSTATION 3; 3.55)";
webRequest.Accept = "*/*";
webRequest.Method = "GET";
if (type == true)
{
webRequest.Referer = "http://smtng.com/?auth=" + auth;
}
else
{
webRequest.Referer = "http://smtng.com/i/?auth=" + auth;
}
var response = webRequest.GetResponse().GetResponseStream();
html = new StreamReader(response, Encoding.UTF8).ReadToEnd();
}
public static void getlinks()
{
grequest("http://smtng.com/?auth=" + auth, true);
hap.HtmlDocument doc = new hap.HtmlDocument();
doc.LoadHtml(html);
HtmlNode thislink = doc.DocumentNode.SelectSingleNode("//div[@class='updatebuttons']/a[2]");
//Console.WriteLine(thislink.Attributes["href"].Value);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//div[@id='vids']/div/a"))
{
//Match id = Regex.Match(link.Attributes["href"].Value, @"\*/[0-9]+/*");
//membersimagesrc[i++] = link.Attributes["src"].Value;
Console.WriteLine(link.Attributes["href"].Value);
//i++;
}
}
public static void singlepage(int id)
{
grequest("http://smtng.com/10229?&auth=" + auth, false);
hap.HtmlDocument doc = new hap.HtmlDocument();
doc.LoadHtml(html);
HtmlNode videourl = doc.DocumentNode.SelectSingleNode("//div[@id='moviehd']/a[@id='media']");
scenevideourl = videourl.Attributes["href"].Value;
int i = 0;
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//div[@class='thumbs']/a"))
{
Match n = Regex.Match(link.Attributes["href"].Value, @"faces/(?<name>[a-z0-9.]+)");
sceneimages[i] = link.Attributes["href"].Value;
sceneimagesname[i] = n.Groups["name"].ToString();
//Console.WriteLine(link.Attributes["href"].Value);
i++;
}
}
}
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using fmbt;
using System.IO;
using System.Net;
namespace mbt
{
public partial class index : Form
{
public index()
{
InitializeComponent();
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
}
public string path { get; set; }
public WebClient clientTest2;
private void index_Load(object sender, EventArgs e)
{
fmbt.functions.prequest("http://smtng.com/login/");
fmbt.functions.singlepage(10229);
homepathdialog.Description = "Укажите папку для загрузок";
DialogResult homepath = homepathdialog.ShowDialog();
if (homepath == DialogResult.OK)
{
string homefolderpath = homepathdialog.SelectedPath;
path = homefolderpath + "\\test";
if (Directory.Exists(path))
{
return;
}
else
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
fmbt.functions.getlinks();
//fmbt.functions.singlepage(10229);
}
else
{
this.Close();
}
}
static void OnProcessExit(object sender, EventArgs e)
{
fmbt.functions.grequest("http://smtng.com/logout/?auth=" + fmbt.functions.auth, true);
}
private void button1_Click(object sender, EventArgs e)
{
clientTest2 = new WebClient();
clientTest2.DownloadFileCompleted += new AsyncCompletedEventHandler(clientTest_DownloadFileCompleted);
clientTest2.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientTest_DownloadProgressChanged);
clientTest2.DownloadFileAsync(new Uri(fmbt.functions.scenevideourl), path + "\\abc.mp4");//public версия
}
private void clientTest_DownloadFileCompleted(object ad, AsyncCompletedEventArgs e)
{
MessageBox.Show("Скачивание завершено!");
}
private void clientTest_DownloadProgressChanged(object obj, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Загружено: {0} Кбайт из {1}", e.BytesReceived.ToString(), e.TotalBytesToReceive.ToString());
}
}
}Решение задачи: «.NET 4.x Необходимо Ваше мнение»
textual
Листинг программы
/// <summary> /// /// </summary>