Getting 'BadImageFormatException' when loading libsodium.dll in Visual Studio 17 - vb.net

I have the libsodium-net NuGet loaded into my PoC solution and have the 32-bit and 64-bit libsodium.dll files in their respective directories (System32 and SysWOW64). Whenever I go to run the program in debug mode, I get the BadImageFormatException error. Is it enough to have the libsodium.dll files in their respective System directories and I'm just missing something else, or do I need to have copies of those dll files in my solution as well?
I have tried compiling using both x86 and x64 build configurations since I read here: BadImageFormatException during .Net assembly load issue that, that could be the cause of this error but I still got the same error in both areas.
I also tried the answer I found here: How to include libsodium.net on ASP.NET for incorporating libsodium-net into VS, where it said to install Visual C++ Redistributable 2015 as well, but the problem there is when I tried that, I got an error from the installer stating that it was already installed on my computer. When I checked though, all I had were the 2008, 2013 and 2017 versions, not 2015, so I'm still at a loss on why I couldn't install the 2015 Redistributable but that's for another time.
Here's my procedure and at least according to intellisense, everything here's hooked up correctly.
Option Explicit On
Imports Sodium
Imports System.Text
Public Class Form1
Dim textToEncrypt, decrypted As String
Shared encoder As New UTF8Encoding
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim key, hashedBytes, salt As Byte()
textToEncrypt = TextBox1.Text
Dim textBytes As Byte() = encoder.GetBytes(textToEncrypt)
hashedBytes = CryptoHash.Sha512(textToEncrypt)
salt = PasswordHash.ScryptGenerateSalt()
key = SecretBox.GenerateKey()
Dim passEnc As Byte() = PasswordHash.ScryptHashBinary(textBytes, salt, PasswordHash.Strength.Medium)
TextBox2.Text = Convert.ToBase64String(passEnc)
TextBox6S.Text = Convert.ToBase64String(salt)
TextBox3PBK.Text = Convert.ToBase64String(key)
TextBox5H.Text = Convert.ToBase64String(hashedBytes)
End Sub
End Class
As you can see in the above procedure, this program's fairly straight forward and should just take an input, run it through a couple of Sodium functions, then convert to Base 64 strings and print the results to some text boxes but I get the BadImageFormatException error on each Sodium function the procedure calls.

Related

Sage200c SDK crashing in webforms

We are having a problem with the Sage 200c Extra 2018 SDK when used in Web Forms.
We have created solution with library, win forms and web forms project. We have noticed that when using the 'Win Forms project' it works, but the same example in 'Web Forms project' crashes. Sage 200c SDK documentation does not exclusively talk about Win or Web forms and what configuration each may need.
Could you please help us to get this working in web forms? We have an older version of the SDK working on an older version of Sage 200 v8.
We have upgraded Sage 200 v8 to Sage 200c Extra 2018 Summer Enhancements and tested it with the new client and all is working.
I have noticed on sage City similar questions but no answer.
Here
Here is our code sample:
Private Shared Sub FindCore200()
' get registry info for Sage 200 server path
Dim path As String = String.Empty
Dim root As RegistryKey = Registry.CurrentUser
Dim key As RegistryKey = root.OpenSubKey(REG_PATH)
If key IsNot Nothing Then
Dim value As Object = key.GetValue(REGKEY_VALUE)
If value IsNot Nothing Then
path = TryCast(value, String)
End If
End If
' refer to all installed assemblies based on location of default one
If String.IsNullOrEmpty(path) = False Then
Dim commonDllAssemblyName As String = System.IO.Path.Combine(path, DEFAULT_ASSEMBLY)
If (System.IO.File.Exists(commonDllAssemblyName)) Then
Dim defaultAssembly As System.Reflection.Assembly = System.Reflection.Assembly.LoadFrom(commonDllAssemblyName)
Dim type As Type = defaultAssembly.[GetType](ASSEMBLY_RESOLVER)
Dim method As MethodInfo = type.GetMethod(RESOLVER_METHOD)
Dim x = method.Invoke(Nothing, Nothing)
Dim ok = 1
End If
End If
End Sub
when running the application, it always crashes on
application = New Sage.Accounting.Application
Exception Type: System.TypeInitializationException
Message: The type initializer for 'Sage.Accounting.Application' threw an exception.
Inner Exception:
Exception Type: System.IO.FileNotFoundException
Message: Could not load file or assembly 'Sage.MMSAdmin.Util, Version=19.0.0.0, Culture=neutral, PublicKeyToken=b2daa66d74953d11' or one of its dependencies. The system cannot find the file specified.
Are your application pools targeted to the correct version of .net and bit architecture?
If you can physically see the assembly in the path but the app can't, it's usually down to having the wrong version of .net configured. Going from such an old version to a new one, likely requires a .net version change (2.0 to 4.5 for example). It may just be that your winforms solution is targeted to the correct config and it's definitely worth comparing your build and application settings. Check that your targeting the correct CPU architecture in your build too.

VB.NET Resource exe in memory with argument

