An unhandled exception of type 'System.AccessViolationException' occurred vb.net 2013 - vb.net

Imports Microsoft.Office.Interop
Imports System.IO
Imports Access
Public Class Form1
Dim AccessApplication As Microsoft.Office.Interop.Access.Application
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AccessApplication = New Access.Application()
If Not AccessApplication.Visible = True Then
AccessApplication.Visible = True
End If
AccessApplication.OpenCurrentDatabase("C:\POS\POS.lib", False)
End Sub
End Class
I'm trying to open "C:\POS\POS.lib" from vb.net 2013, but the error 'System.AccessViolationException' appear, I tried a lot of methods to fix it but didn't works :
the error appear on the line
AccessApplication.OpenCurrentDatabase("C:\POS\POS.lib", False)
This is the full error :
An unhandled exception of type 'System.AccessViolationException' occurred in PosStartup.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Here is the file logo:

Find the original file extension, and rename the file to have this extension before you open it, and rename it to the have "lib" extension, after you close it. Use System.Diagnostics.Process.Start to start Access in a new process. System knows to open Access, according to file extension:
If System.IO.File.Exists ("C:\POS\POS.lib") And Not System.IO.File.Exists Then ("C:\POS\POS.mdb") ' replace 'mdb' with the correct file extension
System.IO.File.Move("C:\POS\POS.lib", "C:\POS\POS.mdb")' replace 'mdb' with the correct file extension
System.Diagnostics.Process.Start("C:\POS\POS.mdb")' replace 'mdb' with the correct file extension
End If

If you have no need to manege Access from your VB.net app, remove all Office.Interop, and Access Namespaces objects, and use System.Diagnostics.Process.Start to start Access in a new process, and send the file to it as a parameter:
System.Diagnostics.Process.Start ("Access.exe", "C:\POS\POS.lib")

Rename Interop.DLL_Name.dll to DLL_Name.dll and reference it to project. Set Interop true.

Related

How do I open .jpg file in external application

So what I'm trying to do is open some images in Photoshop on the press of a button. I can get PS to launch without an issue but it just sits there waiting and does not open the file I am requesting (regardless of format (.png .jpg. bmp etc)).
I have added the Photoshop Object Library through the Add Reference Manager, but I keep getting the following error...
System.InvalidCastException: 'Unable to cast COM object of type 'Photoshop.ApplicationClass' to interface type 'Photoshop._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{5DE90358-4D0B-4FA1-BA3E-C91BBA863F32}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).'
All I'm wanting to do is open a series of image files from a listBox but I cannot even open an external image file. Any help would be much appreciated.
This is what I am trying...
Dim PSD_App As Photoshop.Application
Dim PSD_Doc As Photoshop.Document
Private Sub OpenInPS_btn_Click(sender As Object, e As EventArgs) Handles OpenInPS_btn.Click
PSD_App = New ApplicationClass
PSD_Doc = PSD_App.Open("E:\TestImageConverter\TestImage.jpg")
End Sub
Thanks for taking the time to look.
Simplest way to open a file in VB with photoshop:
Dim appRef, sampleDoc
Set appRef = CreateObject( "Photoshop.Application" )
' Switch off any dialog boxes
appRef.displayDialogs = 3
' Bring to front
appRef.BringToFront
sampleDoc = "E:/TestImageConverter/TestImage.jpg"
appRef.Open sampleDoc

Error message "Could not load type 'System.ComponentModel.AsyncCompletedEventArgs' "when running the published .exe

