Converting python code to vb.net - python

I have a python code. I need vb.net equivalent of it.
Thanks in advance.
payload2 = {"auth_token": "YOUR_AUTH_TOKEN", "status":"green", "data-title1":"index", "data-title2":"machine1", "data-title3":"package10", "data-title4":"current", "data-title5":"tmp"}
r=requests.post("http://localhost:3030/widgets/hot21",data=json.dumps(payload2))
Extra information
Code is invoked in "UiPath community edition"
Last code (thanks to JussiV) is
Imports System.Text
Dim payload2 As New Dictionary(Of String, String)
payload2.Add("auth_token", "YOUR_AUTH_TOKEN")
payload2.Add("status", "green")
payload2.Add("data-title1", "index")
payload2.Add("data-title2", "machine1")
payload2.Add("data-title3", "package10")
payload2.Add("data-title4", "current")
payload2.Add("data-title5", "tmp")
Dim params As String = JsonConvert.SerializeObject(payload2, Formatting.None)
Dim Uri As New Uri(String.Format("http://10.10.115.99:3030/widgets/hot21"))
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Dim reqString() As Byte
webClient.Headers("content-type") = "application/json"
Dim senddata As Object = JsonConvert.SerializeObject(New With {Key .param = params}).ToString()
reqString = Encoding.Default.GetBytes(senddata)
resByte = webClient.UploadData(Uri, "post", reqString)
resString = Encoding.Default.GetString(resByte)
Last error-messages are
webservice has thrown an exception
Source: Invoke code
Message: Error compiling code
error BC30035: syntax error. At line 1
error BC30561: 'Formatting' is ambiguous, imported from the namespaces or types 'Newtonsoft.Json, System.Xml'. At line 10
error BC30002: Type 'WebClient' is not defined. At line 12
error BC30451: 'Encoding' is not declared. It may be inaccessible due to its protection level. At line 18
error BC30451: 'Encoding' is not declared. It may be inaccessible due to its protection level. At line 20
Exception Type: ArgumentException

