CЕТЕВОЕ ПРОГРАММИРОВАНИЕ
Теория по сетевому программированию
Средства Visual Studio для работы с сетевым программированием
Пространство имён System. Net содержит классы для поиска IP-адресов, сетевой аутентификации, разрешений, отправки и получения данных. Все эти классы представлены ниже.
Dns;
DnsPermission;
IpHostEntry;
AsyncResult;
Ipaddress.
Классы
DNS. Предназначен для получения IP-адреса из DNS-имени хоста или получения имени хоста из IP-адреса.
DnsPermission. Управляет правами доступа к DNS-серверам в сети.
IpHostEntry. Предоставляет класс контейнеров для сведений об адресе веб-узла.
AsyncResult. Инкапсулирует результаты асинхронной операции над делегатом.
Ipaddress. Предоставляет IP-адрес.
Выполненные задания по сетевому программированию
Базовый пример WebClient
Задание 1.
Данный пример демонстрирует применение метода WebClient.OpenRead(). Содержимое страницы, которую мы прописываем в коде программы, в данном случае www.vk.com, будет показано в элементе управления listBox.
В этом примере класс StreamReader из пространства имен System.IO подключается к сетевому потоку. Это позволяет получить данные из потока в виде текста, используя высокоуровневые методы вроде ReadLine().
Форма представлена на рисунке 3.1.
Рисунок 3.1 – Форма содержимого страницы
Листинг задания представлен в приложении 3.
Классы WebRequest и WebResponse
Задание 2
Класс WebRequest предоставляет запрос информации для отправки по определенному URL. Идентификатор URI передается в качестве параметра методу Create(). Класс WebResponse предоставляет данные , извлекаемые из сервера. Вызов метода WebRequest.GetResponse() на самом деле приводит к отправке запроса веб-серверу и к созданию объекта WebResponse для просмотра возвращенных данных. Как и в случае объекта WebClient, можно получить поток для представления данных, но для этого должен использоваться метод WebResponse.Get.ResponseStream().
В этом примере код начинается с создания экземпляра объекта, представляющего веб-запрос. Это делается с помощью конструктора, а вызовом статического метода WebRequest.Create().
Форма представлена на рисунке 3.2.
Рисунок 3.2 – Запрос информации и предоставление данных , извлекаемых из сервера
Листинг задания представлен в приложении 3.
WebBrowser
Задание 3
Приложение обеспечивает просмотр веб-страниц из формы. В поле справа при нажатии кнопки «Показать код страницы» выводится код данной веб-страницы. Кнопки «Обновить», «Печать», «Главная», соответственно, обновляют, печатают, переходят на главную страницу.
Консоль представлена на рисунке 3.3.
Рисунок 3.3 – Просмотр веб-страниц из формы.
Листинг задания представлен в приложении 3.
IP-адрес
Задание 4
Приложение работает следующим образом, вводим имя какого-либо хоста и нажимаем кнопку «Enter». Ниже выдается IP-адреса введенного хоста.
Консоль представлена на рисунке 3.4.
Рисунок 3.4 – Консоль вывода IP-адреса введенного хоста
Листинг задания представлен в приложении 3.
ЗАКЛЮЧЕНИЕ
В ходе прохождения учебной была рассмотрена среда .Net. Работа в этой среде проходила с помощью объектно-ориентированного языка программирования С#. Были показаны пространства имён, в которые входят классы для управления файловой системой, работы с делегатами, сборками, домена, процессами и потоками
При помощи среды .Net и программ Windows, позволяющих работать с этой средой, системный администратор расширяет свой кругозор, может справиться с любыми задачами, которые усложняют его работу.
ЛИТЕРАТУРА
Нейгел К., Ивьен Б., Глинн Дж., Уотсон К. C# 4.0 и платформа .NET4 для профессионалов – 2011.
Троелсен Э. Язык программирования C# 2010 и платформа .NET4.
Шилдт Г. Полное руководство С#4.0.
Эндрю Кровчик, Винод Кумар, Номан Лагари, Аджит Мунгале, Кристиан Нагел, Тим Паркер, Шриниваса Шивакумар - .Net. Сетевое программирование для профессионалов.
Приложение 1
Задание 1-2
namespace Тема_1
{
public partial class Form1 : Form
{
string currentFolderPath;
void ClearAllFields()
{
listBoxFiles.Items.Clear();
listBoxFolders.Items.Clear();
textBoxCreationTime.Text = "";
textBoxFileName.Text = "";
textBoxFileSize.Text = "";
textBoxLastAccessTime.Text = "";
textBoxLastWriteTime.Text = "";
}
void DisplayFolderList(string folderFullName) //список Папки
{
DirectoryInfo theFolder = new DirectoryInfo(folderFullName);
if (!theFolder.Exists)
{
throw new DirectoryNotFoundException
("Папка не найдена!" + folderFullName);
}
ClearAllFields();
textBoxFolder.Text = theFolder.FullName;
currentFolderPath = theFolder.FullName;
//Отображение всех подпапок данной папки
foreach (DirectoryInfo nextFolder in theFolder.GetDirectories())
listBoxFolders.Items.Add(nextFolder.Name);
//Отображение всех файлов данной папки
foreach (FileInfo nextFile in theFolder.GetFiles())
listBoxFiles.Items.Add(nextFile.Name);
}
void DisplayFilelnfo(string fileFullName)//вывод информации о файле
{
FileInfo theFile = new FileInfo(fileFullName);
if (!theFile.Exists)
{
throw new FileNotFoundException("Файл не найден: " + fileFullName);
}
textBoxFileName.Text = theFile.Name;
textBoxFileSize.Text = theFile.Length.ToString() + " bytes";
textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();
textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();
}
public Form1()
{
InitializeComponent();
}
private void buttonDisplay_Click(object sender, EventArgs e)
{
try
{
string folderPath = textBoxInput.Text;
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
if (theFolder.Exists)
{
DisplayFolderList(folderPath);
return;
}
FileInfo theFile = new FileInfo(folderPath);
if (theFile.Exists)
{
DisplayFolderList(theFile.Directory.FullName);
int index = listBoxFiles.Items.IndexOf(theFile.Name);
listBoxFiles.SetSelected(index, true);
return;
}
throw new FileNotFoundException
("Файл или папка с таким именем не существует: " +
textBoxInput.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void listBoxFolders_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFolders.SelectedItem.ToString();
string fileFullName = Path.Combine(currentFolderPath, selectedString);
DisplayFolderList(fileFullName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonUp_Click(object sender, EventArgs e)
{
try
{
string folderPath = new FileInfo(currentFolderPath).DirectoryName;
DisplayFolderList(folderPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonUp_Click_1(object sender, EventArgs e)
{
try
{
string folderPath = new FileInfo(currentFolderPath).DirectoryName;
DisplayFolderList(folderPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void listBoxFiles_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFiles.SelectedItem.ToString();
string fileFullName = Path.Combine(currentFolderPath, selectedString);
DisplayFilelnfo(fileFullName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button4_Click(object sender, EventArgs e)
{
FileInfo fi = new FileInfo(textBoxFolder.Text + "/" + listBoxFiles.Text);
string path = textBoxCopy.Text;
fi.CopyTo(path + "/" + listBoxFiles.Text);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string filePath = textBoxFolder.Text + "/" + listBoxFiles.Text;
string filepath2 = listBoxFiles.Text;
string q1 = "Вы действительно хотите удалить? " + filepath2 + "?";
if (MessageBox.Show(q1, "Удалить файл ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) ;
{
File.Delete(filePath);
}
}
catch (Exception ex)
{
MessageBox.Show("Не удается удалить файл: " + ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
FileInfo fi = new FileInfo(textBoxFolder.Text + "/" + listBoxFiles.Text);
string path = textBoxMove.Text;
fi.MoveTo(path + "/" + listBoxFiles.Text);
}
}
}
Задание 3
namespace _333
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DriveInfo[] di = DriveInfo.GetDrives();
foreach (DriveInfo itemDrive in di)
{
listBox1.Items.Add(itemDrive.Name);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DriveInfo di = new DriveInfo(listBox1.SelectedItem.ToString());
try
{
MessageBox.Show("Avaible Free Space: " + di.AvailableFreeSpace + "\n " + "DriveFormat: " + di.DriveFormat + "Drive type: " + di.DriveType + "\n " + "Is Ready: " + di.IsReady + "\n " + "Name: " + di.Name + "\n " + "Root Directory: " + di.RootDirectory + "\n " + "ToStringO Value: " + di + "\n " + "Total Free Space: " + di.TotalFreeSpace + "\n " + "Total Size: " + di.TotalSize + "\n " + "Volume Label: " + di.VolumeLabel, di.Name + " Drive Info: ");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Задание 4
namespace ConsoleAccess
{
class Program
{
private static string mentionedDir;
private static void Main()
{
Console.Write("Введите полный путь к каталогу: ");
mentionedDir = Console.ReadLine();
try
{
DirectoryInfo myDir = new DirectoryInfo(mentionedDir);
if (myDir.Exists)
{
DirectorySecurity myDirSec = myDir.GetAccessControl();
foreach (FileSystemAccessRule fileRule in myDirSec.GetAccessRules(true,
true, typeof(NTAccount)))
{
Console.WriteLine("{0} {1} доступ {2} для {3}", myDir,
fileRule.AccessControlType ==
AccessControlType.Allow ? "разрешен" : "запрещен",
fileRule.FileSystemRights,
fileRule.IdentityReference);
}
}
}
catch
{
Console.WriteLine("Некорректный путь к каталогу!");
}
Console.ReadLine();
}
}
}
Задание 5
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 System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace Задание_5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
DirectoryInfo myDir = new DirectoryInfo(textBox1.Text);
if (myDir.Exists)
{
DirectorySecurity myDirSec = myDir.GetAccessControl();
string al;
foreach (FileSystemAccessRule fileRule in myDirSec.GetAccessRules(true, true, typeof(NTAccount)))
{
if (fileRule.AccessControlType == AccessControlType.Allow)
{
al = "разрешен";
}
else
{
al = "запрещено";
}
MessageBox.Show(myDir + " " + al + " доступ " + fileRule.FileSystemRights + " для " + fileRule.IdentityReference);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Задание 6
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
//string[] args = System.Environment.GetCommandLineArgs();
string[] args = { ".", "d:\\Test" };
// If a directory is not specified, exit program.
if (args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
}
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
Приложение 2
Задание 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Тема_7
{
// Простой пример применения делегата.
// Объявить тип делегата.
delegate string StrMod(string str);
class DelegateTest
{
// Заменить пробелы дефисами.
static string ReplaceSpaces(string s)
{
Console.WriteLine("Замена пробелов дефисами.");
return s.Replace(' ', '-');
}
// Удалить пробелы.
static string RemoveSpaces(string s)
{
string temp = "";
int i;
Console.WriteLine("Удаление пробелов.");
for (i = 0; i < s.Length; i++)
if (s[i] != ' ') temp += s[i];
return temp;
}
// Обратить-строку.
static string Reverse(string s)
{
string temp = "";
int i, j;
Console.WriteLine("Обращение строки.");
for (j = 0, i = s.Length - 1; i >= 0; i--, j++)
temp += s[i];
return temp;
}
static void Main()
{
StrMod strOp = ReplaceSpaces; //короткая запись
string str;
// Вызвать методы с помощью делегата.
str = strOp("Это простой тест.");
Console.WriteLine("Результирующая строка: " + str);
Console.WriteLine();
//strOp = new StrMod(RemoveSpaces); полная запись
strOp = RemoveSpaces;//короткая запись
str = strOp("Это простой тест.");
Console.WriteLine("Результирующая строка: " + str);
Console.WriteLine();
//strOp = new StrMod(Reverse); полная запись
strOp = Reverse;//короткая запись
str = strOp("Это простой тест.");
Console.WriteLine("Результирующая строка: " + str);
}
}
}
Задание 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Тема_7_2
{
// Простой пример применения делегата.
// Объявить тип делегата.
delegate void StrMod(ref string str);
class DelegateTest
{
// Заменить пробелы дефисами.
static void ReplaceSpaces(ref string s)
{
Console.WriteLine("Замена пробелов дефисами.");
s = s.Replace(' ', '-');
}
// Удалить пробелы.
static void RemoveSpaces(ref string s)
{
string temp = "";
int i;
Console.WriteLine("Удаление пробелов.");
for (i = 0; i < s.Length; i++)
if (s[i] != ' ') temp += s[i];
s = temp;
}
// Обратить-строку.
static void Reverse(ref string s)
{
string temp = "";
int i, j;
Console.WriteLine("Обращение строки.");
for (j = 0, i = s.Length - 1; i >= 0; i--, j++)
temp += s[i];
s = temp;
}
static void Main()
{
// Сконструировать делегаты.
StrMod strOp;
StrMod replaceSp = ReplaceSpaces;
StrMod removeSp = RemoveSpaces;
StrMod reverseStr = Reverse;
string str = "Это простой тест.";
// Организовать групповую адресацию.
strOp = replaceSp;
strOp += reverseStr;
// Обратиться к делегату с групповой адресацией.
strOp(ref str);
Console.WriteLine("Результирующая строка: " + str);
Console.WriteLine();
// Удалить метод замены пробелов и добавить метод удаления пробелов.
strOp -= replaceSp;
strOp += removeSp;
str = "Это простой тест."; // восстановить исходную строку
// Обратиться к делегату с групповой адресацией.
strOp(ref str);
Console.WriteLine("Результирующая строка: " + str);
Console.WriteLine();
}
}
}
Задание 3
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
// Объявить тип делегата для события,
delegate void MyEventHandler();
// Объявить класс, содержащий событие,
class MyEvent
{
public event MyEventHandler SomeEvent;
// Этот метод вызывается для запуска события,
public void OnSomeEvent()
{
if (SomeEvent != null)
SomeEvent();
}
}
class EventDemo
{
// Обработчик события,
static void Handler()
{
Console.WriteLine("Произошло событие");
}
static void Main()
{
MyEvent evt = new MyEvent();
// Добавить метод Handler() в список событий,
evt.SomeEvent += Handler;
// Запустить событие,
evt.OnSomeEvent();
}
}
Задание 4
using System;
using System.Linq;
namespace ListAllAssembliesInAppDomain
{
class Program
{
static void Main()
{
AppDomain defaultAD = AppDomain.CurrentDomain;
var loadedAssemblies = from a in defaultAD.GetAssemblies()
orderby a.GetName().Name
select a;
Console.WriteLine("*****Here ate the assemblies loaded in {0} *****\n",
defaultAD.FriendlyName);
foreach (var a in loadedAssemblies)
{
Console.WriteLine("-> Name: {0}", a.GetName().Name);
Console.WriteLine("-> Version: {0}\n", a.GetName().Version);
}
}
}
}
Задание 5
using System;
using System.Linq;
namespace CustomAppDomains1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("*****Fun with custom domains*****\n");
AppDomain defaultAD = AppDomain.CurrentDomain;
ListAllAssembliesInAppDomain(defaultAD);
MakeNewAppDomain();
Console.ReadLine();
}
private static void MakeNewAppDomain()
{
AppDomain newAd = AppDomain.CreateDomain("SecondAppDomain");
ListAllAssembliesInAppDomain(newAd);
}
static void ListAllAssembliesInAppDomain(AppDomain ad)
{
var loadedAssemblies = from a in ad.GetAssemblies()
orderby a.GetName().Name
select a;
Console.WriteLine("*****Here are the assemblies loaded in {0}*****\n", ad.FriendlyName);
foreach (var a in loadedAssemblies)
{
Console.WriteLine("-> Name: {0}", a.GetName().Name);
Console.WriteLine("-> Version: {0}", a.GetName().Version);
}
}
}
}
Задание 6
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Diagnostics;
namespace ConsoleApplication12
{
classProgram
{
staticvoid Main(string[] args)
{
Console.WriteLine("***** Fun with Processes ******");
ListAllRunningProcesses();
Console.ReadLine();
}
publicstaticvoidListAllRunningProcesses()
{
varrunningProcs =
fromprocinProcess.GetProcesses(".") orderbyproc.Idselectproc;
foreach(varp inrunningProcs)
{
string info = string.Format("->PID: {0}\tName: {1}", p.Id, p.ProcessName);
Console.WriteLine(info);
}
Console.WriteLine("*********************************\n");
}
}
}
Задание 7
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Diagnostics;
namespace ConsoleApplication16
{
classProgram
{
staticvoid Main(string[] args)
{
Console.WriteLine("***** Fun with Processes ******");
ListAllRunningProcesses();
Console.ReadLine();
StartAndKillProcess();
}
staticvoidStartAndKillProcess()
{
ProcessieProc = null;
try
{
ieProc = Process.Start("IExplore.exe", "www.vk.com");
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
Console.Write("--> Hit enter to kill {0}...", ieProc.ProcessName);
Console.ReadLine();
try
{
ieProc.Kill();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
}
publicstaticvoidListAllRunningProcesses()
{
varrunningProcs =
fromprocinProcess.GetProcesses(".") orderbyproc.Idselectproc;
foreach (varp inrunningProcs)
{
string info = string.Format("->PID: {0}\tName: {1}", p.Id, p.ProcessName);
Console.WriteLine(info);
}
Console.WriteLine("*********************************\n");
}
}
Задание 8
using System;
using System.Diagnostics;
namespace ProcessStartKill
{
class Program
{
static void Main (string[] args)
{
Process lePdoc = null;
try
{
lePdoc = Process.Start("IExplore.exe", "www.facebook.com");
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("--> Hit enter to kill {0}...", lePdoc.ProcessName);
Console.ReadLine();
try
{
lePdoc.Kill();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Приложение 3
Задание 1
using System;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace WebClient_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
WebClient client = new WebClient();
Stream strm = client.OpenRead("http://www.vk.com");
StreamReader sr = new StreamReader(strm);
string line;
while ((line=sr.ReadLine()) !=null)
{
listBox1.Items.Add(line);
}
strm.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Задание 2
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace WebRequestAndWebResponse_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
WebRequest wrq = WebRequest.Create("http://vk.com");
HttpWebRequest hwrq = (HttpWebRequest)wrq;
listBox1.Items.Add("Request Timeout (ms) : " + wrq.Timeout);
listBox1.Items.Add("Request Keep Alive = " + hwrq.KeepAlive);
listBox1.Items.Add("Request AllowAutoRedirect = " + hwrq.AllowAutoRedirect);
WebResponse wrs = wrq.GetResponse();
Stream strm = wrs.GetResponseStream();
StreamReader sr = new StreamReader(strm);
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
strm.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Задание 3
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
webBrowser1.Navigate(textBox1.Text);
}
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
textBox1.Text = webBrowser1.Url.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://google.com/");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
((WebBrowser)sender).Url = new Uri(((WebBrowser)sender).StatusText);
e.Cancel = true;
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
PrintDialog dlg = new PrintDialog();
dlg.ShowDialog();
}
private void button6_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://google.com/");
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
webBrowser1.GoBack();
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
webBrowser1.GoForward();
}
private void toolStripButton4_Click(object sender, EventArgs e)
{
PrintDialog dlg = new PrintDialog();
dlg.ShowDialog();
}
private void toolStripButton5_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://google.com/");
}
private void toolStripButton6_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
richTextBox1.AppendText(webBrowser1.DocumentText);
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
webBrowser1.Refresh();
int Count = 10000;
Random Rnd = new Random();
int[] Mas_1 = new int[Count];
int[] Mas_2 = new int[Count];
for (int i = 0; i < Count; ++i)
{
Mas_1[i] = Rnd.Next();
Mas_2[i] = Rnd.Next();
}
toolStripProgressBar1.Maximum = Count;
toolStripProgressBar1.Value = 0;
Thread t = new Thread(new ThreadStart(delegate
{
for (int i = 0; i < Count; ++i)
{
this.Invoke(new ThreadStart(delegate
{
toolStripProgressBar1.Value++;
}));
}
}));
t.Start();
}
Задание 4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace ConsoleApplication19
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\nВведите имя хоста:");
string hostname = Console.ReadLine();
IPHostEntry entry = Dns.Resolve(hostname);
Console.WriteLine("\nIP-адресс " + hostname + ": ");
foreach (IPAddress address in entry.AddressList)
Console.WriteLine(address.ToString() );
Console.ReadKey();
}
}
}