I've created a little VB.NET console application (using Visual Studio 2019 Commmunity Edition), that automatically downloads a file from the Internet.
The compiled .exe works just fine if I launch it from the Debug directory, inside my Project tree; it does not if I publish the application to a local folder; instead, I get the error message:
Could not load type 'System.ComponentModel.AsyncCompletedEventArgs' from assembly 'System.Net.WebHeaderCollection, Version=4.1.2.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Here's the configuration I use to publish my app:
Apparently, this is the code generating the exception:
In Program Module:
Imports System
Imports Microsoft.VisualBasic
Imports Microsoft.Win32
Module Program
Sub Main(Args() As String)
(...)
End Sub
Sub Download_SpeedTest()
Dim ooklaWebSite As String
Dim html As String
ooklaWebSite = "https://www.speedtest.net/apps/cli"
Try
' Retrieve download link
Console.WriteLine("Getting download link from " & ooklaWebSite)
html = Get_WebPage(ooklaWebSite)
(...)
Catch ex As Exception
Console.WriteLine("An error occurred downloading SpeedTest utility. - " & ex.Message)
End Try
End Sub
In WebRequests Module:
Imports System.Net
Module WebRequests
Public Function Get_WebPage(WebURL As String) As String
Dim sourceString As String
Dim wc As New System.Net.WebClient
sourceString = wc.DownloadString(WebURL)
wc.Dispose()
Return sourceString
End Function
End Module
Here's an example of what I get when I run the published program from Windows Command Line:
Getting download link from https://www.speedtest.net/apps/cli
An error occurred downloading SpeedTest utility. - Could not load type 'System.ComponentModel.AsyncCompletedEventArgs' from assembly 'System.Net.WebHeaderCollection, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
As per I could see, the exception occurs as soon the function Get_WebPage is called (no code inside it is executed)
Any suggestion?
When you use Trim unused assemblies (in preview) it sometimes removes assemblies you actually need. You can either turn that off (bloating the file size) or for this particular error, you can add the following to your csproj file:
<ItemGroup>
<TrimmerRootAssembly Include="System.ComponentModel.EventBasedAsync" />
</ItemGroup>
This will make sure that System.ComponentModel.EventBasedAsync.dll (where System.ComponentModel.AsyncCompletedEventArgs is defined) is not trimmed from the final, self-contained binary.

How can SQLAnywhere's "external CLR" access a System Process

In need of an extension in SQLAnywhere (16) to access some DOS functions on the server where the DB is running, I tried :
A first code for a DLL to be called from Sybase
________! SAExternal.vb !____________
Imports System.Diagnostics
Public Class SAExternal
Public Shared Function getDone()
Dim myProcess As Process = System.Diagnostics.Process.Start("notePad.exe", "C:\data\CLR\zTest.txt")
myProcess.WaitForExit()
myProcess.Close()
getDone = "OK"
End Function
End Class
compiled using :
vbc.exe /t:library /out:SAExt.dll SAExternal.vb
Follows some code to test my DLL
_________! SAMain.vb !______________
Module SAMain
Sub Main()
Dim obj as New SAExternal()
MsgBox("Test SAMain " & obj.getDone())
End Sub
End Module
compiled using : vbc.exe /t:winexe /r:SAExt.dll SAMain.vb
SAMain.exe opens correctly notepad.exe, waits until I close it, and comes with the message "Test SAMain OK"
In SQLAnywhere, I coded :
CREATE FUNCTION getDone()
RETURNS LONG VARCHAR
EXTERNAL NAME 'C:\data\CLR\SAExternal\SAExt.dll::SAExternal.getDone() string'
LANGUAGE CLR
Calling the function by "Select getDone()" returns an error :
"Impossible to load the file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=........' or one of it's denpendencies..."
If I take out the Process part of the SAExternal module:
Public Class SAExternal
Public Shared Function getDone()
getDone = "OK"
End Function
End Class
my function gives me the correct answer ("OK")
For test purposes, I leaved all these files in the same directory as my Database file, including .vb and .dll .
I've searched the web for days to understand what I did wrong, and can't find what I missed.
Could somebody help me ?
try
CREATE FUNCTION getDone() RETURNS LONG VARCHAR
EXTERNAL NAME 'C:\data\CLR\SAExternal\SAExt.dll::SAExternal.getDone() *out* string'
LANGUAGE CLR
Please notice the addition of the out option before string

Download a file from the web periodically

