The type initializer for '[Modulename]' threw an exception - visual-studio-2022

i am using visual studio 2022
if i run the program from IDE, it runs, creates the SQLite database
and all funtions work as expectd.
if i create an installation through VS installer program and run the
program, i get the following error
"The type initializer for '[Modulename]' threw an exception"
here is the code in my module.
error occurs no matter were i place this
#Region "Declarations"
'Find users Roaming location
'Get the path to the Application Data folder
Public appData1 As String = GetFolderPath(SpecialFolder.ApplicationData)
Public location As String = appData1 & "\RJ Enterprize\" & Application.ProductName
Public fileName As String = "Password2023.rjd"
Public fullPath As String = System.IO.Path.Combine(location, fileName)
Public connectonString As String = String.Format("Data Source = {0}", fullPath)
Public SqlConn As New SQLiteConnection(connectonString)
#End Region
tried in various modules and forms

Related

VB6 dll in COM+ Sub Main is not called

VB6 dll named SimpleBO with a module (.bas) and Sub Main has the following code
Public gsConnectionString As String
Sub Main()
Dim constr As String
constr = getConStr() 'get it from a file
gsConnectionString = constr
LogToFile "At main after getting constr showing gsConnectionString " & gsConnectionString 'logToFile simply writes a line in a file
....
Exit Sub
... Error handler
Exit sub
The module also has a public method:
Public Function GetConnectionEnterprise() As String
GetConnectionEnterprise = gsConnectionString
Exit Function
The dll has a class called SystemBO with different methods including:
Public Function Connection() As String
Connection = GetConnectionEnterprise
Exit Function
Then a VB6 exe also has a module with Sub Main as it startup.
It references the dll and has this code in the sub main:
Public gsConnectionString as String
Sub Main()
Dim oBO As SimpleBO.SystemBO
Set oBO = New SimpleBO.SystemBO
gsConnectionString = oBO.Connection
LogToFile "InTestBOSimple:ModStartUpForTestBOSimple:Main gsConnectionString " & gsConnectionString
frmTestBO1.Show
Set oBO = Nothing
Exit Sub
The VB6 is added as a COM+ component.
First test on a Windows 10 computer - running the exe.
The log file shows:
SimpleBO:modStartUp:Main At main after getting constr showing gsConnectionString Provider=sqlOLEDB;Data ...
Then
InTestBOSimple:ModStartUpForTestBOSimple:Main gsConnectionString Provider=sqlOLEDB;Data Source
Results as expected. The Sub Main of the dll is called.
Next install the dll and the exe on Windows Server 2012 running on a VM.
The dll is installed in Com+ with same setup.
Then when running the exe (which runs with no errors) the log file does not show that the Sub Main of the dll was called and only shows:
InTestBOSimple:ModStartUpForTestBOSimple:Main gsConnectionString (blank)
Meaning the call to oBO.Connection, which did not error out, returned nothing, which also shows that Sub Main of the dll was not called.
I tried various things - re install the com+ from scratch on the server but same issues.
I tried to add code in the exe which has a form and on a button click has
Private Sub cmdGetCN_Click()
Dim oBO As SimpleBO.SystemBO
Dim cn As String
Set oBO = New SimpleBO.SystemBO
cn = oBO.Connection
lblMessage.Caption = "cn = " & cn
Exit Sub
the message showed CN = (and blank after it).
Did anyone experience this type of issue?
Thank you

Extracting `dll` files from the Resources after they been added using CodeDOM in VB.Net