Creating a dictionary in VB.net https://www.dotnetperls.com/dictionary-vbnet:
Dim payload2 As New Dictionary(Of String, String>
payload2.add("auth_token", "<token>")
....
Then post the dictionary as JSON:
Dim params As String = JsonConvert.SerializeObject(payload2, Formatting.None)
Dim Uri As New Uri(String.Format("http://localhost:3030/widgets/hot"+indeks))
Dim webClient As New WebClient()
Dim resByte As Byte()
Dim resString As String
Dim reqString() As Byte
webClient.Headers("content-type") = "application/json"
Dim senddata As Object = JsonConvert.SerializeObject(New With {Key .param = params}).ToString()
reqString = Encoding.Default.GetBytes(senddata)
resByte = webClient.UploadData(Uri, "post", reqString)
resString = Encoding.Default.GetString(resByte)
Edit:
You are missing at least the import for System.Net that has the WebClient class. I'm not sure where/how you import the Newtonsoft.Json as I don't see it in your imports but based on the errors it is imported somewhere.
For the ambiguous import, see this answer for resolving ambiguous imports.

Related

vb.net Builder Python Server Connection

Imports System.Text
Public Class Form1
Const FileSplitter = "FILE"
Dim stubBytes As Byte()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath As String
Dim filesaver As New SaveFileDialog
If filesaver.ShowDialog = Windows.Forms.DialogResult.OK Then
filePath = filesaver.FileName
Dim email As String = TextBox1.Text
Dim fileSystem = My.Computer.FileSystem
stubBytes = fileSystem.ReadAllBytes(Application.StartupPath & "\stub.exe")
fileSystem.WriteAllBytes(filePath, stubBytes, False)
fileSystem.WriteAllBytes(filePath, Encoding.Default.GetBytes(FileSplitter), True)
fileSystem.WriteAllBytes(filePath, Encoding.Default.GetBytes(email), True)
MessageBox.Show("Server build!")
Else
MessageBox.Show("error!")
End If
End Sub
End Class
I want to connect to a python server. Here is my code. I use pyinstaller and change server.py to server.exe
str='FILE'
print(str)
I want to change FILE message using vb.net

Encryption in python and decryption in vb.net not working

I have this requirement where I need to encrypt a dictionary in python using password based AES256 encryption. I was only given a sample vb.net project by my boss to take reference from regarding the steps that I need to follow for encryption but I am not really aware of how vb.net works. I have converted as much code from vb.net to python as much I could but still the output that my code produces is different from the vb.net project. Can someone please explain what exactly am I missing out on due to which the encryption output of my python program is different than the encryption output of the vb.net program? Thanks in advance!
Here is the vb.net code
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Imports System.Web.Script.Serialization
Imports System.Net
Imports System.Security.Cryptography.X509Certificates
Imports System.Net.Security
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loginrequest()
End Sub
Private Sub loginrequest()
Dim lobjLogin As New loginrequest
lobjLogin.jsonProperty1 = "jsonProperty1"
lobjLogin.jsonProperty2 = "jsonProperty2"
lobjLogin.jsonProperty3 = "jsonProperty3"
lobjLogin.jsonProperty4 = "jsonProperty4"
Dim lRequestJson As String = ""
lRequestJson = (New JavaScriptSerializer()).Serialize(lobjLogin)
Dim lchecksum As String = EncryptText(lRequestJson, "key")
End Sub
Public Function EncryptText(pInput As String, password As String) As String
Dim bytesToBeEncrypted As Byte() = Encoding.UTF8.GetBytes(GenerateSHA256String(pInput))
Dim passwordBytes As Byte() = Encoding.UTF8.GetBytes(password)
passwordBytes = SHA256.Create().ComputeHash(passwordBytes)
Dim bytesEncrypted As Byte() = AES_Encrypt(bytesToBeEncrypted, passwordBytes)
Dim result As String = Convert.ToBase64String(bytesEncrypted)
Return result
End Function
Private Function AES_Encrypt(bytesToBeEncrypted As Byte(), passwordBytes As Byte()) As Byte()
Dim encryptedBytes As Byte() = Nothing
Dim saltBytes As Byte() = New Byte() {1, 2, 3, 4, 5, 6, _
7, 8}
Using ms As New MemoryStream()
Using AES As New RijndaelManaged()
AES.KeySize = 256
AES.BlockSize = 128
Dim key = New Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000)
AES.Key = key.GetBytes(AES.KeySize / 8)
AES.IV = key.GetBytes(AES.BlockSize / 8)
AES.Mode = CipherMode.CBC
Using cs = New CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length)
cs.Close()
End Using
encryptedBytes = ms.ToArray()
End Using
End Using
Return encryptedBytes
End Function
Private Function GenerateSHA256String(ByVal inputString) As String
Dim sha256 As SHA256 = SHA256Managed.Create()
Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputString)
Dim hash As Byte() = sha256.ComputeHash(bytes)
Dim stringBuilder As New StringBuilder()
For i As Integer = 0 To hash.Length - 1
stringBuilder.Append(hash(i).ToString("X2"))
Next
Return stringBuilder.ToString()
End Function
End Class
Public Class loginrequest
Public Property jsonProperty1 As String
Public Property jsonProperty2 As String
Public Property jsonProperty3 As String
Public Property jsonProperty4 As String
End Class
Here is the corresponding python code that I wrote
import base64
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Util.Padding import pad
import hashlib, json
payload = {
"jsonProperty1": "jsonProperty1",
"jsonProperty2": "jsonProperty2",
"jsonProperty3": "jsonProperty3",
"jsonProperty4": "jsonProperty4",
}
payload = json.dumps(payload)
bytesToBeEncrypted = hashlib.sha256(payload.encode("utf-8")).hexdigest()
class AESCipher(object):
def __init__(self, key, interactions=1000):
self.bs = AES.block_size
self.key = hashlib.sha256(key.encode("utf-8")).hexdigest()
self.interactions = interactions
def pkcs7padding(self, data, block_size=16):
if type(data) != bytearray and type(data) != bytes:
raise TypeError("Only support bytearray/bytes !")
pl = block_size - (len(data) % block_size)
return data + bytearray([pl for i in range(pl)])
def encrypt(self, raw):
import os
raw = "".join([x.upper() for x in bytesToBeEncrypted])
keyiv = PBKDF2(self.key, os.urandom(8), 48, self.interactions)
key = keyiv[:32]
iv = keyiv[32:48]
cipher = AES.new(key, AES.MODE_CBC, iv)
encoded = raw.encode("utf-8")
encodedpad = self.pkcs7padding(encoded)
ct = cipher.encrypt((encodedpad))
cip = base64.b64encode(ct)
print(cip, len(cip))
enc = AESCipher("key")
dec = enc.encrypt(bytesToBeEncrypted)
Please note that I took some reference from some other threads as well regarding my python code because encryption is a new concept for me.
P.S. I also found out that the vb.net code is using .toString("X2") to generate a hexadecimal string in uppercase but unfortunately, I was not able to find the corresponding equivalent in python for the same. Could that be a problem?

