Using Visual basic 2017 to navigate to a esp8266 wifi switch (Sonoff) - vb.net

I am using the below code to navigate to a specific web address as follows :
WebBrowser1.Navigate("http://192.168.0.157/cm?cmnd=POWER%20Toggle"
The fact is that the the link returns a .json file and the WebBrowser controls displays the default save file dialog asking if i want to save the file or run it.
I want to ignore it the dialog and read from the .json file directly(i mean after downloading it).
I just want to get rid of the Save dialog of the webbrowser.I am a newbie so i don't know what to search or how to ask properly.

Though your post is not even close to be standard and hardly explains the issue, what i understand so far is that you have a few issues and i will answer them separately.
Disabling the download dialog of the webbrowser and downloading the files automatically
Firstly, you mentioned it returns a .json file. So , you can easily add a SaveFileDialogto your form or set a custom path(maybe in a variable) and check if the webbrowser is trying to download any .json files. Then you will Cancel the call(typically i mean that cancel the popup that says Save , Run ...) and make use of the SaveFileDialog or the local variable to save the file directly to disk. Here's a sample which uses a local string variable as the path and saves the .json file directly to disk :
Imports System.ComponentModel
...
Dim filepath As String '''class lever variable
Private Sub myBroswer_Navigating(sender as Object, e As WebBrowserNavigatingEventArgs) Handles myBroswer.Navigating
If e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".json") Then
e.Cancel = True
filepath = "C:\test\" + e.Url.Segments(e.Url.Segments.Length - 1)
Dim client As WebClient = New WebClient()
AddHandler client.DownloadFileCompleted , AddressOf New AsyncCompletedEventHandler(DisplayJson);
client.DownloadFileAsync(e.Url, filepath)
End If
End Sub
Displaying the result AKA .json
It is very easy to de-serialize/parse .json files.But first, download this , extract the ZIP and Add Reference to Newtonsoft.Json.dll. Now consider the bellow code snippet :
Private Sub DisplayJson()
Dim parseJson = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllLines(filepath))
MsgBox(parseJson("element name here").ToString)
End sub
Hope this helps

Related

Exe working only if started manually but I want it to start automatically

I have done a simple VB application with this code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim procName As String = Process.GetCurrentProcess().ProcessName
Dim processes As Process() = Process.GetProcessesByName(procName)
If processes.Length > 1 Then
Process.GetProcessesByName("keyinput")(0).Kill()
End If
End Sub
Public Sub type(ByVal int As Double, str As String)
For Each c As Char In str
SendKeys.Send(c)
System.Threading.Thread.Sleep(int * 1000)
Next
End Sub
Sub vai()
Dim line As String = ""
If File.Exists("trans.txt") Then
Using reader As New StreamReader("trans.txt")
Do While reader.Peek <> -1
line = reader.ReadLine()
type(0.155, line)
'SendKeys.Send(line)
SendKeys.Send("{ENTER}")
Loop
End Using
File.Delete("trans.txt")
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
vai()
End Sub
Basically the timer in it check if a file exists, read it and type the content simulating the keyboard.
I want this exe to start automatically when user login, it does it, apparently, I can see the form1 pop up but doesn't really works. Everyting is fine only if I run it manually by double-clicking the icon. Why and what can I do? Thanks
ps. i already tried to execute it with windows task manager, or putting a shortcut in the windows startup folder, or calling it from a cmd
EDIT:
when app starts automatically , process is running, but windows form is showing like this
Instead starting manually is showing like this:
I don't know this for a fact but I suspect that the issue is the fact that you are not specifying the location of the file. If you provide only the file name then it is assumed to be in the application's current directory. That current directory is often the folder that the EXE is in but it is not always and it can change. DO NOT rely on the current directory being any particular folder. ALWAYS specify the path of a file. If the file is in the program folder then specify that:
Dim filePath = Path.Combine(Application.StartupPath, "trans.txt")
If File.Exists(filePath) Then
Using reader As New StreamReader(filePath)
EDIT:
If you are running the application at startup by adding a shortcut to the user's Startup folder then, just like any other shortcut, you can set the working directory there. If you haven't set the then the current directory will not be the application folder and thus a file identified only by name will not be assumed to be in that folder.
If you are starting the app that way (which you should have told us in the question) then either set the working directory of the shortcut (which is years-old Windows functionality and nothing to do with VB.NET) or do as I already suggested and specify the full path when referring to the file in code. Better yet, do both. As I already said, DO NOT rely on the current directory being any particular folder, with this being a perfect example of why, but it still doesn't hurt to set the current directory anyway if you have the opportunity.
It was a Windows task scheduler fault, that for some reason didn't executed the exe correctly at logon. I've solved the issue by using Task Till Down and everything works fine now.

Files not opening as read-only in VB.NET when read-only attribute set

I'm having trouble with a bit of code designed to intentionally open files as read-only. My team often needs to be able to peek into each others' files without locking the file owner out, so in a form being designed for document management I want users to be able to open files optionally as read-only.
Coming from VBA I'm still somewhat new to VB.NET and also bitwise operations generally, but I believe the "read-only" interpretation of this code from MS Docs has been correctly implemented:
Dim attributes As FileAttributes
attributes = File.GetAttributes(path)
If Not (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
' Make file readonly.
File.SetAttributes(path, File.GetAttributes(path) Or FileAttributes.ReadOnly)
End If
' Open the file
System.Diagnostics.Process.Start(path)
' Reset the file to read/write.
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
File.SetAttributes(path, attributes)
When I use "GetAttributes" before and after the line to open the file I get a return of 1 or sometimes as 33, which the FileAttributes enumeration documentation suggests is correct for what I'm trying to do. Before and after the attribute change "GetAttributes" returns 128 or in certain cases 32, which also should be correct.
However despite the fact the above code appears correctly implemented and seems to be producing the correct affect in the file's attributes, files opened this way (namely Excel files) open as read-write. I'm also fine with other ways of opening a file read-only provided that it can be used equally well on any document you would commonly encounter in an office setting (Excel, Word, etc.) with its default program. That being said, I've tried several methods and haven't had any success, and this one by far has seemed the cleanest and most promising.
Thanks in advance!
As described in comments, the file attributes are restored to their
previous state right after the Process.Start() command: the
application that opens the file has not been started yet; when it
finally access the file, the read-ony attribute has already been
removed.
A possible solution is to subscribe to the Process.Exited event and restore the original file attributes when the Process termination is notified.
A modified version of your code: the EnableRaisingEvents property causes a process to raise the Process.Exited event. I subscribed to the event using an in-line delegate (a Lambda), but I added an example that uses a standard delegate method using the AddressOf operator (since you said you have to learn about events).
Since we want to run a file and not an executable, we need to also set UseShellExecute = True, so the Shell will find and execute the registered application associated with the file extension.
If UseShellExecute = True is not specified, an exception is raised (the file is not an executable).
The name of the file to execute is assigned to the Process.StartInfo.FileName
When the Process terminates, the Exited event is raised. In the event handler, the file attributes are restored to the previous state.
Private Sub SomeMethod(filePath As String)
' filePath is File's Full path
Dim attributes As FileAttributes = File.GetAttributes(filePath)
File.SetAttributes(filePath, (attributes) Or FileAttributes.ReadOnly)
Dim proc As Process = New Process()
proc.StartInfo.FileName = filePath
proc.StartInfo.UseShellExecute = True
proc.EnableRaisingEvents = True
AddHandler proc.Exited,
Sub()
File.SetAttributes(filePath, attributes)
proc?.Dispose()
End Sub
proc.Start()
End Sub
If you want to use a standard method as the Exited event handler, you have to declare the filePath and attributes variables in a different scope. Neither can be a local variable, they won't be accessible from the method delegate.
If you need to run just one file, these can be instance fields (declared in the scope of the current class).
If you instead can have multiple processes running different files, all waiting for the associated applicationt to terminate, these informations should to be stored in a list of objects, a Dictionary or a similar container.
For example, using a Dictionary, declared as a Field:
(the Dictionary Key is the File path. If a file can be opened multiple times - a .txt file maybe, use a different identifier)
Private myRunningFiles As New Dictionary(Of String, FileAttributes)
' (...)
Private Sub SomeMethod(filePath As String)
Dim attributes As FileAttributes = File.GetAttributes(filePath)
If Not myRunningFiles.ContainsKey(filePath) Then
myRunningFiles.Add(filePath, attributes)
Else
' Notify that the file is already opened
Return
End If
Dim proc As Process = New Process()
' (... same ...)
AddHandler proc.Exited, AddressOf OnProcessExited
End Sub
Protected Sub OnProcessExited(sender As Object, e As EventArgs)
Dim proc = DirectCast(sender, Process)
Dim filePath = proc.StartInfo.FileName
Dim attributes = myRunningFiles(filePath)
File.SetAttributes(filePath, attributes)
myRunningFiles.Remove(filePath)
proc?.Dispose()
End Sub
Thanks to #Jimi I was able to come up with the solution. In my application Excel files are the most important to open in ReadOnly so I'm happy with an Excel-only solution for the time being. While his answer for using and releasing attributes was great it had the problem of not restoring the attributes to their default until the file is closed, which to my understanding would cause others to also open the file ReadOnly while the file is open. The point of this in my application is to "peek" at a file without locking other users on a network out of ReadWrite access, so unfortunately his-well-thought out solution won't work.
I was however able to use the /r switch with a bit of investigating. It was a bit tricky (for someone of my skill level) since some switches need to be placed before the file path and some after. Solution below:
Process.Start("EXCEL.exe", "/r " & Chr(34) & path & Chr(34))

Unable to open network PDF file from embedded link inside another PDF

I use a small program to open a main PDF file used by multiple employees. If open the given file on the Network (without using the program) and select the hyperlink inside the PDF, it will open correctly.
However, when I run my program to open that given file and try to select the hyperlink inside the PDF, I receive a "Security Block" error:
The control I am using to display the PDF on the program is:
And I use the following code to load the PDF file:
Private Sub UpdateFile()
Dim fileList As IEnumerable(Of String) = Directory.GetFiles(DrawingsRootDirectory, "*.PDF", SearchOption.TopDirectoryOnly)
Me.AxAcroPDF1.LoadFile(fileList.Last)
Me.AxAcroPDF1.Refresh()
Me.WindowState = FormWindowState.Maximized
End Sub
I'm not quite sure why opening the PDF file via a program would prevent it from using the hyperlinks inside that given file. Any ideas?

Cannot set OpenFileDialog initial directory to Downloads in visual basic [duplicate]

This question already has an answer here:
How to reference the current Windows user's video folder path in VB.net
(1 answer)
Closed 6 years ago.
I am trying to set the initial directory to the downloads folder but it doesn't work, Even though it's a perfectly valid path. Here is the code that I am using:
Private Sub btn_AddMod_Click(sender As Object, e As EventArgs) Handles btn_AddMod.Click 'This brings up the file dailoge
Dim Downloads As String = "\Downloads" 'A variables called \Downloads
Dim UserprofilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) 'This finds the directory to the User profile environment variable
Dim Downloadspath As String = UserprofilePath.Insert(0, "") + Downloads 'This adds \downloads to userpath
OpenFileDialog1.InitialDirectory = Downloadspath 'This sets the Open File Dialog to go to the users downloads
txt_setmodname.Text = Downloadspath 'This is used for debugging, it sets a textbox to the path
OpenFileDialog1.ShowDialog() 'This opens the Dialog
End Sub
When I copy the output text, the path is perfectly valid but instead of taking me to the path, it takes me to MyDocuments
That's some wacky code you have there. I'm not sure why it doesn't work and I'm not too interested in finding out. I just tested this and it worked as you want:
Using ofd As New OpenFileDialog
ofd.InitialDirectory = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads")
ofd.ShowDialog()
End Using
Obviously you can use an OpenFielDialog that you created in the designer instead of created in code if you want.
By the way, it should be noted that the user's Downloads folder is not necessarily in that location. Mine is on my D: drive, while my personal folder is on my C: drive. For people who keep C: only for system files, all their libraries and the like may be on a secondary drive. Unfortunately, there's no easy way to get the path for the Downloads folder like there is for Documents and some others. I'm guessing that the path is stored in the Registry or the like, but I'm not sure where.
I looked further into it and found out that there is a registry entry for the downloads path, so I used that instead and that seemed to have worked, My code is as follows.
Private Sub btn_AddMod_Click(sender As Object, e As EventArgs) Handles btn_AddMod.Click
Using ofd As New OpenFileDialog
Dim DownloadsPath = My.Computer.Registry.GetValue(
"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\", "{374DE290-123F-4565-9164-39C4925E467B}", Nothing)
ofd.InitialDirectory = DownloadsPath
ofd.ShowDialog()
End Using
I'm not sure why the other method didn't work, it always took me to the MyDocuments folder for some reason.

How do I extract from a password protected zip file using VBA?

I have been struggling with this problem for quite some time now, and have trawled through various forums trying to find an answer.
I have a mailbox which received 5 emails each morning which have zipped, password-protected .csv files which require opening and processing in Excel. I am semi-competent in VBA so the Excel side of things is no issue, but it would save me a lot of time if I could automatically unzip these files and save them to a folder.
These emails have the same subjects, attachments and passwords each day, and are from the same sender to the same mailbox. I have code which can automatically process and save the .zip files to a location, but I am still stuck with the problem of having to go into each one, enter the password, open the file, save it, etc.
I have refrained from attaching this code because I would like to see if there are better solutions to my one, and it is the unzipping and password entering that I really need help with. This being said if you would like me to attach my code I will be happy to do so :)
To expand my comment, no input is required - the password is obtained via an event so can be provided in code.
Download the demo project and DLL
In the outlook VBA editor, right click the Project in the tree, Import File and add
cUnzip.cls
mUnzip.bas
Put the DLL in \System32 (or \SysWoW64 on 64bit)
As a naive example, add a new class cWhatever:
Private WithEvents Unzip As cUnzip
Private Sub Class_Initialize()
Set Unzip = New cUnzip
End Sub
Sub RunUnzip()
With Unzip
.ZipFile = "c:\blah\qqq.zip"
.UnzipFolder = "c:\temp"
.Unzip
End With
End Sub
Private Sub Unzip_PasswordRequest(sPassword As String, bCancel As Boolean)
sPassword = "password123"
End Sub
Then to run from elsewhere:
Dim x As New cWhatever
x.RunUnzip
First time you run there is an error highlighting App.EXEName, just delete the App.EXEName &