I'v seen a lot of answers here on stackoverflow, but none of them help me with exactly what i need and almost all of them in C# when i need VB, so i hope someone will help me with my problem, which is this :
I have compiled a exe file in vb.net using CodeDOM, and i added two dll file to its resources and that worked just fine and you can even notice that the size of the exe has increase after adding the resources, but when i run the exe file like that My.Resources.Touchless, it gives me an error saying that
"Resources" is not a member of "My".
And what i need is to read these dll files from the compiled exe file and then extract them using File.WriteAllBytes()..., if i didn't try to extract the files from the resources and instead of that i copied them manually to the executable path, the application will work perfectly, so the problem is just with trying to call the dll files from the resources.
Here is some code :
Public Shared Function Compile(ByVal Output As String, ByVal Source As String, ByVal Icon As String, ByVal resources As String) As Boolean
Dim Parameters As New CompilerParameters()
Dim cResults As CompilerResults = Nothing
Dim Compiler As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
Parameters.GenerateExecutable = True
Parameters.TreatWarningsAsErrors = False
Parameters.OutputAssembly = Output
Parameters.MainClass = "MyNamespace.MainWindow"
Parameters.EmbeddedResources.Add(Path.GetTempPath & "TouchlessLib.dll")
Parameters.EmbeddedResources.Add(Path.GetTempPath & "WebCamLib.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", Path.GetTempPath & "TouchlessLib.dll"})
Parameters.CompilerOptions = "/platform:x86 /target:winexe"
If Not String.IsNullOrEmpty(Icon) Then
File.Copy(Icon, "icon.ico")
Parameters.CompilerOptions += " /win32icon:" & "icon.ico"
End If
cResults = Compiler.CompileAssemblyFromSource(Parameters, Source)
If cResults.Errors.Count > 0 Then
For Each compile_error As CompilerError In cResults.Errors
Dim [error] As CompilerError = compile_error
Console.Beep()
MsgBox("Error: " & [error].ErrorText & vbCr & vbLf & [error].Line)
Next
Return False
End If
If Not (String.IsNullOrEmpty(Icon)) Then
File.Delete("icon.ico")
End If
Return True
End Function
When i call them from the compiled exe file like this :
File.WriteAllBytes(Application.StartupPath & "\TouchlessLib.dll", My.Resources.TouchlessLib)
File.WriteAllBytes(Application.StartupPath & "\WebCamLib.dll", My.Resources.WebCamLib)
... i get the following error message :
"Resources" is not a member of "My".
Try adding this class:
Imports System.Dynamic
Imports System.Reflection
Public Class DynamicResources
Inherits DynamicObject
Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim name As String = IO.Path.GetFileNameWithoutExtension(s)
Dim Manager As New Resources.ResourceManager(name, asm)
Try
Dim resource = Manager.GetObject(binder.Name)
If Not resource Is Nothing Then
result = resource
Return True
End If
Catch ex As Exception
End Try
Next
Return False
End Function
End Class
You can use it like this:
Dim root as string=Application.StartupPath
File.WriteAllBytes(Path.Combine(root, "TouchlessLib.dll"), DynamicResources.TouchlessLib)
File.WriteAllBytes(Path.Combine(root, "WebCamLib.dll"), DynamicResources.WebCamLib)
The My namespace and any associated functionality is created via auto-generated code. Since your code is now the code generator and not the IDE, you will not have those niceties unless your code provides it.
To extract an embedded resource, you need to include code similar to the following in the source code you are compiling with CodeDOM.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim fi As New FileInfo(s)
Using strm As Stream = asm.GetManifestResourceStream(s)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
Next
Make sure that you also include:
Imports System.Reflection
Imports System.IO
This code retrieves the executing Assembly obtains an array of embedded resource names. It then calls GetManifestResourceStream method to get the named resource as a stream. This stream is copied to a file stream.
Modify the example to suite your needs.
Note that I have not included any error checking/handling in this example. Anything dealing with IO should have some error handling.
Edit:
Based on the comment below, it appears that only a copy/paste type answer will do for the OP.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resourceName As String
Dim fi As FileInfo
resourceName = "TouchlessLib.dll"
fi = New FileInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, resourceName))
Using strm As Stream = asm.GetManifestResourceStream(resourceName)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using

Cannot upload the file to dropbox when published on server

