Adding ipv6 address to firewall rule in windows programmatically - vb.net

I am struggling to add ipv6 addresses to firewall rule, ipv4 I was able to add with . could anyone help me out with it would be great
Imports NetFwTypeLib
Imports System.Net
Public Class Firewall
Implements IDisposable
Private _policy As INetFwPolicy2 = Nothing
Private ReadOnly Property Policy As INetFwPolicy2
Get
If _policy Is Nothing Then
_policy = DirectCast(Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")), INetFwPolicy2)
End If
Return _policy
End Get
End Property
Public Sub Add(ipAddress As String, ruleName As String)
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
'Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
Dim NewAddress As String = ipAddress.ToString
If Not firewallRule.RemoteAddresses.Contains(NewAddress) Then
firewallRule.RemoteAddresses += "," & NewAddress
End If
End Sub
End Class

Just in case anyone else faced the same found the answer
Imports System.Net
Public Class Firewall
Implements IDisposable
Private _policy As INetFwPolicy2 = Nothing
Private ReadOnly Property Policy As INetFwPolicy2
Get
If _policy Is Nothing Then
_policy = DirectCast(Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")), INetFwPolicy2)
End If
Return _policy
End Get
End Property
Public Sub Add(ipAddress As String, ruleName As String)
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
Dim NewAddress As String
If IpClass(ipAddress).Equals("ipv4") Then
NewAddress = ipAddress.ToString & "/255.255.255.255"
Else
NewAddress = ipAddress.ToString & "/128"
End If
If Not firewallRule.RemoteAddresses.Contains(NewAddress) Then
firewallRule.RemoteAddresses += "," & NewAddress
End If
End Sub
Public Sub Remove(ipAddress As String, ruleName As String)
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
Dim NewAddress As String
If IpClass(ipAddress).Equals("ipv4") Then
NewAddress = ipAddress.ToString & "/255.255.255.255"
Else
NewAddress = ipAddress.ToString & "/128"
End If
If firewallRule.RemoteAddresses.Contains(NewAddress) Then
Dim ipList As String = firewallRule.RemoteAddresses
ipList = ipList.Replace(NewAddress, "")
ipList = ipList.Replace(",,", ",")
firewallRule.RemoteAddresses = ipList
End If
End Sub
Public Function Exists(ipAddress As String, ruleName As String) As Boolean
Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
Dim NewAddress4 As String = ipAddress.ToString & "/255.255.255.255"
Dim NewAddress6 As String = ipAddress.ToString & "/128"
If firewallRule.RemoteAddresses.Contains(NewAddress4) Or firewallRule.RemoteAddresses.Contains(NewAddress6) Then
Return True
Else
Return False
End If
End Function
Public Function IsAddressValid(ByVal addrString As String) As Boolean
Dim address As IPAddress = Nothing
Return IPAddress.TryParse(addrString, address)
End Function
Public Function IpClass(ipAddress As String) As String
If ipAddress.Contains(".") Then
Return "ipv4"
Else
Return "ipv6"
End If
End Function

Related

Find inactive windows vpn name

How do I find the name of all inactive Windows VPN adapters? I'm working on a VPN app that should list all VPN connections, whether active or inactive. I'm using the NetworkInterface class to list all adapters. It correctly shows the active or inactive Ethernet 2 adapter (used for OpenVPN), and correctly shows the active VPN L2TP connection, but will not list the inactive VPN L2TP adapter name. Are there other (preferably not too obsolete) .Net (or non .Net) classes I could use? I would like to programmaticaly do this, otherwise I could have the option for the user to set the name (I have code to connect, monitor, or disconnect the Windows VPN adapter by name). Any help would be appreciated. Thanks in advance.
Here is the solution I found:
Public Class VPN
Public name As String
Public type As String
Public status As String
Public ip As String
End Class
Public Function GetWindowsVPNs() As List(Of VPN)
Dim vpn_names As String()
Dim vpns As New RAS
Dim strVpn As String
Dim active As Boolean = False
Dim conIPstr As String = ""
Dim vpnCheck As New clsVPN
Dim vpnList As New List(Of VPN)
vpn_names = vpns.GetConnectionsNames()
For Each strVpn In vpn_names
Dim vpn As New VPN
vpn.name = strVpn
vpn.type = "Windows VPN"
active = False
vpnCheck.ConName = vpn.name
active = vpnCheck.CheckConnection()
If active = True Then
vpn.status = "Active"
Try
conIPstr = GetMyIPstr()
Catch e As Exception
MessageBox.Show("Error: Function GetConnectionList: Error returning IP Address" & vbCrLf & vbCrLf & e.Message)
End Try
vpn.ip = conIPstr
Else
vpn.status = "Not Active"
vpn.ip = "No IP Address"
End If
vpnList.Add(vpn)
Next
Return vpnList
End Function
Private Function GetMyIPstr() As String
Dim client As New WebClient
Dim s As String = "No IP Address"
'// Add a user agent header in case the requested URI contains a query.
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR1.0.3705;)")
Dim baseurl As String = "http://checkip.dyndns.org/"
' with proxy server only:
Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
proxy.Credentials = CredentialCache.DefaultNetworkCredentials
client.Proxy = proxy
Dim data As Stream
Try
data = client.OpenRead(baseurl)
Catch ex As Exception
MsgBox("open url " & ex.Message)
Exit Function
End Try
Dim reader As StreamReader = New StreamReader(data)
s = reader.ReadToEnd()
data.Close()
reader.Close()
s = s.Replace("<html><head><title>Current IP Check</title></head><body>", "").Replace("</body></html>", "").ToString()
s = s.Replace("Current IP Address: ", "")
s = s.Replace(vbCr, "").Replace(vbLf, "")
Return s
End Function
Imports System.Linq
Imports System.Net.NetworkInformation
Public Class clsVPN
Public Delegate Sub delPing()
Public Delegate Sub delConnect()
Public Delegate Sub delIdle()
Public Delegate Sub delDisconnect()
Public Delegate Sub delStatus(blnConnected As Boolean)
Public Event Ping As delPing
Public Event Con As delConnect
Public Event Discon As delDisconnect
Public Event Idle As delIdle
Public Event StatusChanged As delStatus
Public strRASPhone As String = "C:\WINDOWS\system32\rasphone.exe"
Public strIPAddress As String = ""
Public strVPNCon As String = ""
Public blnConnected As Boolean = False
Dim file As String = "C : \Users\Tom\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk"
Protected Sub OnStatusChanged(blnConnected As Boolean)
RaiseEvent StatusChanged(blnConnected)
End Sub
Protected Sub OnDisconnect()
RaiseEvent Discon()
End Sub
Protected Sub OnPing()
RaiseEvent Ping()
End Sub
Protected Sub OnIdle()
RaiseEvent Idle()
End Sub
Protected Sub OnConnect()
RaiseEvent Con()
End Sub
Public ReadOnly Property Connected() As Boolean
Get
Return blnConnected
End Get
End Property
Public Property ConName() As String
Get
Return strVPNCon
End Get
Set(strValue As String)
strVPNCon = strValue
End Set
End Property
Public Function Test() As Boolean
Dim blnSucceed As Boolean = False
OnPing()
Dim p As New Ping()
If p.Send(strIPAddress).Status = IPStatus.Success Then
blnSucceed = True
Else
blnSucceed = False
End If
p = Nothing
If blnSucceed <> blnConnected Then
blnConnected = blnSucceed
OnStatusChanged(blnConnected)
End If
OnIdle()
Return blnSucceed
End Function
Public Function Connect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-f " & file & " -d "
OnConnect()
'MessageBox.Show("strVPNCon = " )
'Process.Start(strRASPhone, Convert.ToString(" -f ") & file & Convert.ToString(" -d ") _
' & strVPNCon)
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(5000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function Disconnect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-h "
OnDisconnect()
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(8000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function CheckConnection() As Boolean
Dim niVPN As NetworkInterface() =
NetworkInterface.GetAllNetworkInterfaces
Dim blnExist As Boolean =
niVPN.AsEnumerable().Any(Function(x) x.Name = ConName)
If blnExist Then
'MessageBox.Show("VPN Exists")
Else
' MessageBox.Show("VPN Does Not Exist")
End If
Return blnExist
End Function
Public Sub ProcessExec(processarg As String, param As String, wait As Boolean)
' Start the child process.
Dim p As New ProcessStartInfo
' Redirect the output stream of the child process.
p.FileName = processarg
p.Arguments = param
p.UseShellExecute = True
p.WindowStyle = ProcessWindowStyle.Normal
Dim proc As Process = Process.Start(p)
' Do Not wait for the child process to exit before
' reading to the end of its redirected stream.
If wait = True Then
proc.WaitForExit()
End If
End Sub
End Class
Imports System.Runtime.InteropServices
Public Class RAS
Private Const MAX_PATH As Integer = 260 + 1
Private Const MAX_RAS_ENTRY_NAMES As Integer = 256 + 1
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Structure RASENTRYNAME
Public dwSize As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=MAX_RAS_ENTRY_NAMES)>
Public szEntryName As String
Public dwFlags As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=MAX_PATH)>
Public szPhonebook As String
End Structure
Private Declare Auto Function RasEnumEntries Lib "rasapi32.dll" (
ByVal reserved As String,
ByVal phonebook As String,
<[In](), Out()> ByVal RasEntries() As RASENTRYNAME,
ByRef BufferSize As Integer,
ByRef EntryCount As Integer
) As Integer
Public Function GetConnectionsNames() As String()
Dim res As New List(Of String)
Try
Dim bufferSize As Integer = Marshal.SizeOf(GetType(RASENTRYNAME))
Dim entryCount As Integer = 1
Dim entryNames(0) As RASENTRYNAME
Dim rc As Integer
entryNames(0).dwSize = Marshal.SizeOf(GetType(RASENTRYNAME))
rc = RasEnumEntries(Nothing, Nothing, entryNames, bufferSize, entryCount)
If rc = 0 Then
' There was only one entry and it's been filled into the "dummy"
' entry that we made before calling RasEnumEntries.
res.Add(entryNames(0).szEntryName.Trim)
ElseIf rc = 603 Then
' 603 means that there are more entries than we have allocated space for.
' So, expand the entryNames array and make sure we fill in the structure size
' for every entry in the array! This is important!! Without it, you'll get 632 errors!
ReDim entryNames(entryCount - 1)
For i As Integer = 0 To entryCount - 1
entryNames(i).dwSize = Marshal.SizeOf(GetType(RASENTRYNAME))
Next
rc = RasEnumEntries(Nothing, Nothing, entryNames, bufferSize, entryCount)
For i As Integer = 0 To entryCount - 1
res.Add(entryNames(i).szEntryName.Trim)
Next
Else
' So if we get here, the call bombed. It would be a good idea to find out why here!
MsgBox("Error reading RAS connections names, error code:" & rc.ToString(), MsgBoxStyle.SystemModal)
End If
Catch ex As Exception
MsgBox("Error reading RAS connection names: " & ex.Message.ToString(), MsgBoxStyle.SystemModal)
End Try
Return res.ToArray
End Function
End Class

How to use rasphone.exe to get vpn connection without always prompting for password

I have an app that connects a Windows VPN (not OpenVPN) using the rasphone.exe interface. I can successfully establish the connection but It prompts for the password each time. Is there a way to get the interface to remember the password so that if the connection is lost the connection can automatically be re-established programatically? As a note when I start the process for rasphone.exe I'm getting exceptions when I try to pass more than 1 parameter to it. The only parameter I can successfully pass is the entry name, I can't add parameters like -d, -h, or -f.
Here is the code I have:
Imports System.Linq
Imports System.Net.NetworkInformation
Public Class clsVPN
Public Delegate Sub delPing()
Public Delegate Sub delConnect()
Public Delegate Sub delIdle()
Public Delegate Sub delDisconnect()
Public Delegate Sub delStatus(blnConnected As Boolean)
Public Event Ping As delPing
Public Event Con As delConnect
Public Event Discon As delDisconnect
Public Event Idle As delIdle
Public Event StatusChanged As delStatus
Public strRASPhone As String = "C:\WINDOWS\system32\rasphone.exe"
Public strIPAddress As String = ""
Public strVPNCon As String = ""
Public blnConnected As Boolean = False
Dim file As String = "C : \Users\Tom\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk"
Protected Sub OnStatusChanged(blnConnected As Boolean)
RaiseEvent StatusChanged(blnConnected)
End Sub
Protected Sub OnDisconnect()
RaiseEvent Discon()
End Sub
Protected Sub OnPing()
RaiseEvent Ping()
End Sub
Protected Sub OnIdle()
RaiseEvent Idle()
End Sub
Protected Sub OnConnect()
RaiseEvent Con()
End Sub
Public ReadOnly Property Connected() As Boolean
Get
Return blnConnected
End Get
End Property
Public Property ConName() As String
Get
Return strVPNCon
End Get
Set(strValue As String)
strVPNCon = strValue
End Set
End Property
Public Function Test() As Boolean
Dim blnSucceed As Boolean = False
OnPing()
Dim p As New Ping()
If p.Send(strIPAddress).Status = IPStatus.Success Then
blnSucceed = True
Else
blnSucceed = False
End If
p = Nothing
If blnSucceed <> blnConnected Then
blnConnected = blnSucceed
OnStatusChanged(blnConnected)
End If
OnIdle()
Return blnSucceed
End Function
Public Function Connect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-f " & file & " -d "
OnConnect()
'MessageBox.Show("strVPNCon = " )
'Process.Start(strRASPhone, Convert.ToString(" -f ") & file & Convert.ToString(" -d ") _
' & strVPNCon)
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(5000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function Disconnect() As Boolean
Dim blnSucceed As Boolean = False
Dim optionstr As String = "-h "
OnDisconnect()
optionstr = ""
Dim wait As Boolean = True
ProcessExec(strRASPhone, optionstr & strVPNCon, wait)
Application.DoEvents()
System.Threading.Thread.Sleep(8000)
Application.DoEvents()
blnSucceed = True
OnIdle()
Return blnSucceed
End Function
Public Function CheckConnection() As Boolean
Dim niVPN As NetworkInterface() =
NetworkInterface.GetAllNetworkInterfaces
Dim blnExist As Boolean =
niVPN.AsEnumerable().Any(Function(x) x.Name = ConName)
If blnExist Then
'MessageBox.Show("VPN Exists")
Else
' MessageBox.Show("VPN Does Not Exist")
End If
Return blnExist
End Function
Public Sub ProcessExec(processarg As String, param As String, wait As Boolean)
' Start the child process.
Dim p As New ProcessStartInfo
' Redirect the output stream of the child process.
p.FileName = processarg
p.Arguments = param
p.UseShellExecute = True
p.WindowStyle = ProcessWindowStyle.Normal
Dim proc As Process = Process.Start(p)
' Do Not wait for the child process to exit before
' reading to the end of its redirected stream.
If wait = True Then
proc.WaitForExit()
End If
End Sub
End Class
I know this was asked more than one year before.
I suppose that the described problem is not caused of the Visual Basic code. The problem may be caused from the file rasphone.pbk. It is generally contained in
%APPDATA%\Microsoft\Network\Connections\Pbk
This file can be read with a text editor. There exist an option PreviewUserPw after [YOURVPNNAME]. The value 1 generates a prompting before dialing in.
Changing of this line to
PreviewUserPw=0
will help.

How can I print from an object?

I am having a problem getting my program to print an array. I have created a class with code and I want to be able to use the class to print the array. I have submitted my code below. hopefully Y'all can help me out thanks.
Option Strict On
Imports System.IO
Imports FinalLIB
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fsrFile As StreamReader = New StreamReader("Cars.csv")
Dim line, splitLine(1) As String
Dim bestCars(14) As Cars
Dim counter As Integer
Do Until fsrFile.EndOfStream
line = fsrFile.ReadLine
splitLine = Split(line, ",")
bestCars(counter) = New Cars(splitLine(0), (splitLine(1)), (splitLine(2)), (splitLine(3)))
counter += 1
Loop
Dim strCarMake, strCarModel, intyear, strColorc As Cars
Console.WriteLine(bestCars(3))
End Sub
This is the code from my library created.
Option Strict On
Public Class Cars
Private strCarMake As String
Private strCarModel As String
Private intYear As String
Private strColor As String
Public Sub New(ByVal bvstrCarMake As String, ByVal bvstrCarModel As String, ByVal bvintYear As String, ByVal bvstrColor As String)
prpCarMake = bvstrCarMake
prpYear = CInt(bvintYear)
prpCarModel = bvstrCarModel
prpColor = bvstrColor
End Sub
Public Property prpCarMake() As String
Get
Return strCarMake
End Get
Set(bvstrCarMake As String)
strCarMake = bvstrCarMake
End Set
End Property
Public Property prpCarModel() As String
Get
Return strCarModel
End Get
Set(bvstrCarModel As String)
strCarModel = bvstrCarModel
End Set
End Property
Public Property prpYear() As Integer
Get
Return CInt(intYear)
End Get
Set(bvintYear As Integer)
intYear = CType(bvintYear, String)
End Set
End Property
Public Property prpColor() As String
Get
Return strColor
End Get
Set(bvstrColor As String)
strColor = bvstrColor
End Set
End Property
Public ReadOnly Property prpIsOld() As Boolean
Get
If prpYear > 2010 Then
Return True
Else
Return False
End If
End Get
End Property
'Public ReadOnly Property prpSSN() As String
'Get
'Return strSSN
'End Get
'End Property
Public Function ReturnFullInfo() As String
Return "Make: " & prpCarMake & " Model: " & prpCarModel & "Year: " & prpYear & "Color: " & prpColor
End Function
End Class

How to make a program that removes things form the host file VB.NET

I made a program that adds text to the system32 host file and I want a way a button can remove the selected one from the listbox and delete it from the host file here is the code to add it...
If TextBox1.Text = "" Then
MsgBox("Please Enter A Valid Website Url")
Else
path = "C:\Windows\System32\drivers\etc\hosts"
sw = New StreamWriter(path, True)
Dim sitetoblock As String = (Environment.NewLine & "127.0.0.1 " & TextBox1.Text) 'has to be www.google.com | NOT: http://www.google.com/
sw.Write(sitetoblock)
sw.Close()
ListBox1.Items.Add(TextBox1.Text)
MsgBox("Site Blocked")
End If
Thanks for your time
You can use this code to add, read and delete from windows hosts file.
Add this class to your project -
WindowsHost Class:
Public Class WindowsHost
Public ReadOnly Location As String
Private FullMap As List(Of HostMap)
Public Sub New()
Location = Environment.SystemDirectory & "\drivers\etc\hosts"
If Not System.IO.File.Exists(Location) Then
Throw New System.IO.FileNotFoundException("Host File Was Not Found", Location)
End If
FullMap = LoadCurrentMap()
End Sub
Public Function Count() As Integer
Return FullMap.Count
End Function
Public Function Item(ByVal index As Integer) As HostMap
Return New HostMap(FullMap.Item(index))
End Function
Public Sub AddHostMap(ByVal NewMap As HostMap)
FullMap = LoadCurrentMap()
FullMap.Add(NewMap)
SaveData()
End Sub
Public Sub DeleteHostMapByDomain(ByVal dom As String)
FullMap = LoadCurrentMap()
Dim Reall As Integer = 0
For i As Integer = 0 To FullMap.Count - 1 Step 1
If FullMap.Item(Reall).domain = dom Then
FullMap.RemoveAt(Reall)
Else
Reall += 1
End If
Next
SaveData()
End Sub
Public Sub DeleteHostMapByIp(ByVal ip As System.Net.IPAddress)
FullMap = LoadCurrentMap()
Dim Reall As Integer = 0
For i As Integer = 0 To FullMap.Count - 1 Step 1
If FullMap.Item(Reall).Ip.Equals(ip) Then
FullMap.RemoveAt(Reall)
Reall += 1
End If
Next
SaveData()
End Sub
Public Sub UpdateData()
FullMap = LoadCurrentMap()
End Sub
Private Function LoadCurrentMap() As List(Of HostMap)
Dim FileStream As New System.IO.StreamReader(Location)
Dim Lines() As String = FileStream.ReadToEnd.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
FileStream.Close()
Dim Lst As New List(Of HostMap)
For Each line As String In Lines
If Not line.Contains("#") Then
Dim LineData() As String = line.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
If LineData.Length = 2 Then
Try
Dim temp As New HostMap(LineData(1), System.Net.IPAddress.Parse(LineData(0)))
Lst.Add(temp)
Catch ex As Exception
End Try
End If
End If
Next
Return Lst
End Function
Private Sub SaveData()
Dim Data As String = "# Windows Host Generate" & vbNewLine & "# Time: " & Now.ToString
For Each Map As HostMap In FullMap
Data = Data & vbNewLine & Map.ToString
Next
Dim w As New System.IO.StreamWriter(Location)
w.Write(Data)
w.Close()
End Sub
End Class
Public Class HostMap
Public domain As String
Public Ip As System.Net.IPAddress
Public Sub New(ByVal _dom As String, ByVal _ip As System.Net.IPAddress)
domain = _dom
Ip = _ip
End Sub
Public Sub New(ByRef map As HostMap)
domain = map.domain
Ip = map.Ip
End Sub
Public Overrides Function ToString() As String
Return Ip.ToString & " " & domain
End Function
End Class
Now you can use it like this
Dim WindowsHostSession As New WindowsHost()
WindowsHostSession.AddHostMap(New HostMap("SomeSite.com", System.Net.IPAddress.Parse("127.0.0.1"))) 'Add ip domin map to hosts file
WindowsHostSession.Item(2).domain 'Read the second ip domain map from the hosts file
WindowsHostSession.DeleteHostMapByDomain("SomeSite.com") 'Delete all maps with SomeSite.com domain from the hosts file

vb.net arraylist of objects

I am trying to create an arraylist of objects, and everything is working fine except that the value of all 11 objects are the same. I've have tried multiple ways of writing the code, but I get the same outcome everytime.
arrFullProdList collects the name of all the products in the database. This is working properly. arrProducts is where I am having the issue with all the objects being the same.
What am I doing wrong?
Declared
Private objReader As SqlDataReader
Private objProducts As New CProducts
Private arrFullProdList As ArrayList = New ArrayList
Public arrProdcuts As ArrayList = New ArrayList
class CProduct
Public Class CProduct
Private _pstrProdId As String
Private _pstrProdDesc As String
Private _psngWhCost As Single
Private _psngRetPrice As Single
Private _pblnTaxable As Boolean
Private _isNewProd As Boolean
Public Sub New()
'_pstrProdId = ""
'_pstrProdDesc = ""
'_psngWhCost = 0
'_psngRetPrice = 0
'_pblnTaxable = False
'_isNewProd = False
End Sub
Public Property strProdId() As String
Get
Return _pstrProdId
End Get
Set(strVal As String)
_pstrProdId = strVal
End Set
End Property
Public Property strProdDesc() As String
Get
Return _pstrProdDesc
End Get
Set(strVal As String)
_pstrProdDesc = strVal
End Set
End Property
Public Property sngWhCost() As Single
Get
Return _psngWhCost
End Get
Set(sngVal As Single)
_psngWhCost = sngVal
End Set
End Property
Public Property sngRetPrice() As Single
Get
Return _psngRetPrice
End Get
Set(sngVal As Single)
_psngRetPrice = sngVal
End Set
End Property
Public Property blnTaxable() As Boolean
Get
Return _pblnTaxable
End Get
Set(blnVal As Boolean)
_pblnTaxable = blnVal
End Set
End Property
Public Property IsNewProd() As Boolean
Get
Return _isNewProd
End Get
Set(blnVal As Boolean)
_isNewProd = blnVal
End Set
End Property
Public ReadOnly Property GetSaveParameters() As ArrayList
Get
Dim paramList As New ArrayList
paramList.Add(New SqlClient.SqlParameter("ProdId", _pstrProdId))
paramList.Add(New SqlClient.SqlParameter("ProdDesc", _pstrProdDesc))
paramList.Add(New SqlClient.SqlParameter("WhCost", _psngWhCost))
paramList.Add(New SqlClient.SqlParameter("RetPrice", _psngRetPrice))
paramList.Add(New SqlClient.SqlParameter("Taxable", _pblnTaxable))
Return paramList
End Get
End Property
Public Function Save() As Integer
'return -1 if the ID already exists and we can't create a new record
If _isNewProd Then
Dim strRes As String = myDB.GetSingleValueFromSP("sp_CheckProdIDExists", _
New SqlClient.SqlParameter("ProdId", _pstrProdId))
If Not strRes = 0 Then
Return -1 'ID NOT unique!!
End If
End If
'if not a new member or it is new and is unique, then do the save (update or insert)
Return myDB.ExecSP("sp_SaveProduct", GetSaveParameters)
End Function
End Class
class CProducts
Imports System.Data.SqlClient
Public Class CProducts
'This class represents the Members table and the associated business rules
Private _Product As CProduct
'constructor
Public Sub New()
'instantiate the CMember object
_Product = New CProduct
End Sub
Public ReadOnly Property CurrentObject() As CProduct
Get
Return _Product
End Get
End Property
Public Sub Clear()
_Product = New CProduct
End Sub
Public Sub CreateNewProduct() 'call me when you are clearing the screen to create a new member
Clear()
_Product.IsNewProd = True
End Sub
Public Function Save() As Integer
Return _Product.Save
End Function
Public Function GetProductList() As SqlDataReader
Return myDB.GetDataReaderBySP("dbo.sp_GetProductList")
End Function
Public Function GetProducIdList() As SqlDataReader
Return myDB.GetDataReaderBySP("dbo.sp_GetProductIdList")
End Function
Public Function GetProductByName(strProdDesc As String) As CProduct
Dim params As New ArrayList
Dim param1 As New SqlParameter("proddesc", strProdDesc)
params.Add(param1)
FillObject(myDB.GetDataReaderBySP("dbo.sp_GetProductByName", params))
Return _Product
End Function
Public Function GetProductById(strProdId As String) As CProduct
Dim aParam As New SqlParameter("ProdId", strProdId)
FillObject(myDB.GetDataReaderBySP("dbo.sp_GetProductByID", aParam))
Return _Product
End Function
Public Function FillObject(sqlDR As SqlDataReader) As CProduct
Using sqlDR
If sqlDR.Read Then
With _Product
.strProdId = sqlDR.Item("ProdId") & ""
.strProdDesc = sqlDR.Item("ProdDesc") & ""
.sngWhCost = sqlDR.Item("WhCost") & ""
.sngRetPrice = sqlDR.Item("RetPrice") & ""
.blnTaxable = sqlDR.Item("Taxable") & ""
End With
Else
'failed for some reason
End If
End Using
Return _Product
End Function
'----------Start Alex's Code---------
Public Function GetProductByDesc(strProdDesc As String) As SqlDataReader
Dim aParam As New SqlParameter("ProdDesc", strProdDesc)
Return myDB.GetDataReaderBySP("dbo.sp_GetProductByDesc", aParam)
End Function
End Class
main
Private Sub LoadProducts()
arrProdcuts.Clear()
objReader = objProducts.GetProductByDesc(txtSearch.Text)
While objReader.Read
arrFullProdList.Add(objReader.Item("prodDesc"))
End While
objReader.Close()
For i = 0 To arrFullProdList.Count - 1
Dim aNewProd As CProduct
aNewProd = objProducts.GetProductByName(arrFullProdList.Item(i).ToString)
arrProdcuts.Add(aNewProd)
Next
End Sub