Decoding base64 image string to an image in Unity

I'm using the following code encode an image from python end,
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5558")
frame = cv2.imread("input.jpg")
encoded, buffer = cv2.imencode('.jpg', frame)
encoded_string = base64.b64encode(buffer)
socket.send_string("output", zmq.SNDMORE)
socket.send_pyobj(encoded_string)
Eventually, I'm using the following code to decrypt it in Unity end.
void Start()
{
AsyncIO.ForceDotNet.Force();
NetMQConfig.ManualTerminationTakeOver();
NetMQConfig.ContextCreate(false);
string topic = "output";
subSocket = new SubscriberSocket();
var timeout = new System.TimeSpan(0, 0, 1); //1sec
string subport;
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://localhost:5558");
subSocket.Subscribe(topic);
bool is_connected = subSocket.TryReceiveFrameString(timeout, out subport);
Debug.Log(is_connected);
myTexture = new Texture2D(640, 480, TextureFormat.ARGB32, false);
}
// Update is called once per frame
void Update()
{
string base64string = subSocket.ReceiveFrameString();
Debug.Log(base64string.Length);
if (base64string.Length > 100)
{
byte[] imgBytes = Convert. FromBase64String(base64string);
myTexture.LoadRawTextureData(imgBytes);
myTexture.Apply();
rawImg.texture = myTexture;
}
}
Unfortunately it throws the following error,
FormatException: The input is not a valid Base-64 string as it
contains a non-base 64 character, more than two padding characters, or
an illegal character among the padding characters.
what am I missing?
It would be more helpful if you could try sending a very small image through the channel (encode, transfer, receive) and log-print what was received on the other end.
My suspicions:
Somehow you're not converting to base-64
You end up sending too many bytes, or unnecessary bytes (null-termination character?)
Receiving the image content in a manner that adds CR or LF at the end (such as 'HTTP Response' body)
More information is needed to provide a better answer...

Calling functions with arguments from CoreFoundation using ctypes