I'm trying to upload a file to dropbox. The file gets uploaded and code works when i'm running locally. But file never gets uploaded when published on the server. I'm having the following error .
Could not load type 'System.Security.Authentication.SslProtocols' from assembly 'System.Net.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*********'.
I'm trying the below code sample to upload it
public sub uploadtodropbox()
Using httpclient As New HttpClient
httpclient.Timeout = TimeSpan.FromMinutes(20)
Dim _DropboxClient = New DropboxClient(ApiKeyDropBox, config)
Dim resultstring As String = UploadToDB(_DropboxClient, dropboxdir, docName, fileBytes)
_DropboxClient.Dispose()
If Not resultstring = "RanToCompletion" Then
ErrorMsg &= "The following error occured: " & resultstring
End If
End Using
End Sub
and this is the funtion that is uploading to Dropbox
Private Function UploadToDB(_DropboxClient As DropboxClient, Directory As String, Filename As String, Content As [Byte]()) As String
Try
Dim result As String = "Unknown"
Dim trycnt As String = 0
Dim tryLimit As String = 20
Dim respnse As Task(Of FileMetadata)
Using _mStream = New MemoryStream(Content)
respnse = _DropboxClient.Files.UploadAsync(Convert.ToString(Directory & Convert.ToString("/")) & Filename, WriteMode.Overwrite.Instance, body:=_mStream)
While Not respnse.IsCompleted And trycnt < tryLimit
Threading.Thread.Sleep(1000)
trycnt += 1
result = respnse.Status.ToString()
End While
UploadToDB = result
End Using
End try
END function.
I have tried without using the httpclient then i am getting this error :
The type initializer for 'Dropbox.Api.DropboxRequestHandlerOptions' threw an exception.
Thank you
I go the answer . I have system.Net.primitives assembly that is creating a problem uploading the file to Dropbox. All i need to do is delete the reference and also the System.Net.Http has versions have been set wrong in the web.config file. Once i set that in the configuration everything works fine.
For the certificate I have set the on post back to validate and allow the certificates generated in the event handler.

VB.NET How to save Program settings inside class module

I'm currently building a program which requires numerous staff to use my program and the program is located on a shared drive on the network so all users can access the program. In my program I have a Database which I use to manage all the user accounts and other information. When you run the program for the first time ever on the network, it asks the administrator where to create the database. After the program creates the database, I save the connection string to a string variable in a class module within my program. However once I exit the program the value I set the to the string variable in the class gets erased. Is there a way to prevent the string from losing its value after closing the program ? I know I could do this via my.settings but I don't want to do it that way.
You can make your own settings file using a binary serializer.
This method can be used to store an instance of your settings class to a file, which is not very human-readable. If human readability and editability is required, you could use an xml serializer instead. The settings file will reside in the application directory. You can control this with the variable settingsFileName.
Create a new console application and paste the code below. Run it a couple of times and note that the "connection string" is persisted through application close and open.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Module Module1
Private settingsFileName As String = "Settings.bin"
Private mySettingsClass As SettingsClass
Private Sub loadSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Open)
mySettingsClass = CType(formatter.Deserialize(stream), SettingsClass)
End Using
Else
Using Stream As New FileStream(settingsFileName, FileMode.CreateNew)
mySettingsClass = New SettingsClass()
formatter.Serialize(Stream, mySettingsClass)
End Using
End If
End Sub
Private Sub saveSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Truncate)
formatter.Serialize(stream, mySettingsClass)
End Using
Else
Using stream As New FileStream(settingsFileName, FileMode.CreateNew)
formatter.Serialize(stream, mySettingsClass)
End Using
End If
End Sub
<Serializable>
Public Class SettingsClass
Public Property ConnectionString As String = ""
End Class
Sub Main()
Console.WriteLine("Loading settings...")
loadSettings()
Dim connectionString = mySettingsClass.ConnectionString
Console.WriteLine("Connection string: ""{0}""", connectionString)
Console.WriteLine("Enter new connection string...")
mySettingsClass.ConnectionString = Console.ReadLine()
Console.WriteLine("Saving settings...")
saveSettings()
Console.WriteLine("Done!")
Console.ReadLine()
End Sub
End Module
Add additional properties to SettingsClass which can be used elsewhere in your application.

Need Help Compiling DLL for Silverlight 3.0 With VBCodeProvider