I am creating an application which on startup (MainWindow loaded) starts a BackgroundWorker, which on DoWork checks whether there is a newer version of the file (DatasSource for an Autocompletebox) available. If so, I download and merge this with the existing file and create a new file.
Now I want to do this on startup and also periodically (like 30 minutes). So I created a threading.Timer [it's a private member in MainWindow class] and initialize it in RunWorkerCompleted of the backgroundWorker (as mentioned above). The timer goes to the callback successfully but at the file download code (just a fyi, a different namespace and different class) it just terminates and I can't figure out why?
I have tried using Windows.Timers.Timer, ThreadPool.RegisterWaitForSingleObject() but no luck...
Can anyone point me to the right direction? I am open to any solution.
Download code:
Public Sub MergeHistoryFile()
/*Check the directory if there are any downloaded files(.tmp);if there are;just delete them*/
/*some code which checks if file on web is modified;if yes download file*/
Try
Dim waiter As Threading.AutoResetEvent = New AutoResetEvent(False)
_downloader = New WebClient()
AddHandler _downloader.DownloadDataCompleted, AddressOf Me.DownloaderFileCompleted
_downloader.DownloadDataAsync(New Uri(path_file), waiter)
waiter.WaitOne()
Catch ex As Exception
Throw ex
End Try
/*some more code which checks if there something new in the downloaded file;if yes merge the local and the downloaded file reinitialize the autocomplebox*/
End Sub
Private _downloadCancelled As Boolean = False
Private Sub DownloaderFileCompleted(ByVal sender As Object, ByVal e As System.Net.DownloadDataCompletedEventArgs)
If IsNothing(e.Error) Then
If Not (IsNothing(e.Result)) Then
Using fs As New FileStream(Path.Combine(HistoryPath, "_tempDownladedFile.tmp"), FileMode.CreateNew)
fs.Write(e.Result, 0, e.Result.Count)
End Using
CType(e.UserState, Threading.AutoResetEvent).Set()
End If
Else
_downloadCancelled = True
_downloader.CancelAsync()
End If
End Sub
There are several problems with this code, as I pointed out in my comment.
I think your primary problem is that when you create the file, you're passing FileMode.CreateNew, which is going to fail if the file already exists. As the documentation says:
CreateNew Specifies that the operating system should create a new file. This requires FileIOPermissionAccess.Write permission. If the file already exists, an IOException exception is thrown.
You probably want FileMode.Create.
So what happens is that the FileStream constructor throws an exception, which causes your DownloadFileCompleted method to exit without ever setting the event that tells the caller to stop waiting.

VB.net Class Not Registered Error

I'm in the process of writing a VB application but whenever I run the application I get the error listed below:
"An error occurred creating the form. See Exception.InnerException for details. The error is: Retrieving the COM class factory for component with CLSID {11219420-1768-11D1-95BE-00609797EA4F} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."
I have tried registering the shell32.dll file, I have looked in the registry for the entry {11219420-1768-11D1-95BE-00609797EA4F} but it does not exist, and I have tried compiling this application for x86.
Imports Shell32
Imports System.IO
Public Class frmIconChanger
Dim sh As ShellLinkObject = New ShellLinkObject
Private Sub btnBackupAndChange_Click(sender As Object, e As EventArgs) Handles btnBackupAndChange.Click
For Each desktopIcon In My.Computer.FileSystem.GetFiles("C:\Users\" + getUserName().ToString + "\Desktop")
Dim fileExtension As String = Path.GetExtension(desktopIcon)
If (fileExtension = ".lnk") Then
MsgBox(sh.GetIconLocation(desktopIcon).ToString)
End If
Next
End Sub
Private Function getUserName() As String
Return System.Environment.UserName.Trim
End Function
End Class
Other information: I am on a Windows 7 64-bit machine. I have .Net 4.0 and previous versions and am working in Visual Studio 2012. Also I have shell32.dll added as a reference in my project. Any help resolving this issue would be much appreciated.
Thanks.
Refer to this link Creating Links. Take a look at the "C" code and look for constants
CLSID_ShellLink
IID_IShellLink
Those are the values you need for the class and interface.
This other link is useful: IShellLink interface
This should be the GUIDs you need:
CLSID := "{00021401-0000-0000-C000-000000000046}"
IID := "{000214F9-0000-0000-C000-000000000046}"