extract my.setting.whatever from another exe - vb.net

Ussing vb.net I extract an image from another exe using the following code.
My question is, is it also possible to extract a setting value from another exe using a simular method?
Try
Dim ExternalAssembly As Assembly = Assembly.LoadFile(Application.StartupPath & "/" & PluginPath)
Dim TargetPlugin As String = IO.Path.GetFileNameWithoutExtension(Application.StartupPath & "/" & PluginPath)
Dim ExternalResourceManager As Resources.ResourceManager
ExternalResourceManager = New Resources.ResourceManager(TargetPlugin & ".resources", ExternalAssembly)
If ExternalResourceManager.GetObject("MyStringRefrenceName") = Nothing Then
.Image = My.Resources.ResourceManager.GetString("MyStringRefrenceName").testing 'or is it value?
Msgbox(MyStringRefrenceName)
End If
Catch ex As Exception
Msgbox("failed")
End Try

Related

Vb.net problems download

How can I do a check that first download something and only after that it starts up the program.exe?
I already tried to do something like this but it excutes the file when the download is not finished and it throws some errors.
my Code:
Dim client As WebClient = New WebClient
Dim SourcePath As String = "C:\ProgramData\KDetector\UserAssistView.exe"
Dim SaveDirectory As String = "C:\ProgramData\KDetector"
Dim FileName As String = System.IO.Path.GetFileName(SourcePath)
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, FileName)
If System.IO.File.Exists(SavePath) Then
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
Else
client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"), "C:\ProgramData\KDetector\")
Process.Start("C:\ProgramData\KDetector\UserAssistView.exe")
End If
You are calling the asynchronous DownloadFile method. Asynchronous method will not block the calling thread.
In order to avoid the problem, your code must be like this:
Dim downloadLink As String = "http://www.nirsoft.net/utils/userassistview.zip"
Dim saveFilePath As String = "C:\ProgramData\KDetector\userassistvkew.zip"
Dim fileName As String = Path.GetFileNameWithoutExtension(saveFilePath)
Dim client As WebClient = New WebClient
Try
CheckExsist(saveFilePath, fileName)
'Before was client.DownloadFileAsync(New Uri("http://ge.tt/70n8YPr2"))
client.DownloadFile(downloadLink, saveFilePath)
MsgBox("Download file completed. File saved in: " & saveFilePath)
'Zip extraction stuff
Catch ex As Exception
MsgBox(ex.Message)
End Try
This is the CheckExsist sub:
Private Sub CheckExsist(ByRef sourcePath As String, ByVal fileName As String, Optional ByVal counter As Integer = 1)
If System.IO.File.Exists(sourcePath) Then
sourcePath = sourcePath.Replace(Path.GetFileName(sourcePath), "") & fileName & "(" & counter & ")" & Path.GetExtension(sourcePath)
counter += 1
CheckExsist(sourcePath, fileName, counter)
End If
End Sub
I manage to download the software (from the official website) and save it as a .zip. Code the last few rows to programmatically extract the .zip, if you ecounter any problem or bug feel free to ask with another question. Anyways there are alot of post on SO regarding zip extraction on vb.net

saving multiple image to local folder using its default filename in vb.net

I was trying to save multiple image to a local folder in one go in vb. Right now, i am able to save one image at a time to a specified folder. In my code, i have set up a file name for the image to use when uploaded. What I needed is to save the image with it's original file name and file type. My program should also allow user to save multiple images in one go.
I am Using VB 2013 Ultimate
this is the code for searching.
Try
a.Filter = "Image files | *.*"
If a.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(a.FileName)
PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
and this is my code for saving
If (Not System.IO.Directory.Exists("d:/Site Images/" & Label33.Text & "/")) Then
System.IO.Directory.CreateDirectory("d:/Site Images/" & Label33.Text & "/")
End If
'Dim address = ("d:/Site Images/" & a.FileName & ".jpg")
PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" & "a.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
thanks for the help.
A sample snippet
Dim a As New OpenFileDialog
a.Filter = "Jpeg Files|*.jpg"
a.ShowDialog()
For i As Integer = 0 To a.FileNames.Count - 1
Try
Dim img As Image = Image.FromFile(a.FileNames(i))
img.Save("Your Saving Path")
Catch ex As Exception
End Try
Next

Trying to create a function