I am having difficulty dynamically compiling a DLL for use with Silverlight 3.0. My goal is to take some rules provided by my users and compile them into a DLL for custom editing purposes.
I created a Silverlight class library project in Visual Studio to get the command line for compiling a Silverlight class library. Based on that and the many examples for compiling VB using the VBCodeProvider, I came up with the following method for comping code in a string to a DLL:
Public Function Compile(ByVal code As String, ByVal assemblyName As String) As CompilerResults
' set the compiler parameters
Dim parameters As CompilerParameters = New CompilerParameters()
parameters.OutputAssembly = assemblyName
parameters.GenerateInMemory = False
parameters.GenerateExecutable = False
parameters.IncludeDebugInformation = True
' constants for the silverlight assembly directories
Dim sdkDir As String = "c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v3.0\"
Dim clientDir As String = "c:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Libraries\Client\"
Dim riaDir As String = "C:\Program Files (x86)\Microsoft SDKs\RIA Services\v1.0\Libraries\Silverlight\"
' set referenced assemblies
parameters.ReferencedAssemblies.Clear()
parameters.ReferencedAssemblies.Add(sdkDir + "mscorlib.dll")
parameters.ReferencedAssemblies.Add(sdkDir + "System.Core.dll")
parameters.ReferencedAssemblies.Add(sdkDir + "system.dll")
parameters.ReferencedAssemblies.Add(sdkDir + "System.Net.dll")
parameters.ReferencedAssemblies.Add(sdkDir + "System.Windows.Browser.dll")
parameters.ReferencedAssemblies.Add(sdkDir + "System.Windows.dll")
parameters.ReferencedAssemblies.Add(sdkDir + "System.Xml.dll")
' build compiler options for sdk path to point to Silverlight.
Dim options As String
options = "/sdkpath:""" + sdkDir + "\"" "
options = options + "/define:""SILVERLIGHT=1"""
parameters.CompilerOptions = options
' compile
Dim provider = New VBCodeProvider()
Return provider.CompileAssemblyFromSource(parameters, code)
End Function
My unit test class that code as follows:
Public Sub CompileTest()
' Assemble
Dim builder As StringBuilder = New StringBuilder()
builder.AppendLine("Imports System")
builder.AppendLine("Namespace Namespace1")
builder.AppendLine("Public Class Class1")
builder.AppendLine("Public Sub Test()")
builder.AppendLine("Console.WriteLine(""Hello Compilation"")")
builder.AppendLine("Console.ReadLine()")
builder.AppendLine("End Sub")
builder.AppendLine("End Class")
builder.AppendLine("End Namespace")
Dim assemblyName As String = ".\TestAssembly.dll"
' Act
Dim compiler As SilverlightCompiler = New SilverlightCompiler()
Dim cr As CompilerResults = compiler.Compile(builder.ToString(), assemblyName)
' Assert
Assert.AreEqual(0, cr.Errors.Count)
End Sub
This does not compile with the following error:
vbc : Command line (0,0) : error BC2010: compilation failed : 'Member 'IsNumeric' cannot be found in class 'Microsoft.VisualBasic.Information'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.'
I've looked and, in fact, the Silverlight version of the class Microsoft.VisualBasic.Information does not contain member IsNumeric. So I appear to be picking up the correct libraries using the sdkpath option. But I have no idea why I'm trying to call that method in the first place.
Can anyone shed light on how to successfully compile source code dynamically into a Silverlight compatible class library? TIA.
Found the answer by getting the code provider to save the temp files it was creating. This is done my adding:
parameters.TempFiles.KeepFiles = True
to the compiler options.
When this was done, the vbc command line and the code it compiled was left behind in my user temp directory. Looking at it, I could see I was using the vbc compiler in the .Net 2.0 directory, not the 3.5 directory.
In order to get it to use the compiler in the 3.5 directory, the lines under the 'Compile comment were changed to the following:
' compile
Dim languageOptions As Dictionary(Of String, String) = New Dictionary(Of String, String)()
languageOptions("CompilerVersion") = "v3.5"
Dim provider = New VBCodeProvider(languageOptions)
Return provider.CompileAssemblyFromSource(parameters, code)
It uses an overload on the VBCodeProvider constructor that takes language options. A co-worker found this using Reflector on the T4 template engine; later I found it documented in an example here:
http://msdn.microsoft.com/en-us/library/bb470844.aspx
Once this was set properly, the code compiled.