visual basic error in referencing SNMP class - vb.net

I have created an SNMP class
And then i want to test this class,so I create a program which imports this class…
Imports SNMPClass
Module Module1
End Module
Public Class SimpleSNMP
Public Sub Main(ByVal argv As String())
Dim commlength As Integer, miblength As Integer, datatype As Integer, datalength As Integer, datastart As Integer
Dim uptime As Integer = 0
Dim output As String
Dim response As Byte() = New Byte(1023) {}
Dim conn As New SNMP()
Console.WriteLine("Device SNMP information:")
' Send sysName SNMP request
response = conn.[get]("get", argv(0), argv(1), "1.3.6.1.2.1.1.5.0")
If response(0) = &HFF Then
Console.WriteLine("No response from {0}", argv(0))
Return
End If
............
I got an error in this line
Dim conn As New SNMP()
Which says “SNMPClass.SNMP is not accessible in this context because it is friend”..
I m using Visual Studio 2008

While I don't have all of your code to verify this is the case, I believe the following article from Microsoft about this error will address your issue:
http://support.microsoft.com/kb/814319

Related

Class not registered error after migration

Issue with custom VB.net solution after moving user to new Windows 10.
Removing, re-adding various references. Cleaning and Rebuilding.
Public Class mainForm
Dim exc As Excel.Application
Dim wd As Word.Application
Private wsClient As New WebClient()
Dim customAccForm As New customAccessories
Dim custNumArray(4200) As String
Dim preload As Boolean = False
Public custName As String = ""
Public custPhone As String = ""
Public custAddy, custSuite, custCity As String
Dim accessoriesprice, accessoriesWeight As Double
Dim chkQty(20), chkPrc(20), chkWt(20) As Double
Dim chkCtr As Integer = 0
Dim chkDsc(20) As String
Dim currName As String
Dim updateQuotes As Boolean
Dim thr, thr2 As Threading.Thread
Dim bodyTxt, quotedFreight As String
Public USPS_UserID As String = "USERNAME"
I've moved a user from an older Windows 7 machine to a new windows 10 machine. I have a custom built VB.net application that will not compile on the new machine. I get a "class not registered" message and the debugger highlights a variable declaration at the top of Forms class. What's weird is it is on a declaration for a String, the USPS_UserID declaration in the code above. Even weirder is that I can reorder my declarations and it will show the registration error for another class (String, Integer, Double). It varies.

