vb.net Builder Python Server Connection - python

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

Related

How to run python coding in anaconda prompt using vba?

I am attempting to run python coding using vba.
However, when running using vba, it was not successful .
(i discovered that it is not running in anaconda prompt)
the code is attached as follow. appreciate the help.
Sub RunPythonScript()
Dim objShell As Object
Dim PythonExePath As String, PythonScriptPath As String
Set objShell = VBA.CreateObject("Wscript.Shell")
PythonExePath = """C:xxx.exe"""
PythonScriptPath = """C:xxx.py"""
objShell.Run PythonExePath & " " & PythonScriptPath
End Sub
Alternatively, I manually run in anaconda prompt and the code works.
"C:xxx.exe" "C:xxx.py"
What I observed on screen was the black cmd window pop out and disappeared in second. It did not work as expected. Is there anything I input incorrectly?
Sub RunPythonScript()
Dim pythonExePath As String, pythonScriptPath As String
pythonExePath = """C:\Users\xxx\Anaconda3\python.exe"""
pythonScriptPath = """C:\Users\xxx\xxx.py"""
Shell pythonExePath & " " & pythonScriptPath, vbNormalFocus
End Sub
Try both of these and feedback with your results.
Public Sub PythonOutput()
Dim oShell As Object, oCmd As String
Dim oExec As Object, oOutput As Object
Dim arg As Variant
Dim s As String, sLine As String
Set oShell = CreateObject("WScript.Shell")
arg = "somevalue"
oCmd = "python ""C:\Users\ryans\from_vba.py""" ' & " " & arg
Set oExec = oShell.Exec(oCmd)
Set oOutput = oExec.StdOut
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbNewLine
Wend
Debug.Print s
Set oOutput = Nothing: Set oExec = Nothing
Set oShell = Nothing
End Sub
Sub RunPython()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
PythonExe = """C:\Users\ryans\AppData\Local\Programs\Python\Python38\python.exe"""
PythonScript = "C:\Users\ryans\from_vba.py"
objShell.Run PythonExe & PythonScript
End Sub

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?

Converting python code to vb.net

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.

Executing VBAscript from Python

I am in need of some help in regards to win32com.client. I have the code working as far as creating the macro from Python and using Excel but I would like this code to also run the vbascript.
Thank you guys for all of your wonderful feedback!
import pyodbc
import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
xlmodule = ss.VBProject.VBComponents.Add(1) # vbext_ct_StdModule
sCode = '''Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
ConnectionString = "Provider=SQLOLEDB; Network Library=dbmssocn;Password=********;User ID=*******;Initial Catalog=**;Data Source=*************;"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
StrQuery = "SELECT * FROM car_search WHERE shop_id = *******"
rst.Open StrQuery, cnn
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub'''
xlmodule.CodeModule.AddFromString(sCode)
You should be able to use Excel's Application.Run method:
xl.Run "Download_Standard_BOM"
EDIT
If you need to refer to ADO, then you can either use late-binding, like this:
Dim cnn As Object 'ADODB.Connection
Dim rst As Object 'ADODB.Recordset
Set cnn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
Or, use early binding and add a reference to the VBA Project:
ss.VBProject.References.AddFromGuid "{2A75196C-D9EB-4129-B803-931327F72D5C}", 2, 8

Problem in downloading the file using sharepoint copy.asmx

I am trying to download the file from the document using sharepoint webservices called copy.asmx. its onlt 100 kb file size.
But its not downloading the file.
The web services iteself return empty stream (out byte[] Stream) in the web service response. is that any memory issue.
Also it returning like "download_document()out of memory"
Note: I am using the MFP printer to view this application.
Please try below function. you need to pass FileURL(Full web url for document), Title(Pass name you want to give for downloaded file.)
public string DownLoadfiletolocal(string FileURL, string Title)
{
//Copy.Copy is a webservice object that I consumed.
Copy.Copy CopyObj = new Copy.Copy();
CopyObj.Url = SiteURL + "/_vti_bin/copy.asmx"; // Dynamically passing SiteURL
NetworkCredential nc2 = new NetworkCredential();
nc2.Domain = string.Empty;
nc2.UserName = _UserName;
nc2.Password = _Password;
string copySource = FileURL; //Pass full url for document.
Copy.FieldInformation myFieldInfo = new Copy.FieldInformation();
Copy.FieldInformation[] myFieldInfoArray = { myFieldInfo };
byte[] myByteArray;
// Call the web service
uint myGetUint = CopyObj.GetItem(copySource, out myFieldInfoArray, out myByteArray);
// Convert into Base64 String
string base64String;
base64String = Convert.ToBase64String(myByteArray, 0, myByteArray.Length);
// Convert to binary array
byte[] binaryData = Convert.FromBase64String(base64String);
// Create a temporary file to write the text of the form to
string tempFileName = Path.GetTempPath() + "\\" + Title;
// Write the file to temp folder
FileStream fs = new FileStream(tempFileName, FileMode.Create, FileAccess.ReadWrite);
fs.Write(binaryData, 0, binaryData.Length);
fs.Close();
return tempFileName;
}

Categories