So I'm trying to change this sub in to a function so that I can reference it and set a label.text as it's result, this is so I don't have to creating new subs to update different labels.
Dim drive As String = "C"
Dim disk As ManagementObject = _
New ManagementObject _
("win32_logicaldisk.deviceid=""" + drive + ":""")
disk.Get()
Dim serial As String = disk("VolumeSerialNumber").ToString()
Label1.Text = ("Serial: " & serial)
Can someone tell me how I can change this in to a function? I've tried declaring Serial as an empty String and then changing the last line to read:
Return serial = disk("VolumeSerialNumber").ToString()
At the moment this just sets Label1.Text to display "False", like I've set it as a Boolean or something?!
I'm learning functions at the moment, I'm trying to make things cleaner as up until now I've just been creating different subs to update labels etc...
I'm looking for some tips so I can try and get this myself.
It is really a simple refactoring operation.
Sub Main
Dim driveLetter = "X"
Try
Dim result = DriveSerialNumber(driveLetter)
Console.WriteLine(result)
Catch ex as Exception
Console.WriteLine("Error: drive " & driveLetter & ": " & ex.Message)
End Try
End Sub
Public Function DriveSerialNumber(drive as String) As String
Dim disk As ManagementObject = _
New ManagementObject _
("win32_logicaldisk.deviceid=""" + drive + ":""")
disk.Get()
return disk("VolumeSerialNumber").ToString()
End Function
However, be prepared to receive Exceptions if you pass an invalid drive letter

DirectoryNotFoundException was unhandled

I'm trying to make a new file and write binary in it but the below error occurred
Could not find a part of the path 'C:\Users\user\Documents...\bin\Debug\data\binary\admin.bin'.
Here is my code
Dim bw As BinaryWriter
dim pathBin As String = Application.StartupPath & "\binary"
Dim fileExist As Boolean
Try
bw = New BinaryWriter(New FileStream(pathBin & "\admin.bin", FileMode.create))
fileExist = True
Catch ex As IOException
MessageBox.Show(ex.Message & vbNewLine & "Cannot create file.")
End Try
bw.Close()
Your issue is the path you are using does not exist which will make FileStream quite upset. Try something like this before you use the FileStream:
If Not Directory.Exists(pathBin) Then
Directory.CreateDirectory(pathBin)
End If
This will ensure that if the directory does not exist then it is created ahead of time.

Problems reading an Excel file in VB.net

I have been trying to upload and read an Excel file (.xls, or .xlsx)
I am upploading sucessfully using this code:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
Dim filename As String = FileUpload1.PostedFile.FileName
Dim extension = (filename.Substring(filename.LastIndexOf("."), (filename.Length() - filename.LastIndexOf("."))))
If extension = ".xlsx" Or extension = ".xls" Then
filepath = "\" & Common.toUnix(Now) & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
' ==== NOW READ THE FILE
Else
StatusLabel.InnerText = "Only Excel file types are accepted (.xls/.xlsx)<br> File Uploaded had extension: " & extension
End If
Catch ex As Exception
StatusLabel.InnerText = "Upload status: The file could not be uploaded. The following error occured: " + ex.ToString()
End Try
End If
End Sub
It uploads OK, but when trying to read the file I get this error:
System.Data.OleDb.OleDbException (0x80004005): The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.
I am using code to read similar to this:
vb.net traversing an xls / xlsx file?
Therefore the connection is as follows:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _
";Data Source=" & ExcelFile & _
";Extended Properties=Excel 8.0;"
Dim conn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Dim excelDataSet As New DataSet()
Try
conn = New OleDbConnection(connString)
conn.Open() '<<< ERROR IS RAISED ON THIS LINE
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets(dt.Rows.Count) As String
Dim i As Integer = 0
For Each row As DataRow In dt.Rows
excelSheets(i) = row("payments").ToString
System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
If i = SheetNumber Then
Exit For
End If
Next
..................
I'm uploading to a shared server so don't have control as to permissions as such, but I do have read/write permissions and uploading Images works OK, but it's reading this file that I can't get to work.
NOTE
This error occurs with .xls files, when using .xlsx I get this error:
System.Data.OleDb.OleDbException (0x80004005): Cannot update. Database or object is read-only. at System.Data.OleDb.OleDbConnectionInternal
This error occurs on this line:
For Each row As DataRow In dt.Rows
So it appears it is uplpoading and opening the file OK, but not reading the rows....
I am not sure why that's happening either!
Any help would be much appreciated!
ACE is brutal, have troubles with it all the time and it cannot exist on a System in both 32 and 64 bit version at the same time. As a result I just dont use it at all.
To read an Excel XLSX file I use "EPPlus" which has proven to be very easy to deal with and extreamly efficient.
It ONLY works with XLSX (not XLS)
Example... (simple just pulls out first sheet as a datatable)
Public Function XlsxToDataTable(byteStream As IO.MemoryStream) As DataTable
Using pac As New OfficeOpenXml.ExcelPackage(byteStream)
Dim wb As OfficeOpenXml.ExcelWorkbook = pac.Workbook
Dim ws As OfficeOpenXml.ExcelWorksheet = wb.Worksheets(1) '1 based
Dim out As New DataTable
For iC As Integer = 1 To ws.Dimension.End.Column
out.Columns.Add(ws.Cells(1, iC).Value.ToString)
Next
For iR As Integer = 2 To ws.Dimension.End.Row
Dim nr As DataRow = out.NewRow
For iC As Integer = 1 To ws.Dimension.End.Column
nr(iC - 1) = ws.Cells(iR, iC).Value
Next
out.Rows.Add(nr)
Next
Return out
End Using
End Function