Imports System.IO
Imports System.Net.Sockets
Imports ComponentPro.Net

Namespace ProxySample
	Partial Public Class Sample
		Inherits Form
		Private ReadOnly _settings As SettingInfo

		Public Sub New()
			InitializeComponent()

			' Set timeout values to 15s.
			proxyClient.Timeout = 15000 ' 15 secs

			' Load settings from the Registry.
			_settings = SettingInfo.LoadConfig()
			txtUrl.Text = _settings.Url

			' Get proxy settings.
			txtProxyHost.Text = _settings.ProxyServer
			txtProxyPort.Text = _settings.ProxyPort.ToString()
			cbxType.SelectedIndex = CInt(Fix(_settings.ProxyType))

			' Authentication info.
			txtUserName.Text = _settings.ProxyUser
			txtPassword.Text = _settings.ProxyPassword
			txtDomain.Text = _settings.ProxyDomain
			cbxMethod.SelectedIndex = CInt(Fix(_settings.ProxyMethod))
		End Sub

		''' <summary>
		''' Handles the form's Closed event.
		''' </summary>
		''' <param name="e">The event arguments.</param>
		Protected Overrides Sub OnClosed(ByVal e As EventArgs)
			MyBase.OnClosed(e)

			' Update settings.
			_settings.ProxyServer = txtProxyHost.Text
			Try
				_settings.ProxyPort = Integer.Parse(txtProxyPort.Text)
			Catch
				_settings.ProxyPort = 1080
			End Try
			_settings.ProxyType = CType(cbxType.SelectedIndex, ProxyType)
			_settings.ProxyUser = txtUserName.Text
			_settings.ProxyPassword = txtPassword.Text
			_settings.ProxyDomain = txtDomain.Text
			_settings.ProxyMethod = CType(cbxMethod.SelectedIndex, ProxyHttpConnectAuthMethod)

			_settings.Url = txtUrl.Text

			' And save to the Registry.
			_settings.SaveConfig()
		End Sub

		''' <summary>
		''' Enables/disables controls.
		''' </summary>
		''' <param name="enable">Indicates whether to enable or disable the dialog.</param>
		Private Sub EnableDialog(ByVal enable As Boolean)
			btnGet.Enabled = enable
			grbSettings.Enabled = enable
			grbHost.Enabled = enable
			Util.EnableCloseButton(Me, enable)
		End Sub

		Private uri As Uri
		Private _startTime As Date

		''' <summary>
		''' Handles the Get button's Click event.
		''' </summary>
		''' <param name="sender">The button object.</param>
		''' <param name="e">The event arguments.</param>
		Private Sub btnGet_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGet.Click
			If txtUrl.Text.Length = 0 Then
				MessageBox.Show("Host Name is required", "Error")
				Return
			End If

			Dim proxyPort As Integer = 0
			Try
				' Parse the proxy port number.
				proxyPort = Integer.Parse(txtProxyPort.Text)
			Catch exc As Exception
				MessageBox.Show("Invalid proxy port number: " & exc.Message, "Error")
				Return
			End Try

			' Disable dialog.
			EnableDialog(False)

			proxyClient.ProxyHost = txtProxyHost.Text
			proxyClient.ProxyPort = proxyPort
			proxyClient.ProxyType = CType(cbxType.SelectedIndex, ProxyType)
			proxyClient.UserName = txtUserName.Text
			proxyClient.Password = txtPassword.Text
			proxyClient.Domain = txtDomain.Text
			proxyClient.AuthenticationMethod = CType(cbxMethod.SelectedIndex, ProxyHttpConnectAuthMethod)

			Try
				uri = New Uri(txtUrl.Text)
				lblTime.Text = "Downloading..."

				_startTime = Date.Now
				proxyClient.Connect(uri.Host, uri.Port)

				If proxyClient.Connected Then
					Dim requestMessage As String = "GET " & uri.AbsolutePath & " HTTP/1.1" & vbCrLf & "Host: " & uri.Host & vbCrLf & "Connection: close" & vbCrLf & vbCrLf

					Dim nsr As NetworkStream = proxyClient.GetStream()
					Dim streamWriter As New StreamWriter(nsr)
					streamWriter.Write(requestMessage)
					streamWriter.Flush()

					Dim streamReader As New StreamReader(nsr)
					txtContent.Text = streamReader.ReadToEnd()

					proxyClient.Disconnect()

					Dim ts As TimeSpan = Date.Now.Subtract(_startTime)
					lblTime.Text = String.Format("Downloaded in {0} seconds", ts.TotalMilliseconds / 1000.0F)

					EnableDialog(True)
				End If
			Catch exc As Exception
				EnableDialog(True)
				Util.ShowError(exc)
				lblTime.Text = "Ready"
				proxyClient.Disconnect()
			End Try
		End Sub

		''' <summary>
		''' Handles the combo box proxy type's SelectedIndexChanged event.
		''' </summary>
		''' <param name="sender">The combo box.</param>
		''' <param name="e">The event arguments.</param>
		Private Sub cbx_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbxMethod.SelectedIndexChanged, cbxType.SelectedIndexChanged
			Dim enable As Boolean = cbxType.SelectedIndex > 0

			cbxMethod.Enabled = cbxType.SelectedIndex = CInt(Fix(ProxyType.HttpConnect)) ' Authentication method is available for HTTP Connect only.
			txtDomain.Enabled = cbxMethod.Enabled AndAlso cbxMethod.SelectedIndex = CInt(Fix(ProxyHttpConnectAuthMethod.Ntlm)) ' Domain is available for NTLM authentication method only.
			txtUserName.Enabled = enable ' User name and password are ignored with SendToProxy proxy type. -  && cbxType.SelectedIndex != (int)ProxyType.SendToProxy
			txtPassword.Enabled = enable ' && cbxType.SelectedIndex != (int)ProxyType.SendToProxy
			txtProxyHost.Enabled = enable ' Proxy host and port are not available in NoProxy type.
			txtProxyPort.Enabled = enable
		End Sub
	End Class
End Namespace