I am getting error to use C DLL in VB.net - vb.net

I am getting error “System.DllNotFoundException: 'Unable to load DLL 'swedll32.dll': Invalid access to memory location. (Exception from HRESULT: 0x800703E6)'” while Button1.Click. That dll is a native or unmanaged dll written in C. I am using 64 bit Windows 10 and visual studio 2019.
Please help. Thanks
Public Class Form1
Public Declare Sub swe_set_ephe_path Lib "swedll32.dll" Alias "_swe_set_ephe_path#4" (ByVal path As String)
Public Shared Function swe_get_planet_name(ByVal ipl As Int32) As String
Dim Pointer As IntPtr
Dim ReturnParam As New StringBuilder(255)
Dim Result As String
Pointer = _swe_get_planet_name(ipl, ReturnParam)
Result = Marshal.PtrToStringAnsi(Pointer)
Return Result
End Function
Private Sub Button1_Click_2(sender As Object, e As EventArgs) Handles Button1.Click
swe_set_ephe_path(System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\SwEph")
End Sub
End Class

Related

file deletion exception on vb.net

My VB.NET junk cleaner cannot delete aria-Debug-10144.log since it is used by another process.
I tried this:
Imports System.Collections.ObjectModel
Imports System.IO
Public Class Form1
Dim TempDirs As ReadOnlyCollection(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TempDirs = (My.Computer.FileSystem.GetDirectories("C:\Users\Aitor\AppData\Local\Temp"))
Dim ListDirs As List(Of String) = TempDirs.ToList
Dim directoryName As String = "C:\Users\Aitor\AppData\Local\Temp"
For Each deleteFile In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
If Not deleteFile.ToString = "aria-Debug-10144.log" Then
File.Delete(deleteFile)
End If
Next
MsgBox("Clean completed!", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Results")
End Sub
End Class
But it still tries to do it.
Can anybody help me?
There are two reasons:
Firstly, the selected file is being occupied by another program. In this case, you need to determine whether the selected file is occupied before deleting it. Here is a small example.
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("kernel32.dll")>
Public Shared Function _lopen(ByVal lpPathName As String, ByVal iReadWrite As Integer) As IntPtr
End Function
<DllImport("kernel32.dll")>
Public Shared Function CloseHandle(ByVal hObject As IntPtr) As Boolean
End Function
Public Const OF_READWRITE As Integer = 2
Public Const OF_SHARE_DENY_NONE As Integer = &H40
Public Shared ReadOnly HFILE_ERROR As IntPtr = New IntPtr(-1)
Public Shared Function IsFileOccupied(ByVal filePath As String) As Boolean
Dim vHandle As IntPtr = _lopen(filePath, OF_READWRITE Or OF_SHARE_DENY_NONE)
CloseHandle(vHandle)
Return If(vHandle = HFILE_ERROR, True, False)
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If (IsFileOccupied("C:\Users\juliex\AppData\Local\Temp\aria-debug-13836.log")) Then
MessageBox.Show("File is already occupied")
Else
MessageBox.Show("File is not occupied")
'Then do some delete operation.
End If
End Sub
End Class
Secondly, the selected file is a temporary file and is currently locked. If you want to clear the temporary files it owns, you need to have full control to unlock these files and then delete them!
You should be very careful if you want to delete the TEMP file, whether it is owned by the application or by another owner. The original application may have applied the lock because it wanted to use the file!
At this time you can refer to this link below:
1.How can I unlock a file that is locked by a process in .NET
2.https://social.msdn.microsoft.com/Forums/vstudio/en-US/9e2044c5-ae5d-4552-a335-01cc567dfc58/how-to-unlock-a-file-used-by-other-process?forum=csharpgeneral

VB compilation error, expected identifier

Below is the code for a script to download a zip file from a website, but I get a compilation error that states 'expected identifier'.
Public Class DownloadAddrFile
Public Function DownloadFile(ByVal Addr As String, ByVal SaveAddrFile As String) As Boolean
Try
Dim WC As New System.Net.WebClient()
WC.DownloadFile(Addr, SaveAddrFile)
Return True
Catch ex As Exception
MessageBox.Show(ex.Message)
Return False
End Try
End Function
End Class
Call DownloadFile("http://data.gdeltproject.org/events/index.html/20171002.export.CSV.zip", "C:\Users\mwhiting\Documents\Zip_files\data.zip")
Any help on how to make this work would be great!
You can't call a method inside a Namespace.
Create an instance of Class DownloadAddrFile and for example inside a button-click call the method DownloadFile.
(The Call-keyword is usually not required)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim d As New DownloadAddrFile
d.DownloadFile("http://data.gdeltproject.org/events/index.html/20171002.export.CSV.zip", "C:\Users\mwhiting\Documents\Zip_files\data.zip")
End Sub

Replicate Windows Unhide folders and files function

I'm re-visiting a tool that I wrote in VB.Net for my helpdesk team a while back and want to add a couple of checkboxes to replicate the same function that Windows uses to show hidden files and folders / re-hide, as well as protected operating system files.
I know I can do this by editing a registry entry and restarting explorer.exe, but that closes all open Explorer Windows and I don't want that.
Does anyone know how Windows is able to do this by a simple click of a checkbox and how I may be able to code it in VB.net?
Any input on this is greatly appreciated in advance.
EDIT: So it looks like I have found a refresh method that works to refresh Windows Explorer / File Explorer which can be applied to Drarig's answer below but I am having trouble converting it to VB.net as the original example is in C#.
'Original at http://stackoverflow.com/questions/2488727/refresh-windows-explorer-in-win7
Private Sub refreshExplorer(ByVal explorerType As String)
Dim CLSID_ShellApplication As Guid = Guid.Parse("13709620-C279-11CE-A49E-444553540000")
Dim shellApplicationType As Type = Type.GetTypeFromCLSID(CLSID_ShellApplication, True)
Dim shellApplication As Object = Activator.CreateInstance(shellApplicationType)
Dim windows As Object = shellApplicationType.InvokeMember("Windows", Reflection.BindingFlags.InvokeMethod, Nothing, shellApplication, New Object() {})
Dim windowsType As Type = windows.GetType()
Dim count As Object = windowsType.InvokeMember("Count", Reflection.BindingFlags.GetProperty, Nothing, windows, Nothing)
For i As Integer = 0 To CType(count, Integer)
Dim item As Object = windowsType.InvokeMember("Item", Reflection.BindingFlags.InvokeMethod, Nothing, windows, New Object() {i})
Dim itemType As Type = item.GetType()
'Only fresh Windows explorer Windows
Dim itemName As String = CType(itemType.InvokeMember("Name", Reflection.BindingFlags.GetProperty, Nothing, item, Nothing), String)
If itemName = explorerType Then
itemType.InvokeMember("Refresh", Reflection.BindingFlags.InvokeMethod, Nothing, item, Nothing)
End If
Next
End Sub
I am getting an exception Object reference not set to an instance of an object when I set itemType as Type = item.GetType() above. I can't figure out which object isn't being created. When I step through the code it looks like windowsType contains an object for windows. Does anyone have any idea on this? Once this is worked out I can then apply it to Drarig's solution below.
Alright I wish I could have got this to you sooner, but busy lately at work. I took a little time today to figure this out as I love digging into something I have not done before. This is the whole class from a new project; didn't have time to wrap it up in a separate class. I am sure this will get you what you need. It was a little harder than I thought as getting the correct handle and then send the command, but I got it. I hope you find it useful.
P.S. Some of the things you can leave out, specifically the boolean used for loading, this was so I can pull the current value back on load and either check/uncheck the CheckBox.
Note: This is tried and tested on Windows 7, 8 and 10
Imports Microsoft.Win32
Imports System.Reflection
Imports System.Runtime.InteropServices
Public Class Form1
<Flags()> _
Public Enum KeyboardFlag As UInteger
KEYBOARDF_5 = &H74
End Enum
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetWindow(ByVal hl As Long, ByVal vm As Long) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
Private blnLoading As Boolean = False
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
Form1.HideFilesExtension(Me.CheckBox1.Checked)
If Not blnLoading Then NotifyFileAssociationChanged()
RefreshExplorer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim name As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(name, False)
blnLoading = True
Me.CheckBox1.Checked = CBool(key.GetValue("Hidden"))
key.Close()
blnLoading = False
End Sub
Private Shared Sub HideFilesExtension(ByVal Hide As Boolean)
Dim name As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(name, True)
key.SetValue("Hidden", If(Hide, 1, 0))
key.Close()
End Sub
Public Shared Sub RefreshExplorer()
Dim clsid As New Guid("13709620-C279-11CE-A49E-444553540000")
Dim typeFromCLSID As Type = Type.GetTypeFromCLSID(clsid, True)
Dim objectValue As Object = Activator.CreateInstance(typeFromCLSID)
Dim obj4 As Object = typeFromCLSID.InvokeMember("Windows", BindingFlags.InvokeMethod, Nothing, objectValue, New Object(0 - 1) {})
Dim type1 As Type = obj4.GetType
Dim obj2 As Object = type1.InvokeMember("Count", BindingFlags.GetProperty, Nothing, obj4, Nothing)
If (CInt(obj2) <> 0) Then
Dim num2 As Integer = (CInt(obj2) - 1)
Dim i As Integer = 0
Do While (i <= num2)
Dim obj5 As Object = type1.InvokeMember("Item", BindingFlags.InvokeMethod, Nothing, obj4, New Object() {i})
Dim type3 As Type = obj5.GetType
Dim str As String = CStr(type3.InvokeMember("Name", BindingFlags.GetProperty, Nothing, obj5, Nothing))
If (str = "File Explorer") Then
type3.InvokeMember("Refresh", BindingFlags.InvokeMethod, Nothing, obj5, Nothing)
End If
i += 1
Loop
End If
End Sub
Public Shared Sub NotifyFileAssociationChanged()
'Find the actual window...
Dim hwnd As IntPtr = FindWindow("Progman", "Program Manager")
'Get the window handle and refresh option...
Dim j = GetWindow(hwnd, 3)
'Finally post the message...
PostMessage(j, 256, KeyboardFlag.KEYBOARDF_5, 3)
End Sub
End Class
Here's a solution for everything excepting the refreshing of the explorer.
I've translated the code, but I'm unable to find how to refresh the explorer/desktop without restarting it.
Const keyName As String = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Const Hidden As String = "Hidden"
Const SHidden As String = "ShowSuperHidden"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim St As Integer = GetRegValue(Hidden)
If St = 2 Then
SetRegValue(Hidden, 1)
SetRegValue(SHidden, 1)
Else
SetRegValue(Hidden, 2)
SetRegValue(SHidden, 0)
End If
End Sub
Private Function GetRegValue(valueName As String) As Integer
Return CInt(My.Computer.Registry.GetValue(keyName, valueName, 0))
End Function
Private Sub SetRegValue(valueName As String, value As Integer)
My.Computer.Registry.SetValue(keyName, valueName, value, Microsoft.Win32.RegistryValueKind.DWord)
End Sub
I have a few ideas to refresh the desktop :
Send a key to a running process. I tried this (source) :
Dim pp As Process() = Process.GetProcessesByName("explorer")
If pp.Length > 0 Then
For Each p In pp
AppActivate(p.Id)
SendKeys.SendWait("{F5}")
Next
End If
Refresh using SHChangeNotify (source),
Refresh broadcasting a WM_SETTINGCHANGE message (source),
etc.
I think you'll be forced to manually refresh or restart the explorer.

VB.NET calling a WCFservice in windowsphone 7.1

I am trying to call the function getTemp(value as integer) from my webservice service1. When I execute the code it gives an error saying that _value is nothing.
If I call the same function in a normal windowsforms project it runs perfectly.
Does anyone have a solution ?
See my code below (import statements omitted):
Dim _value As String
Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
Dim client As New Service1Client
AddHandler client.GetTempCompleted, AddressOf getTempgotten
client.GetTempAsync(3)
MessageBox.Show(CStr(_value))
End Sub
Public Sub getTempgotten(sender As Object, e As GetTempCompletedEventArgs)
_value = CStr(e.Result)
End Sub
PS: I'm new to this forum, so forgive my mistakes.

How to read binary data/image from WCF REST

I have the following:
Public Interface INorthwindSvc
<OperationContract()>
<WebGet(UriTemplate:="EmployeePictureBytes?id={EmpId}")>
Function GetEmployeePictureBytesById(ByVal EmpId As String) As Byte()
End Interface
I got the method implemented (using EF 4.0) as follows:
Public Function GetEmployeePictureBytesById(ByVal EmpId As String) As Byte() Implements INorthwindSvc.GetEmployeePictureBytesById
Dim ctxt As New NorthwindEntities
Dim q = From c In ctxt.Employees
Where c.EmployeeID = EmpId
Select c.Photo
Return q.FirstOrDefault
End Function
I am able to receive bytes when I access the operation from browser. If I try to access the same using Win Client as follows (an error occurs as shown inline):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim o As New WebClient
Dim b() As Byte = o.DownloadData(New Uri("http://localhost:8732/WcfWebHttpSvcLib/rest/EmployeePictureBytes?id=2"))
Dim ms As New MemoryStream()
ms.Write(b, 0, b.Length)
Dim original As New System.Drawing.Bitmap(ms) 'error: parameter is not valid
End Sub
I also tried the same using Image.FromStream. But, still no luck.
Can anyone help me on this?
thanks
You're not rewinding the memorystream after writing to it, so trying to read from it will fail That said, even that's unnecessary, as you could just write:
im ms As New MemoryStream(b)
' now call FromStream