How do I reload a block of code on a timer? VB.net - vb.net

Good afternoon.
I've got a program that requests weather from Yahoo! weather which works. However what I want to do is reload the block of code that requests the information.
It's part of a radio station - studio clock, so using a scheduled task to close & then reopen the application isn't a runner.
It only requests the information once, when the .exe file is loaded.
How do I do this with a timer perhaps? Every 15 minutes would be good.
Here's the code I've got - not my own code by the way, found online!
Sub GetWeatherReport(ByVal locationId As Integer)
Me.Text = strLocations(locationId)
Dim doc As New XPathDocument("http://weather.yahooapis.com/forecastrss?w=" & strLocationID(locationId) & "&u=c")
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim ns As New XmlNamespaceManager(nav.NameTable)
ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0")
Dim nodes As XPathNodeIterator = nav.[Select]("/rss/channel/item/yweather:condition", ns)
While (nodes.MoveNext())
Dim node As XPathNavigator = nodes.Current
lblTemp.Text = node.GetAttribute("temp", ns.DefaultNamespace).ToString() & "°C " + node.GetAttribute("text", ns.DefaultNamespace).ToString()
)
weatherImage.ImageLocation = "http://l.yimg.com/a/i/us/we/52/" & node.GetAttribute("code", ns.DefaultNamespace).ToString() & ".gif"
End While
Thanks!

Related

Do...Loop starts too quickly, how to brake it?