Alright so i am pretty new to really anything in memory execution. I usually just write the bytes from the embedded resource into the file on the hard drive but for the program i am making for a work project it cannot write the exe to the disk.
So i took the code from Load a .NET assembly from the application's resources and run It from memory, but without terminating the main/host application
I modified the code a little bit in what i would think would work for running it with an argument and it does nothing but crash, not really listing any crash details though besides the windows error reporting.
here is the code:
Dim ass As Assembly = Assembly.Load(My.Resources.bbinst)
Dim method As MethodInfo = ass.EntryPoint
Dim parametersArray As Object() = New Object() {"/q /SERIAL=xxx-xxx"}
If (method IsNot Nothing) Then
Dim instance As Object = ass.CreateInstance(method.Name)
method.Invoke(instance, parametersArray)
If (instance IsNot Nothing) AndAlso (instance.GetType().GetInterfaces.Contains(GetType(IDisposable))) Then
DirectCast(instance, IDisposable).Dispose()
End If
instance = Nothing
method = Nothing
ass = Nothing
Else
Throw New EntryPointNotFoundException("Entrypoint not found in the specified resource. Are you sure it is a .NET assembly?")
End If
bbinst is the exe name that is embedded as bbinst.exe
The parametersArray is the argument i want to run which i converted from a C# sample i found else where.
Can someone help me as to why the program just crashes and error reporting pops up second after, i'm not to good as debugging. I also tried to run it without the arguments and it as well crashed the same way.
Any help is awesome, sometimes i have these random projects at work i don't know why they give me lol
A BadImageFormatException is thrown either when you attempt to load an assembly of the wrong bitness, or when you try to load an assembly that cannot be read, run or compiled by the current runtime.
Regarding bitness: 32-bit (x86) applications cannot load 64-bit code, and 64-bit (x64) applications cannot load 32-bit code. It's that simple.
As for not being able to read, run or compile the assembly: If the assembly that you're trying to load was programmed in a completely different language (more precisely: a language without .NET support) then it would also cause the above exception to be thrown.
Your method of executing an embedded application will only work with assemblies that were coded in a .NET language (C#, VB.NET, F#, C++/CLR, etc.). This is because that doesn't only run the application, it tries to load it like a .NET app linked to an Assembly, and/or AppDomain, class so that you can have some control over it and invoke methods inside it.
Your issue: My bet that your problem is caused by your embedded application not being of the same bitness as the host. Make sure both applications are compiled either as x86, x64 or AnyCPU.
However if it turns out that your embedded program isn't even written in a .NET language then that is the cause of your problem. That code of yours can only run .NET programs/DLLs.
You can invoke the EntryPoint by loading it in the assembly :
Public Shared Sub RunSearch(ByVal pPath As String, ByVal pText As String)
'Get assembly
Dim assembly As Reflection.Assembly = Reflection.Assembly.GetExecutingAssembly()
'Get the resource stream
Dim resourceStream As Stream = assembly.GetManifestResourceStream("path.executable name")
If resourceStream Is Nothing Then
MsgBox("Unexisting Path","Error")
End If
'Read the raw bytes of the resource
Dim resourcesBuffer(CInt(resourceStream.Length) - 1) As Byte
resourceStream.Read(resourcesBuffer, 0, resourcesBuffer.Length)
resourceStream.Close()
'Load the assembly
Dim exeAssembly As Reflection.Assembly = Reflection.Assembly.Load(resourcesBuffer)
Dim args() As String = {pPath, pText}
Dim parameters = New Object() {args}
Try
exeAssembly.EntryPoint.Invoke(Nothing, parameters)
Catch
MsgBox("Error during assembly executing","Error")
End Try
End Sub

vb.net external dos command hangs without returning output

I am running a dos command from my app, however the dos window just hangs without returning any output. It does work under Windows 8, but not Windows 7.
This is my code:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\Pico Technology\PicoScope6\picoscope.com"
process.StartInfo.UseShellExecute = False
process.StartInfo.Arguments = "/a Measurements.CSV?"
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.Start()
Dim reader As StreamReader = process.StandardOutput
Dim output As String = reader.ReadToEnd()
RichTextBox1.Text = output
End Sub
picoscope.com is a 'wrapper' supplied by the PicoScope vendor - it appears to be a very small .net app, which calls the main PicoScope.exe program with some commands (unknown). The PicoScope.exe app needs to be running for this to work.
I wrote a small console app, and this works just fine - however I can't even call my console app from a forms based application.
Code for console app:
Sub Main()
Dim process As New Process()
process.StartInfo.FileName = "C:\Program Files (x86)\Pico Technology\PicoScope6\picoscope.com"
process.StartInfo.Arguments = "/a Measurements.CSV?"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.Start()
' Synchronously read the standard output of the spawned process.
Dim reader As StreamReader = process.StandardOutput
Dim output As String = reader.ReadToEnd()
process.WaitForExit()
process.Close()
End Sub
This seems to be some strange issue with Windows 7.
I can open cmd.exe without any issue, as well as spawn other applications.
It's almost as if there is some conflict between the running picoscope programs and my application.
Attempting to debug doesn't seem to help at all, with the exception of this:
A first chance exception of type 'System.InvalidOperationException' occurred in System.dll
I have tried several different approaches, disabling shell redirection, even trying to redirect the output to a file. But it would appear that anything to do with this Picoscope app just prevents it working.
I even tried writing another console app to redirect text output to the console and to a file and they worked (because the picoscope app wasn't involved!).
Likewise, a simple dos batch file with "echo Hello World" in it is successfully redirected to my forms app - so I'm sure my code is correct.
I am now at a loss as to what the issue could be here.
I'm using Visual Studio 2013, Windows 7 on SP1.
Can anyone offer any suggestions?
Apologies for the long post, I was trying to give as much detail as possible.
EDIT: Even more curious is that I tried my working app on another Windows 7 PC and it works...
I suspect this must be related to my specific Windows 7 PC (a fresh build).
I compared UAC settings with the other PC - they are the same.
Thanks.

Initializing a Tesseract

I try to get some text of an image by using OCR. I have to initialize a Tesseract for that and this was my try:
Imports Emgu.CV
Imports Emgu.Util
Imports Emgu.CV.Structure
Imports Emgu.CV.OCR
Imports Emgu.CV.UI
Imports Emgu.CV.CvEnum
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lolProcess() As Process = Process.GetProcessesByName("lolClient")
Dim snap As New CScreenFromWindow
Dim OCRz As Tesseract = New Tesseract("tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY)
OCRz.Recognize(New Image(Of Bgr, Byte)(snap.GetFromAll(lolProcess(0))))
MsgBox(OCRz.GetText())
End Sub
End Class
When launching my code I get the following error:
"System.TypeInitializationException"
"Emgu.CV.OCR.Tesseract" caused an exception
I have googled a lot, but can't find my mistake. I've downloaded EMGU from this link and installed the .exe. Then I added every .dll from the bin-directory as a reference to my project. I also added all opencv_XXXXX.dll-files to my project. Then I also added the tessdata-directory to my project. I've marked all the added dlls as "Always copy to output-directory".
There are opencv_XXXXXX.dll-files for x86 and x64. I tried to swap them to x64 but those also don't work.
Does anybody see my mistake?
This are the error-messages and stack-traces:
System.ArgumentException: Unable to create ocr model using Path tessdata and language eng.
bei Emgu.CV.OCR.Tesseract.Init(String dataPath, String language, OcrEngineMode mode) in c:\Emgu\emgucv-windows-universal-gpu 2.4.9.1847\Emgu.CV.OCR\Tesseract.cs:Zeile 226.
bei Emgu.CV.OCR.Tesseract..ctor(String dataPath, String language, OcrEngineMode mode) in c:\Emgu\emgucv-windows-universal-gpu 2.4.9.1847\Emgu.CV.OCR\Tesseract.cs:Zeile 118.
bei Dodgemaster.Form1.Button1_Click(Object sender, EventArgs e) in X:\Dokumente\Visual Studio 2013\Projects\Dodgemaster\Dodgemaster\Form1.vb:Zeile 16.
A Hello World test-programm works fine. So it can't be something wrong with the references, right?
When you have referenced the .dlls try changing the "copy to output directory" value in the properties to "Copy always"
Also try running it on 3.5 .NET framework.
Failing that try following this:
https://www.youtube.com/watch?v=RqvvXJXuRYY&list=UUxAnMtjN08ryThpgYTBmILg
Really helpful tutorial.
After several reinstalls of different emgu-installs I finally found one, that works. It's an older version, not the current one, but it is for x64. Having in mind that EVERY needed file/dll HAS TO be for x64 and working excactly as in the video, I finally got it work.
Seemed to be an x86/x64 issue.
You have to change the DPath from "tessdata" to "".
Dim OCRz As Tesseract = New Tesseract("", "eng", OcrEngineMode.TesseractOnly)
That's how I got mine to work.(libemgucv-windows-universal-cuda-3.0.0.2158)

Cannot add a row to my database without getting 'Illegal Characters in path" error

I am a beginner with Visual Basic.
At the moment I am having a problem with my program where anytime I try and add to a row in my database visual studio flags up an "Illegal characters in path" error.
Here is a snippet of the relevant areas of my code:
Dim customerAdapter As New CustomerDetailsTableAdapters.tblCustomerDetailsTableAdapter
Dim customerTable As CustomerDetails.tblCustomerDetailsDataTable
Dim customerRow As CustomerDetails.tblCustomerDetailsRow
Dim customerDataSet As CustomerDetails
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
customerAdapter.AddCustomer(Forename:="test", Surname:="test",
HouseNumber:="test", StreetName:="test",
Postcode:="test", Email:="test",
Telephone:="test", Mobile:="test",
PreferredContact:="test")
End Sub
I have checked that the data types are correct.
I am working in Visual Studio 2012 Ultimate and I am using .NET Framework 4.
Another thing you should know is that I have one column in the table that is auto incremental by one and currently the table is empty upon start up.
I got rid of slow Visual Studio Ultimate 2012 SQL and installed Visual Studio Ultimate 2010 instead. Turns out something in SQL Server Compact 4.0 that had broken. I did try re-installing 2012 and SQL 4.0 but no good fortune. At least 2010 works :)