Convert a string into a stream correctly

Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Imports System.IO
Imports System.IO.Compression
Imports System.Text
Namespace WindowScriptingObject
<Guid("7448E08D-ED0F-4E23-B528-91937BB41756"), _
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface _WindowScriptingObject
<DispId(1)> Function Decompress(ByVal value as String) As String
End Interface
<Guid("B146BF9E-78FC-4DB0-ABFE-9FF026B43E4D"), _
ClassInterface(ClassInterfaceType.None), _
ProgId("WindowScriptingObject")> Public Class WindowScriptingObject
Implements _WindowScriptingObject
Public WindowScriptingObject()
Public Function Decompress(ByVal value as string) As String Implements _WindowScriptingObject.Decompress
Dim x As String
' on error resume next
Dim xstream As New MemoryStream(Encoding.Unicode.GetBytes(value))
Dim mem2 As New IO.MemoryStream()
'Dim streamMe As New StreamWriter(mem2,Encoding.UTF8)
'streamMe.Write(value)
'StreamMe.Close()
'mem2.Position=0
Dim gz As New System.IO.Compression.GZipStream(xstream, IO.Compression.CompressionMode.Decompress)
Dim sr As New IO.StreamReader(gz)
x = sr.ReadLine
sr.Close()
'End Using
Decompress = x
End Function
End Class
End Namespace
I verified the string I sent over contains the correct values from my VBScript. However, its says the header is bad.
The above code has to be compiled for testing
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:library /out:"%userprofile%\desktop\t.dll" "%userprofile%\desktop\t.txt" /verbose
Then registered
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm" /codebase "%userprofile%\desktop\t.dll" /tlb:"%userprofile%\desktop\t.tlb" /v
Then invoked
c:\windows\SysWOW64\cscript.exe old.vbs
I put code in to read the contents from a file, even though that is not the end goal. When I did that the file decompressed correctly.
Dim xstream As New MemoryStream(Encoding.Unicode.GetBytes(value))
This line hear seems to be incorrectly converting my string to a stream.
The goal is to send a compressed string and return a uncompressed string.
The code above is invoked with this code
Const adTypeBinary = 1
Set wso = CreateObject("WindowScriptingObject")
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile "e:\download\result.gz"
'objStream.Charset = "Windows-1252"
x = objStream.Read(900)
objStream.Close
For i=1 To Len(x)
t = t & Chr(AscW(Mid(x, i, 1)) And 255)
t = t & Chr((AscW(Mid(x, i, 1)) And 65280)/256)
Next
MsgBox wso.Decompress(t), , "vbs"
I tried this, and even converted the string to base64 to get it work.
Dim gzBuffer As Byte() = Convert.FromBase64String(value)
Using ms As New MemoryStream()
Dim msgLength As Integer = BitConverter.ToInt32(gzBuffer, 0)
ms.Write(gzBuffer, 4, gzBuffer.Length - 4)
Dim buffer As Byte() = New Byte(msgLength - 1) {}
ms.Position = 0
Using zipStream As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)
zipStream.Read(buffer, 0, buffer.Length)
End Using
Decompress=System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length)
End Using
The data did not get converted correctly as I still have magic number in GZip header is not correct.
Dumped base64 encoded value into online decoder, and the string I passed in matches to decoded value.
Version 2
Forces me to base64 encode it, but then it works.
How do I remove this annoyance.
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Imports System.IO
Imports System.IO.Compression
Imports System.Text
Namespace WindowScriptingObject
<Guid("7448E08D-ED0F-4E23-B528-91937BB41756"), _
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface _WindowScriptingObject
<DispId(1)> Function Decompress(ByVal value as String) As String
End Interface
<Guid("B146BF9E-78FC-4DB0-ABFE-9FF026B43E4D"), _
ClassInterface(ClassInterfaceType.None), _
ProgId("WindowScriptingObject")> Public Class WindowScriptingObject
Implements _WindowScriptingObject
Public WindowScriptingObject()
Public Function Decompress(ByVal value as string) As String Implements _WindowScriptingObject.Decompress
Dim x As String
' on error resume next
Dim gzBuffer As Byte() = Convert.FromBase64String(value)
Using ms As New MemoryStream()
Dim msgLength As Integer = BitConverter.ToInt32(gzBuffer, 0)
ms.Write(gzBuffer, 0, gzBuffer.Length)
Dim buffer As Byte() = New Byte(msgLength - 1) {}
ms.Position = 0
Using zipStream As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)
zipStream.Read(buffer, 0, buffer.Length)
End Using
Decompress=System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length)
End Using
' Dim xstream As New MemoryStream(value.ToArray())
Dim mem2 As New IO.MemoryStream()
'Dim streamMe As New StreamWriter(mem2,Encoding.UTF8)
'streamMe.Write(value)
'StreamMe.Close()
'mem2.Position=0
'Dim gz As New System.IO.Compression.GZipStream(xstream, IO.Compression.CompressionMode.Decompress)
'Dim sr As New IO.StreamReader(gz)
' x = sr.ReadLine
'sr.Close()
'End Using
'Decompress = x
End Function
End Class
End Namespace
Update this code works except the output size is 500K, and there's only 3100 bytes of text.
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Imports System.IO
Imports System.IO.Compression
Imports System.Text
Namespace WindowScriptingObject
<Guid("7448E08D-ED0F-4E23-B528-91937BB41756"), _
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface _WindowScriptingObject
<DispId(1)> Function Decompress(ByVal value as string) As String
End Interface
<Guid("B146BF9E-78FC-4DB0-ABFE-9FF026B43E4D"), _
ClassInterface(ClassInterfaceType.None), _
ProgId("WindowScriptingObject")> Public Class WindowScriptingObject
Implements _WindowScriptingObject
Public WindowScriptingObject()
Public Function Decompress(ByVal value as string) As String Implements _WindowScriptingObject.Decompress
' on error resume next
Dim gzBuffer() As Byte = System.Text.Encoding.Default.Getbytes(value)
Using ms As New MemoryStream()
Dim msgLength As Integer = BitConverter.ToInt32(gzBuffer, 0)
ms.Write(gzBuffer, 0, gzBuffer.Length)
msgbox(msgLength)
Dim buffer As Byte() = New Byte(msgLength - 1) {}
ms.Position = 0
Using zipStream As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)
zipStream.Read(buffer, 0, buffer.Length)
End Using
Decompress=System.Text.Encoding.Default.GetString(buffer, 0, buffer.Length)
End Using
End Function
End Class
End Namespace
For some reason msgLength is 559,903 in size, and the decompressed text is roughly 3100 bytes. This means BitConverter.toint32 is malfunctioning as gzBuffer is 865 bytes. The final output size is only know to the GZIPStream function as the text is compressed an the input size has no correlation to the output size.
The other question(s)
can this be coded more efficiently?
What can I do to prevent malicious code injection?
Limit output to the correct size?
If I add new functions do I need more Guid's?
How do I generate a new Guid?
In code block #3 I convert X to a string t and transfer value without conversion.
The output size seems to be based on bad information.
intOutputLength=zipStream.Read(buffer, 0, buffer.Length)
End Using
Decompress=System.Text.Encoding.Default.GetString(buffer, 0, intOutputLength)
At least this reduces the amount of data return to the main program.
Dim msgLength As Integer = BitConverter.ToInt32(gzBuffer, 0)
If I read this correctly the msgLength is determined by the first 4 characters of the input stream? Since the GZip header is always 1f 8b 08 00 this seems to be a horrible idea. If the output is every greater than 559k seems like a buffer overflow just waiting to happen.
I think this solves the terrible buffer size issue.
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Imports System.IO
Imports System.IO.Compression
Imports System.Text
Namespace WindowScriptingObject
<Guid("7448E08D-ED0F-4E23-B528-91937BB41756"), _
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface _WindowScriptingObject
<DispId(1)> Function Decompress(ByVal value as string) As String
End Interface
<Guid("B146BF9E-78FC-4DB0-ABFE-9FF026B43E4D"), _
ClassInterface(ClassInterfaceType.None), _
ProgId("WindowScriptingObject")> Public Class WindowScriptingObject
Implements _WindowScriptingObject
Public WindowScriptingObject()
Public Function Decompress(ByVal value as string) As String Implements _WindowScriptingObject.Decompress
' on error resume next
Dim gzBuffer() As Byte = System.Text.Encoding.Default.Getbytes(value)
dim intOutputLength as integer
Dim intBlock as integer
Decompress=""
Using ms As New MemoryStream()
Dim msgLength As Integer = 4096
ms.Write(gzBuffer, 0, gzBuffer.Length)
Dim buffer As Byte() = New Byte(4096) {}
ms.Position = 0
Using zipStream As New System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)
intOutputLength=0
intBlock=4096
while intBlock=4096
intBlock=zipStream.Read(buffer, 0, buffer.Length)
Decompress+=System.Text.Encoding.Default.GetString(buffer, 0, intBlock)
intOutputLength+=intBlock
end while
End Using
End Using
End Function
End Class
End Namespace
I was able to get your code working by changing the VB.NET function and interface to look like this (mainly changing the parameter type):
<Guid("7448E08E-ED0F-4E23-B528-91937BB41756"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
Public Interface _WindowScriptingObject
<DispId(1)> Function Decompress(ByVal value As Byte()) As String
End Interface
Public Function Decompress(ByVal value As Byte()) As String Implements _WindowScriptingObject.Decompress
Using xstream As New MemoryStream(value)
Using gz As New System.IO.Compression.GZipStream(xstream, IO.Compression.CompressionMode.Decompress)
Using sr As New IO.StreamReader(gz)
Return sr.ReadLine()
End Using
End Using
End Using
End Function
My test VBS looks like this
Const adTypeBinary = 1
Dim wso
Set wso = CreateObject("WindowScriptingObject")
Dim objStream, x
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile "c:\users\bluem\desktop\Notes.txt.gz"
x = objStream.Read(342737)
objStream.Close
WScript.StdOut.WriteLine wso.Decompress((x))
I'm not entirely sure why I needed to enclose the x parameter in two sets of parentheses, but I think it has something to do with forcing the parameter to be passed by value instead of by reference and helps it convert to a byte array. I was getting an error before I added the extra pair of parentheses.
Edit:
To answer some of your other questions:
I don't think you need to create a new GUID for a new function, only for a new interface or class.
To create a new GUID you can just copy an existing one and change part of it (to digits between 0 and F inclusive) to be unique, or you can go to https://www.guidgenerator.com/ or you can select "Create GUID" from Visual Studio's Tools menu.
If you can clarify your data length problem based on the new code (if a problem still exists), I might be able to answer.
It's been too long since I've written vbscript, so I don't know enough anymore to give fixes. However, I can point out some serious flaws in the vbscript part of this code.
It starts by reading up to 900 bytes from a .gz file, regardless of the actual length of file. Anything longer than a mere 900 bytes will be not read.
It performs this read in binary mode. Binary mode ignores any character set or encoding info, and just reads raw bytes, which is appropriate for a .gz file. However, the next thing that happens with this data is using the Len() function, which is for strings, not binary data; Len() is not the appropriate function here. Additionally, the data is next used in the For loop via the Mid() function. Mid() is likewise intended only for strings, and the x variant is not a string. vbscript string objects are more than just the raw characters; they include meta data for things like encoding, length, and character buffers, and those string functions rely on the objects being constructed properly with all metadata.
There's no way this vbscript produces correct results. Until that is resolved, there's no point in even looking at the vb.net code. Again, I'm too far gone to suggest a real solution, but I recommend trying to pass an unaltered byte array to the .Net side, rather than a string.

VB.Net and phpMyAdmin: How to connect to phpMyAdmin SQL server without needing a Username or Password?

I'm setting up a Login Form on Visual Basic .Net. I would like to have this database hosted over the internet, so people can connect wherever they are.
The trouble is, security. If I have a username and password in my code, I can easily be hacked, and my program will be cracked.
Is there any way to have a token that I can use instead of a password, that can only be accessed in through the program itself?
This is my code:
Dim connection As New MySqlConnection("datasource=localhost;port-3306;username;whatever;password=whatever;database=whatever")
And this is something like what I'm looking for:
Dim connection As New MySqlConnection("token=aFjiwqMF93JmHSazhH")
If so, how would I do this, and where would I get the database token and link from?
Anyone able to crack your program, will more likely have the knowledge to crack into MySQL too... I know, it's not an answer, I spent many weeks trying to secure my programs against similar, however, I then thought 'Why...?'
That being said, If you really need to keep your source code under wraps and passwords removed, how about loading the connection string from a text file somewhere?
Simple encryption see system.security.cryptography
I have just looked up my old code for encrypting strings simply, you can have a look at this
Imports System.Security.Cryptography
Imports System.Net
Public NotInheritable Class Encryptorr
Public TDS As New TripleDESCryptoServiceProvider
Private Function EncHash(ByVal key As String, ByVal length As Integer) As Byte()
Dim enc_Sha1 As New SHA1CryptoServiceProvider
Dim keyBytes() As Byte =
System.Text.Encoding.Unicode.GetBytes(key)
Dim hash() As Byte = enc_Sha1.ComputeHash(keyBytes)
ReDim Preserve hash(length - 1)
Return hash
End Function
Sub New(ByVal key As String)
TDS.Key = EncHash(key, TDS.KeySize \ 8)
TDS.IV = EncHash("", TDS.BlockSize \ 8)
End Sub
Public Function EncryptData(ByVal plaintext As String) As String
Dim Strbytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)
Dim memStr As New System.IO.MemoryStream
Dim encStream As New CryptoStream(memStr, TDS.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
encStream.Write(Strbytes, 0, Strbytes.Length)
encStream.FlushFinalBlock()
Return Convert.ToBase64String(memStr.ToArray)
End Function
Public Function DecryptData(ByVal encryptedtext As String) As String
Try
Dim enc_Bytes() As Byte = Convert.FromBase64String(encryptedtext)
Dim mem_Str As New System.IO.MemoryStream
Dim decStream As New CryptoStream(mem_Str, TDS.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
decStream.Write(enc_Bytes, 0, enc_Bytes.Length)
decStream.FlushFinalBlock()
Return System.Text.Encoding.Unicode.GetString(mem_Str.ToArray)
Catch ex As Exception
Return "Decryption Failed"
End Try
End Function
End Class
Call with
Public Sub TestMe()
Dim encr As Encryptorr = New Encryptorr("AlovelyLong463728KeytoEncryptwith")
Dim encrytedstr As String = encr.EncryptData(textbox1.text)
Textbox2.text = encrytedstr
Dim decry As Encryptorr = New Encryptorr("AlovelyLong463728KeytoEncryptwith")
Dim decryptedtext As String = decry.DecryptData(Textbox2.text)
Textbox3.text = decryptedtext
End Sub
You can then encrypt and decrypt strings read from text files, although back to my original point. If someone can gain access to the program code, they can also work out the decryption too... :(
Still food for thought! Good luck
Update--
Just to add, you could always create the encrytped string, use that as a global variable and the decryt function to pass directly as your connection string. This means isnstead of saving the username and password in a text file, you just use Public Shared Constr as String = fhdasjifhn32437289cj (or whatever the encrypted string is) and the connection would be Dim Con as MySQLConnection = new MySQLConnection(DecryptMyStr(Constr)) with DecryptMyStr being the decrypt function

vb.net AES decryption returns "data is incomplete block"

I'm aware of the other thread on this issue (AES decryption error " The input data is not a complete block." Error vb.net), but I'm either not implementing the solutions offered there correctly, or something about my particular variant of this issue isn't covered by those solutions. In any event I'm getting the incomplete block error from the following code
Private GD As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create
Private PDB As New System.Security.Cryptography.Rfc2898DeriveBytes(EK, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, &H65, &H64, &H76, &H65, &H64, &H65, &H76})
Public Function Decrypt(ByVal val As String) As String
Dim ret As String = Nothing
Dim TTB As New System.Text.UTF8Encoding
Try
Dim input() As Byte = TTB.GetBytes(val)
Using ms As New System.IO.MemoryStream(input)
Using cs As New System.Security.Cryptography.CryptoStream(ms, GD.CreateDecryptor(PDB.GetBytes(32), PDB.GetBytes(16)), Security.Cryptography.CryptoStreamMode.Read)
Using sr As New System.IO.StreamReader(cs)
ret = sr.ReadToEnd()
End Using
End Using
End Using
input = nothing
Catch ex As Exception
EL.AddErr("Encountered an error while decrypting the provided text for " & FName & ". Error Details: " & ex.Message, path)
End Try
Return ret
End Function
EK is my key, which I'll not be including. It's just a String though, nothing special.
I've tried several other methods to decrypt based on guidance on the MSDN site, DreamInCode, etc. None worked, but they all had different issues (typically returning a blank string). Seeing as this version of code closely mirrors my encryption code, I'd like to stick with it (or at least as close as I can while still having functional code).
Despite all comments, I still lack understanding of your intentions. Therefore, the sample code below may not provide what you exactly want, but at least should give an idea how to employ cryptographic functions. Particularly, the most notable difference from your approach is that the encryption key and initialization vector are computed once and for all messages, rather than reevaluated on each occasion, because the latter is prone to synchronization errors — such as when you reuse single crypto object to communicate with multiple parties, or when some messages get lost in transmission.
Public Shared Sub Test()
' Note: You should not actually hard-code any sensitive information in your source files, ever!
Dim sKeyPreimage As String = "MySuperPassword"
Dim oMyCrypto As New MyCrypto(sKeyPreimage)
Dim sPlaintext As String = "My super secret data"
Dim sEncrypted As String = oMyCrypto.EncryptText(sPlaintext)
Dim sDecrypted As String = oMyCrypto.DecryptText(sEncrypted)
Console.Out.WriteLine("Plaintext: {0}", sPlaintext) ' "My super secret data"
Console.Out.WriteLine("Encrypted: {0}", sEncrypted) ' "72062997872DC4B4D1BCBF48D5D30DF0D498B20630CAFA28D584CCC3030FC5F1"
Console.Out.WriteLine("Decrypted: {0}", sDecrypted) ' "My super secret data"
End Sub
Public Class MyCrypto
Private Shared TextEncoding As Text.Encoding = Text.Encoding.UTF8
Private CipherEngine As System.Security.Cryptography.SymmetricAlgorithm
' Note: Unlike in the question, same key and IV are reused for all messages.
Private CipherKey() As Byte
Private CipherIV() As Byte
Public Sub New(ByVal sKeyPreimage As String)
Dim abKeyPreimage() As Byte = TextEncoding.GetBytes(sKeyPreimage)
Dim abKeySalt() As Byte = TextEncoding.GetBytes("Ivan Medvedev")
Const KeyDerivationRounds As Integer = 1 << 12
Dim oKeyDerivationEngine As New System.Security.Cryptography.Rfc2898DeriveBytes(abKeyPreimage, abKeySalt, KeyDerivationRounds)
Me.CipherEngine = System.Security.Cryptography.Aes.Create()
Me.CipherEngine.Padding = Security.Cryptography.PaddingMode.PKCS7
Me.CipherKey = oKeyDerivationEngine.GetBytes(Me.CipherEngine.KeySize >> 3)
Me.CipherIV = oKeyDerivationEngine.GetBytes(Me.CipherEngine.BlockSize >> 3)
End Sub
Public Function Encrypt(ByVal abPlaintext() As Byte) As Byte()
Dim abCiphertext() As Byte
Using hStreamSource As New System.IO.MemoryStream(abPlaintext),
hStreamCipher As New System.Security.Cryptography.CryptoStream(
hStreamSource,
Me.CipherEngine.CreateEncryptor(Me.CipherKey, Me.CipherIV),
Security.Cryptography.CryptoStreamMode.Read),
hStreamTarget As New System.IO.MemoryStream
hStreamCipher.CopyTo(hStreamTarget)
abCiphertext = hStreamTarget.ToArray()
End Using
Return abCiphertext
End Function
Public Function Decrypt(ByVal abCiphertext() As Byte) As Byte()
Dim abPlaintext() As Byte
Using hStreamSource As New System.IO.MemoryStream(abCiphertext),
hStreamCipher As New System.Security.Cryptography.CryptoStream(
hStreamSource,
Me.CipherEngine.CreateDecryptor(Me.CipherKey, Me.CipherIV),
Security.Cryptography.CryptoStreamMode.Read),
hStreamTarget As New System.IO.MemoryStream
hStreamCipher.CopyTo(hStreamTarget)
abPlaintext = hStreamTarget.ToArray()
End Using
Return abPlaintext
End Function
Public Function EncryptText(ByVal sPlaintext As String) As String
Dim abPlaintext() As Byte = TextEncoding.GetBytes(sPlaintext)
Dim abCiphertext() As Byte = Me.Encrypt(abPlaintext)
Dim sCiphertext As String = Hex.Format(abCiphertext)
Return sCiphertext
End Function
Public Function DecryptText(ByVal sCiphertext As String) As String
Dim abCiphertext() As Byte = Hex.Parse(sCiphertext)
Dim abPlaintext() As Byte = Me.Decrypt(abCiphertext)
Dim sPlaintext As String = TextEncoding.GetChars(abPlaintext)
Return sPlaintext
End Function
End Class
Public Class Hex
Public Shared Function Format(ByVal abValue() As Byte) As String
Dim asChars(0 To abValue.Length * 2 - 1) As Char
Dim ndxChar As Integer = 0
For ndxByte As Integer = 0 To abValue.Length - 1
Dim bNibbleHi As Byte = abValue(ndxByte) >> 4, bNibbleLo As Byte = CByte(abValue(ndxByte) And &HFUS)
asChars(ndxChar) = Convert.ToChar(If(bNibbleHi <= 9, &H30US + bNibbleHi, &H37US + bNibbleHi)) : ndxChar += 1
asChars(ndxChar) = Convert.ToChar(If(bNibbleLo <= 9, &H30US + bNibbleLo, &H37US + bNibbleLo)) : ndxChar += 1
Next
Return New String(asChars)
End Function
Public Shared Function Parse(ByVal sValue As String) As Byte()
If String.IsNullOrEmpty(sValue) Then Return New Byte() {}
If (sValue.Length Mod 2) > 0 Then Return Nothing
Dim ndxText As Integer = 0
Dim ndxByteMax As Integer = (sValue.Length \ 2) - 1
Dim abValue(0 To ndxByteMax) As Byte
Try
For ndxByte As Integer = 0 To ndxByteMax
abValue(ndxByte) = Convert.ToByte(sValue.Substring(ndxText, 2), 16)
ndxText += 2
Next
Catch ex As Exception
Return Nothing
End Try
Return abValue
End Function
End Class
Again, please, note that this is just an example. I am not endorsing any kind of protection techniques shown here, especially because your task remains unknown. The code above simply illustrates the syntax and semantics — not how to do it right.

Get Result of Private Property TcpClient.BeginConnect, IAsyncResult in VB.NET

I have an application in VB.NET When I run the application in Visual Studio 2010 and mouseover an IAsyncResult, I see the protected property Result. I would like to read the value of the property in the application. How can I do that?
Imports System.Net
Imports System.Net.Sockets
...
Friend Function StartSendGo() As String
'Declarations
Dim strSendMachineName As String = "DEV001"
Dim intSendPort As Integer = 50035
Dim socketclient As New System.Net.Sockets.TcpClient()
Dim rslt As IAsyncResult = tcpClient.BeginConnect(strSendMachineName, intSendPort, New AsyncCallback(AddressOf ConnectCallback), socketclient)
Dim blnSuccess = rslt.AsyncWaitHandle.WaitOne(intTimeOutConnect, True)
'HERE is where I need rslt.Result.Message
End Function
Public Function ConnectCallback()
'Placeholder
End Function
When I mouseover rslt, VS shows that it is of type
System.Net.Sockets.Socket+MultipleAddressConnectAsyncResult I have never seen a plus (+) in a type before, and I am not able to declare a variable of that type. If I expand the properties, there is a protected property Result, which has a property Message with a value of "No connection could be made because the target machine actively refused it 192.0.0.10:50035". I need access to that message. I would also like to access addresses, but that is less important.
I found a solution - to use Reflection to read the value of the private property.
'Imports
Imports System.Reflection
'Call functions that write to rslt
rslt = tcpClient.BeginConnect(strSendMachineName, intSendPort, New AsyncCallback(AddressOf ConnectCallback), socketclient)
blnSuccess = rslt.AsyncWaitHandle.WaitOne(intTimeOutConnect, True)
'Use Reflection
'Get Type
Dim myType As Type = rslt.GetType()
'Get properties
Dim myPropertyInfo As PropertyInfo() = myType.GetProperties((BindingFlags.NonPublic Or BindingFlags.Instance))
'The order of the properties is not guaranteed. Find by name.
For Each pi As PropertyInfo In myPropertyInfo
If pi.Name = "Result" Then
'TODO Add check for nothing.
'Assign to Exception-type variable.
exException = pi.GetValue(rslt, Nothing)
End If
Next