With my program, user have to download and save csv files to two different specific directories. Unfortunately automatic downloading not possible. To download file I use command WebBrowser1.Navigate(url), which run php script on the target web page and after one second webBrowser ask path where I or user want to download file. After that again button click and .Navigate to download second one.
But I have to be sure, that user had download file exactly to the specific directory and first, I want to check if file exists there. And here problems are starts. Because of small delay before "Save" possibility, program run immediately Do...Loop process and "Save" window doesn't even come. Also I tried to use thread.sleep, but it doesn't help. Because it immediately go to sleep and "save" window have not time to present. After sleep it immediately starts Do...Loop process.
Is here some other instruments to say to my program, that it wait a little and continue to run code after user "Save" file?
Here is My code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim kraporttila As String
Dim dt1 As Date = DateTimePicker1.Value
Dim dt2 As Date = DateTimePicker2.Value
Dim faa As String = dt1.ToString("yyyy-MM-dd")
Dim fla As String = dt2.ToString("yyyy-MM-dd")
Dim ddla As String = dt2.ToString("MM.yy")
Dim kuitti As Uri = New Uri("https:url/kuitti.php?faa=" & faa & "&fla=" & fla & "&fk_e=&fa_e=&fm=&ftil=&kuittiexportcsv=Lataa%CSV")
WebBrowser1.Navigate(kuitti)
Button2.Visible = False
Do While
If System.IO.File.Exists(kraporttila) = True Then
Button3.Text = "Lataa maksuvirheet"
Button3.Visible = True
Label3.Text = "Nyt lataa maksuviheet ja tellenna kansioon ""C:\Users\Ivan\" & ddla & "\Laskutukset ja Maksuvirheet\Maksuvirheet"""
Exit Do
Else
Continue Do
End If
Loop
End Sub

Memory files get trashed by third party software

I have an collection of apps that rely on memory files. I create them with a persistent app, then 3 apps update the files with GPS, IMU and switch data, and 3 apps read the current status and generate commands to servo controllers. This has worked fine for years, but today the apps failed due to missing memory files when I started a third party c# camera control app.
I suspect the other app overwrites the memory area. Is there a way to protect these memory files.
I am in Visual Studio 2017, Win10/64 and .net 4.6.1
I have included the create and sample read and write code - all of which have worked for years. I did update the system to current .net 4.6.1, and without the 3rd party app the system runs for hours without error. The instant I start the c# app compiled app the memory files disappear. I do not have access to the source, and am hopeless with C#.
Not a clue now, one solution is to install a new CPU and run the 3rd partys app on a separate box. There is no communication between my apps and it.
I create with :
Dim LoopForever As Boolean = True
Dim AHRS_Memory_File_Name As String = "AHRSMemoryData"
Dim GPS_Memory_File_Name As String = "GPSMemoryData"
Dim Switch_Memory_File_Name As String = "SwitchMemoryData"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim MMS = MemoryMappedFile.CreateNew(Switch_Memory_File_Name, 20,
MemoryMappedFileAccess.ReadWrite)
Dim GPS = MemoryMappedFile.CreateNew(GPS_Memory_File_Name, 200,
MemoryMappedFileAccess.ReadWrite)
Dim AHRS = MemoryMappedFile.CreateNew(AHRS_Memory_File_Name, 200,
MemoryMappedFileAccess.ReadWrite)
Do Until LoopForever = False
Thread.Sleep(10000)
Loop
End Sub
A sample Write is
Sub WriteGPS_To_Memory()
Dim GPS_MMF = MemoryMappedFile.OpenExisting(GPS_Memory_File_Name)
Dim Bytes As Byte()
' This is the format of the current gps memory message
outMessage = GPSSpeedIn & "," & GPSBearing & "," & GPSLongitude & ","
& GPSLatitude & "," & GarminMagDeviationText & "," & GPSMessageCount
& "," & GPSAltitude & ","
Bytes = StrToByteArray(outMessage)
Try
Using writer = GPS_MMF.CreateViewAccessor(0, Bytes.Length)
writer.WriteArray(Of Byte)(0, Bytes, 0, Bytes.Length)
' writer.Dispose()
End Using
Catch ex As Exception
MsgBox("mem write error = " & ex.ToString)
End Try
And a sample read is
Dim MMF = MemoryMappedFile.OpenExisting(MEMS_Memory_File_Name)
Using reader = MMF.CreateViewAccessor(0, 200,
MemoryMappedFileAccess.Read)
Dim NewByteString = New Byte(200) {}
reader.ReadArray(Of Byte)(0, NewByteString, 0,
NewByteString.Length)
InMessage = Convert.ToString(NewByteString)
teststring = ""
CycleCount = CycleCount + 1
teststring = BitConverter.ToString(NewByteString)
For i As Integer = 0 To NewByteString.Length - 1
AHRS_CommDataIn =
System.Text.Encoding.ASCII.GetString(NewByteString)
Next
End Using
MMF.Dispose()
Best outcome is to find a way to protect these files. I am in the US, the vendor is in Israel and not particularly responsive.
There is time pressure on this as my company uses this software to locate water bodies producing mosquitoes (hate those pests) which distribute West Nile Virus, Denge and Malaria. Today we scrubbed a 300 sq mi mission affecting about 500K persons.
The issue was apparently in the third party software - they issued a updated program the day we posted the issue to their support site - so we must not have been to only site with this issue

Can't Multi Download With WebClient

I know this question has been asked before, but I have a special way I want to download the files through a webclient, I want to download each file at a time through a Do While statement, but it just adds the file to download and moves on to the next task that also downloads another file so it cancels each other out and crashes the application.
Private Function StartDownloads()
Dim wc As New WebClient
AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
Dim delimiterChars As Char() = {"+"c}
Dim words As String() = RichTextBox1.Text.Split(delimiterChars)
Dim i As Integer = 1
Do While (i < words.Length)
Dim delimiterChars1 As Char() = {"|"c}
Dim words1 As String() = words(i).Split(delimiterChars1)
Dim name As String = words1(0)
Dim fileurl As String = words1(2)
ToolStripStatusLabel1.Text = "Downloading " & name & ":"
wc.DownloadFileAsync(New System.Uri(fileurl), Path.GetTempPath() & "\" & name)
i = (i + 1)
Loop
End Function
AND
Private Sub DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
ProgressBar1.Value = e.ProgressPercentage
ToolStripStatusLabel2.Text = String.Format("{0} MB's / {1} MB's",
(e.BytesReceived / 1024D / 1024D).ToString("0.00"),
(e.TotalBytesToReceive / 1024D / 1024D).ToString("0.00"))
End Sub
So basically in the Do While statement it starts the download then continues without waiting for the download to finish and then downloads both at once, which then crashes the program/interferes with the labels displaying the download name, the reason this is a different question from others is I need it to specify the download name as I can't do with other tutorials, by adding the downloads to a list...
So if anyone can help me make the Do While statement wait for the download to finish then continue with the next without loosing the file name and stuff like that, please give me some tips, thanks!
I know that DownloadFile waits for the download to finish then continues, but I need it to show download progress and download bytes and stuff like that...
P.S. Sorry if this is confusing as it's hard to explain, thanks.
By adding await wc.DownloadFileTaskAsync(...), it worked perfectly

VB.net loading out of date webpages

I use the following code to copy a certain line of text from the website listed.
'Track A
Dim TrackA As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("https://pilotweb.nas.faa.gov/common/nat.html")
Dim GaA As System.Net.HttpWebResponse = TrackA.GetResponse
Dim WrA As System.IO.StreamReader = New System.IO.StreamReader(GaA.GetResponseStream)
Dim ContentStrA As String = WrA.ReadToEnd
Dim StartIndexA As Integer = ContentStrA.IndexOf(vbLf & "A ") + 1
Dim StrLengthA As Integer = ContentStrA.IndexOf(vbLf, StartIndexA) - StartIndexA
However when I open the link in a tab in VB, it shows a version of the site from a few days ago, how do I prevent this from happening as I need the current version of the site?
Change the Cache Policy of your System.Net.HttpWebRequest object, so that you're not getting cached results.
Alternatively, you can clear the cache for your URL.

VB.Net: How To Display Previous Shadow Copy Versions of File Allowing User to Choose One

I'm writing an Excel file recovery program with VB.Net that tries to be a convenient place to gather and access Microsoft's recommended methods. If your interested in my probably kludgy, error filled, and lacking enough cleanup code it's here: http://pastebin.com/v4GgDteY. The basic functionality seems to work although I haven't tested graph macro table recovery yet.
It occurred to me that Vista and Windows 7 users could benefit from being offered a list of previous versions of the file within my application if the Shadow Copy Service is on and there are previous copies. How do I do this?
I looked at a lot of web pages but found no easy to crib code. One possibility I guess would be to use vssadmin via the shell but that is pretty cumbersome. I just want to display a dialogue box like the Previous Versions property sheet and allow users to pick one of the previous versions. I guess I could just display the previous version property sheet via the shell by programmatically invoking the context menu and the "Restore previous versions choice", however I also want to be able to offer the list for Vista Home Basic and Premium Users who don't have access to that tab even though apparently the previous versions still exist. Additionally if it possible I would like to offer XP users the same functionality although I'm pretty sure with XP only the System files are in the shadow copies.
I looked at MSDN on the Shadow Copy Service and went through all the pages, I also looked at AlphaVSS and AlphaFS and all the comments. I'm kind of guessing that I need to use AlphaVss and AlphFS and do the following?
Find out the list of snapshots/restore points that exist on the computer.
Mount those snapshots.
Navigate in the mounted volumes to the Excel file the user wants to recover and make a list of those paths.
With the list of paths handy, compare with some kind of diff program, the shadow copies of the files with the original.
Pull out the youngest or oldest version (I don't think it matters) of those shadow copies that differ from the recovery target.
List those versions of the files that are found to be different.
This seems cumbersome and slow, but maybe is the fastest way to do things. I just need some confirmation that is the way to go now.
I finally decided to go ahead and start coding. Please make suggestions for speeding up the code or what do with files that are found to be different from the recovery file target. Is there a simpler way to do this with AlphaVSS and AlphaFS?
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Find out the number of vss shadow snapshots (restore
'points). All shadows apparently have a linkable path
'\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy#,
'where # is a simple one, two or three digit integer.
Dim objProcess As New Process()
objProcess.StartInfo.UseShellExecute = False
objProcess.StartInfo.RedirectStandardOutput = True
objProcess.StartInfo.CreateNoWindow = True
objProcess.StartInfo.RedirectStandardError = True
objProcess.StartInfo.FileName() = "vssadmin"
objProcess.StartInfo.Arguments() = "List Shadows"
objProcess.Start()
Dim burp As String = objProcess.StandardOutput.ReadToEnd
Dim strError As String = objProcess.StandardError.ReadToEnd()
objProcess.WaitForExit()
Dim xnum As Integer = 0
Dim counterVariable As Integer = 1
' Call Regex.Matches method.
Dim matches As MatchCollection = Regex.Matches(burp, _
"HarddiskVolumeShadowCopy")
' Loop over matches.
For Each m As Match In matches
xnum = xnum + 1
'At the max xnum + 1 is the number of shadows that exist
Next
objProcess.Close()
Do
'Here we make symbolic links to all the shadows, one at a time
'and loop through until all shadows are exposed as folders in C:\.
Dim myProcess As New Process()
myProcess.StartInfo.FileName = "cmd.exe"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Dim myStreamWriter As StreamWriter = myProcess.StandardInput
myStreamWriter.WriteLine("mklink /d C:\shadow" & counterVariable _
& " \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy" _
& counterVariable & "\")
myStreamWriter.Close()
myProcess.WaitForExit()
myProcess.Close()
' Here I compare our recovery target file against the shadow copies
Dim sFile As String = PathTb.Text
Dim sFileShadowPath As String = "C:\shadow" & _
counterVariable & DelFromLeft("C:", sFile)
Dim jingle As New Process()
jingle.StartInfo.FileName = "cmd.exe"
jingle.StartInfo.UseShellExecute = False
jingle.StartInfo.RedirectStandardInput = True
jingle.StartInfo.RedirectStandardOutput = True
jingle.StartInfo.CreateNoWindow = True
jingle.Start()
Dim jingleWriter As StreamWriter = jingle.StandardInput
jingleWriter.WriteLine("fc """ & sFile & """ """ _
& sFileShadowPath & """")
jingleWriter.Close()
jingle.WaitForExit()
Dim jingleReader As StreamReader = jingle.StandardOutput
Dim JingleCompOut As String = jingleReader.ReadToEnd
jingleReader.Close()
jingle.WaitForExit()
jingle.Close()
Dim jingleBoolean As Boolean = JingleCompOut.Contains( _
"no differences encountered").ToString
If jingleBoolean = "True" Then
MsgBox(jingleBoolean)
Else
'I haven't decided what to do with the paths of
'files that are different from the recovery target.
MsgBox("No")
End If
counterVariable = counterVariable + 1
Loop Until counterVariable = xnum + 1
End Sub