I am trying to access the CoreMidi functions from the CoreFoundation framework in MacOSX using ctypes in Python.
When I call a function that doesn't have any parameters, everything goes fine. For example, the following code:
from ctypes import *
core_midi = cdll.LoadLibrary("/System/Library/Frameworks/CoreMIDI.framework/Versions/A/CoreMIDI")
numOfDevices = core_midi.MIDIGetNumberOfDevices()
print numOfDevices
returns
3
which is the number of MIDI devices in my computer.
However, I am not able to execute functions which require parameters. Check this example (EDIT: as eryksun pointed out, I was using a char* as client_name, and the function prototype demanded a CFString. I corrected this in the code example below but I still get the same error):
core_midi = cdll.LoadLibrary("/System/Library/Frameworks/CoreMIDI.framework/Versions/A/CoreMIDI")
client_name = core_foundation.CFStringCreateWithCString(None, "MIDI Client", 0)
midi_client = c_uint()
result = core_midi.MIDIClientCreate(client_name, None, None, byref(midi_client))
print midi_client
print result
This code doesn't print anything at all, doesn't even raise an exception. The MIDIClientCreate function's prototype is:
extern OSStatus MIDIClientCreate(
CFStringRef name,
MIDINotifyProc notifyProc,
void *notifyRefCon,
MIDIClientRef *outClient );
MIDIClientRef is defined as a UInt32, and, as I understand, it receives a pointer to a MIDIClient structure that is created, that is why I use byref() to pass it as a parameter. If I just pass the variable without byref(), the function call returns a value -50, which probably indicates some bizarre error.
EDIT: I am not sure if I am creating the CFString correctly. I tried to test the result with the following code but it doesn't print anything on screen.
client_name = core_foundation.CFStringCreateWithCString(None, "MIDI Client", 0)
cstr = ctypes.create_string_buffer(20)
core_foundation.CFStringGetCString(client_name, cstr, 20, 0)
print cstr
Thanks!
EDIT: Answered by eryksun!
I didn't know this of course, but setting the pointers is not as obvious as my naive example was trying to do.
class _CFString(Structure):
pass
cf_path = ctypes.util.find_library("CoreFoundation")
cm_path = ctypes.util.find_library("CoreMIDI")
core_foundation = ctypes.cdll.LoadLibrary(cf_path)
core_midi = ctypes.cdll.LoadLibrary(cm_path)
CFStringRef = POINTER(_CFString)
midi_client = ctypes.c_uint()
core_foundation.CFStringCreateWithCString.restype = CFStringRef
core_foundation.CFStringCreateWithCString.argtypes = [c_void_p, c_char_p, c_uint32]
client_name = core_foundation.CFStringCreateWithCString(None, "MIDI Client", 0)
core_midi.MIDIClientCreate.argtypes = [CFStringRef, c_void_p, c_void_p, POINTER(c_uint32)]
result = core_midi.MIDIClientCreate(client_name, None, None, byref(midi_client))
print midi_client
print result
Actually, I though restype and argtypes didn't affect how functions were executed or how parameters were passed to them, but it seems that they do.
The above code results in:
c_uint(4657178L)
0
That is, my MIDI client is created somewhere and the function returns without error.
Thanks again eryksun!

Can't pass a string to char * arg of function call in dll in python

I am trying to use a dll in Python source using the ctypes. I began reading it from Python documentation as I am new to this. After successfully loading the dll in Python, when I try to pass a string to a function which expects a char *, it gives me
"ValueError: Procedure probably called with too many arguments (4
bytes in excess)".
I also tried looking at other posts but couldn't resolve the problem.
I tried different approaches to pas this string such as using byref() and pointer() but it didn't change the outcome. I also tried with WINFUNCTYPE but failed. The dll that I'm using is windll.
Here's a test program I wrote in python:
from ctypes import *
lpDLL=WinDLL("C:\some_path\myDll.dll")
print lpDLL
IP_ADDR = create_string_buffer('192.168.100.228')
#IP_ADDR = "192.168.100.228"
#IP_ADDR = c_char_p("192.168.100.228")
print IP_ADDR, IP_ADDR.value
D_Init=lpDLL.D_Init
D_InitTester=lpDLL.D_InitTester
#D_InitTesterPrototype = WINFUNCTYPE(c_int, c_char_p)
#D_InitTesterParamFlags = ((1, "ipAddress", None),)
#D_InitTester = d_InitTesterPrototype(("D_InitTester", lpDLL), D_InitTesterParamFlags)
try:
D_Init()
D_InitTester("192.168.100.254")
except ValueError, msg:
print "Init_Tester Failed"
print msg
Here's how the D_InitTester is implemented in a cpp file which is available in dll exports,
D_API int D_InitTester(char *ipAddress)
{
int err = ERR_OK;
if (LibsInitialized)
{
...
some code;
...
else
{
err = hndl->ConInit(ipAddress);
}
if ( 0 < err )
{
err = ERR_NO_CONNECTION;
}
else
{
nTesters = 1;
InstantiateAnalysisClasses();
InitializeTesterSettings();
if(NULL != hndl->hndlFm)
{
FmInitialized = true;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
return err;
}
Your help is greatly appreciated.
Most likely the cause of the error is a mismatch of calling conventions. I'm guessing your C++ DLL exports functions with cdecl convention but your use of WinDLL implies stdcall.
Create your library like this to use cdecl:
lpDLL=CDLL("C:\some_path\myDll.dll")

Categories