File not getting created - Visual Basic - vb.net

I'm making a skype tool, and I'm creating the config file automatically, or at least that's what I think I am doing. The problem is just that for some reason the FileNotFoundException is fired because of some of my code is refering to the file which doesn't exist yet. So is visual basic checking for exceptions before firing code, or am I doing something wrong?
Here's my file creation code:
If My.Computer.FileSystem.DirectoryExists("C:\BaconSkypeTool") Then
Else
My.Computer.FileSystem.CreateDirectory("C:\BaconSkypeTool")
End If
If My.Computer.FileSystem.FileExists(Path) Then
Else
Dim fs As FileStream = File.Create(Path)
Dim line1 As Byte() = New UTF8Encoding(True).GetBytes("This is the configuration file for BaconSkypeTool" & vbCrLf & "Please do not change anything in here if you don't know what you're doing." & vbCrLf & vbCrLf & "Values below" & vbCrLf & "ChangeStatusInCall = True" & vbCrLf & "Status = Online" & vbCrLf & "Enable .cancel command = True")
fs.Write(line1, 0, line1.Length)
fs.Close()
End If
And here's the code that fires the exception:
skype.CurrentUserStatus = SKYPE4COMLib.TOnlineStatus.olsOnline
Dim text = My.Computer.FileSystem.ReadAllText("C:\BaconSkypeTool\config.cfg")
Dim textAfterStatus As String = Nothing
Dim indexOfStatus = text.IndexOf("Status = ")
Dim text1 As String = Nothing
If indexOfStatus >= 0 Then
textAfterStatus = text.Substring(indexOfStatus + "Status = ".Length)
text1 = textAfterStatus.Split("Blacklist").First().Trim()
End If
The file creation is at the top of my file and therefore should be the first thing to be fired, but maybe that's just something I think.

Related

vb.net WPF application combobox not waiting for user to choose

I have a wpf vb.net application (written in VS 2019 community) containing two website searches. The first search is a string search and that either produces one result, which I then load into the second search, or it produces more than one result, which I load into a combobox to let the user choose. My problem is getting the application to stop and allow the user to choose from the combobox. I have implemented a workaround that uses a modal form containing a combobox and this allows the user to choose from the combobox and supply the value to the second search. I have been advised to use the 'change' event for the combobox but there isn't one available, I have also been advised to use the selectedindexchanged but the control doesn't let the dropdown list occur to select anything. I have also tried using various forms of addhandler (commented out in the code below).
' Build the 'Search API' URL.
Dim uri = New Uri("https://api.themoviedb.org/3/search/tv?" _
& "api_key=" & TMDBAPIKey _
& "&language=en-US" _
& "&query=" & sLvl1NodeName _
& "&page=1" _
& "&first_air_date_year=" & sFirstXmitYear)
' Retrieve the IMDB ID with an API Search function using the series title
Try
Dim Site = New WebClient()
Answer = Site.DownloadString(uri)
Catch ex As NullReferenceException
Dim messagetext As String = "The 'Search API' from GetDetails popup failed with : " _
& ex.Message & " for: Title=" & sLvl1NodeName
Me.txtErrorMessageBox.Text = messagetext
Exit Sub
End Try
' Deserialise the answer
Dim JsonElem As TMDBtitle = JsonConvert.DeserializeObject(Of TMDBtitle)(Answer)
' If the websearch finds only one result this is the TV series we want, if more than
' one result is found load the results into a combobox and get the user to choose.
If JsonElem.results.Length = 1 Then
TVSeriesID = JsonElem.results(0).id
Else
Me.cmbChooseSeries.BeginUpdate()
Me.lblChooseSeries.Text = Me.lblChooseSeries.Text & "( " & JsonElem.results.Length & " )"
Me.cmbChooseSeries.Items.Clear()
For Each titleresult In JsonElem.results
ComboSeriesChoice = titleresult.name & " | " &
titleresult.id & " | " &
titleresult.first_air_date & " | " &
titleresult.overview
Me.cmbChooseSeries.Items.Add(ComboSeriesChoice)
Next
cmbChooseSeries.DroppedDown = True
Me.cmbChooseSeries.EndUpdate()
If cmbChooseSeries.SelectedIndex <> -1 Then
Dim var1 = cmbChooseSeries.SelectedText
Else
Threading.Thread.Sleep(3000)
End If
'AddHandler cmbChooseSeries.MouseDoubleClick,
'Sub()
'Threading.Thread.Sleep(3000)
'End Sub
TVSeriesID = cmbChooseSeries.SelectedItem
End If
' Build the 'TV Search API' call URL.
Dim urix = New Uri("https://api.themoviedb.org/3/tv/" _
& TVSeriesID & "?" _
& "api_key=" & TMDBAPIKey _
& "&language=en-US")
Try
Dim site = New WebClient()
Answer = site.DownloadString(urix) ' download the JSON from the server.
Catch ex As NullReferenceException
Dim MessageText As String = "The 'TV Search API' from GetDetails popup failed with : " _
& ex.Message & " for: Title=" & sLvl1NodeName & " ID=" & popupid
Me.txtErrorMessageBox.Text = MessageText
Exit Sub
End Try
Dim jsonelemx = JsonConvert.DeserializeObject(Of TVResult)(Answer)
lstDetailItems(0) = "Name"
lstDetailItems(1) = jsonelemx.name
lstDetailItems(2) = (String.Empty)
Dim DelItems = New ListViewItem(lstDetailItems)
Me.lstSeriesDetails.Items.Add(DelItems)
lstDetailItems(0) = "Status"
lstDetailItems(1) = jsonelemx.status
lstDetailItems(2) = (String.Empty)
DelItems = New ListViewItem(lstDetailItems)
Me.lstSeriesDetails.Items.Add(DelItems)
lstDetailItems(0) = "Episode run time"
lstDetailItems(1) = Convert.ToString(jsonelemx.episode_run_time(0))
lstDetailItems(2) = (String.Empty)
DelItems = New ListViewItem(lstDetailItems)
Me.lstSeriesDetails.Items.Add(DelItems)

VB.NET Parameter is not valid

I have used dotnetbar devcomponents advanced treeview to create multiple directory trees for one of my projects. Functionality wise, everything is working fine.
I have now added images to the directory file nodes (e.g. pdf image if its a pdf file) and published the application. The application runs without any errors first time on any machine, but once I close this File Management form (I have a control panel form with buttons that is the initial startup form. The buttons take me to other forms. On button click, it hides the control panel and displays the corresponding form through showdialog - File Management form is one of those buttons) and reopen it again - I get the following error:
parameter_is_not_valid
It then fails to load the nodes and after a couple of tries, Microsoft .Net Framework window appears and ends the application.
I get the images from my resource file. Please see the code for LoadAllSubDirectoriesFiles where the error occurs:
Private Sub LoadAllSubDirectoriesFiles(ByVal uParent As DevComponents.AdvTree.Node)
' Initialise Error Checking
Dim uStackframe As New Diagnostics.StackFrame
Dim ufile As IO.FileInfo = Nothing
Try
If uParent.Name.Length <> 248 Then
Dim files As IO.FileInfo() = uParent.Tag.GetFiles()
For Each file As IO.FileInfo In files
If (Not file.Attributes.ToString.Contains("Hidden")) Then
Dim uNode As DevComponents.AdvTree.Node = New DevComponents.AdvTree.Node()
uNode.Tag = file
uNode.Name = file.FullName.ToLower
uNode.Text = file.Name
If file.Extension = ".msg" Then
uNode.Image = My.Resources.Resources.Mail3
ElseIf file.Extension = ".txt" Then
uNode.Image = My.Resources.Resources.Document
ElseIf file.Extension = ".pdf" Then
uNode.Image = My.Resources.Resources.pdf
ElseIf file.Extension = ".doc" OrElse file.Extension = ".docx" Then
uNode.Image = My.Resources.Resources.doc
ElseIf file.Extension = ".xlsx" Then
uNode.Image = My.Resources.Resources.excel
ElseIf file.Extension = ".pub" Then
uNode.Image = My.Resources.Resources.publisher
ElseIf file.Extension = ".pptx" Then
uNode.Image = My.Resources.Resources.powerpoint
ElseIf file.Extension = ".bmp" OrElse file.Extension = ".png" OrElse file.Extension = ".jpg" OrElse file.Extension = ".gif" OrElse file.Extension = ".tif" Then
uNode.Image = My.Resources.Resources.bitmap_image
ElseIf file.Extension = ".zip" OrElse file.Extension = ".rar" Then
uNode.Image = My.Resources.Resources.zip
Else
uNode.Image = My.Resources.Resources.unknown
End If
uNode.DragDropEnabled = True
uParent.Nodes.Add(uNode)
End If
Next
End If
Catch ex As Exception
' Catch Error
If Err.Number <> 0 Then
WriteAuditLogRecord(uStackframe.GetMethod.DeclaringType.FullName, uStackframe.GetMethod.Name.ToString, "Error", ex.Message & vbCrLf & vbCrLf & ex.StackTrace, 0)
MsgBox("System Error Ref: " & sAuditID & vbCrLf & uStackframe.GetMethod.DeclaringType.FullName & " / " & uStackframe.GetMethod.Name.ToString & vbCrLf & ex.Message & vbCrLf & vbCrLf & ex.StackTrace & Chr(13) & sErrDescription & vbCrLf & vbCrLf & "Press Control + C to copy this error report", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Business Management System - Unexepected Error Ref: " & sAuditID)
End If
Finally
' CleanUp
End Try
End Sub
I have spent 2 days now trying to figure out the cause and fix for this problem. There were posts that talked about the image being disposed and not being able to retrieve the image reference [ http://blog.lavablast.com/post/2007/11/29/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx ] , cloning the image before disposing etc.
I have given disposing and cloning a go, but the error still stands. Been trying couple of other things, but still unsuccessful.
Any suggestions to what is wrong?
EDIT 1
Before closing the form, I clear all the treenodes and then use Me.Close()
Private Sub tsbClose_Click(sender As Object, e As EventArgs) Handles tsbClose.Click
atRootFolder.Nodes.Clear()
atAllDirectories.Nodes.Clear()
atScannedFiles.Nodes.Clear()
atFiles.Nodes.Clear()
atInbox.Nodes.Clear()
atSent.Nodes.Clear()
Me.Close()
End Sub
EDIT 2
My treeviews have hundreds of nodes, child nodes etc. Please see the image of my File Management form ( this is the first time it was loaded, no errors) I had to hide the text due to client confidentiality, but I hope it makes sense. Each image is a node.
imgur.com/QQ2FzFV
I had tried to use GC.Collect to see if it works, and surprising it did. Sadly it worked on one machine and didn't in another. Therefore, instead of calling images directly from my resources, I have stored all required images in an image list which I have attached to my treeviews. It's working like a charm.

Getting BC31019 excepetion while compiling vb.net at runtime on Windows 10

we are generating a mass of documents very dynamically. Therefore we concatenate source code and build a dll at runtime. This is running since windows XP.
Now we are in tests of windows 10 and it fails compiling this dll with the error "BC31019: Unable to write to output file 'C:\Users[name]AppData\Local\Temp\xyz.dll': The specified image file did not contain a resource section"
For testing purposes we remove all generated source code and replace it by a rudimental class with only one function (throwing an exception with specified text) and no referenced assemblies.
This is also running on all machines except windows 10. Same error.
Can anybody guess why?
This is the rudimental method
Public Sub Compile()
Dim lSourceCode = "Namespace DynamicOutput" & vbCrLf &
" Public Class Template" & vbCrLf &
" Sub New()" & vbCrLf &
" End Sub" & vbCrLf &
" Public Sub Generate(ByVal spoolJob As Object, ByVal print As Object)" & vbCrLf &
" Throw New System.Exception(""Generate reached"")" & vbCrLf &
" End Sub" & vbCrLf &
"" & vbCrLf &
" End Class" & vbCrLf &
"End Namespace"
Dim lParams As CodeDom.Compiler.CompilerParameters = New CodeDom.Compiler.CompilerParameters
lParams.CompilerOptions = "/target:library /rootnamespace:CompanyName /d:TRACE=TRUE /optimize "
lParams.IncludeDebugInformation = True
lParams.GenerateExecutable = False
lParams.TreatWarningsAsErrors = False
lParams.GenerateInMemory = True
Dim lProviderOptions As New Dictionary(Of String, String) From {{"CompilerVersion", "v4.0"}}
Dim lResult As CodeDom.Compiler.CompilerResults = Nothing
Using provider As New VBCodeProvider(lProviderOptions)
lResult = provider.CompileAssemblyFromSource(lParams, lSourceCode)
End Using
' ... check for errors
Dim lInstance As Object = lResult.CompiledAssembly.CreateInstance("CompanyName.DynamicOutput.Template")
lInstance.GetType.GetMethod("Generate").Invoke(lInstance, New Object() {Me.SpoolJob, Me.Print})
End Sub

Move files with certain extensions only

I'm currently using the Directory.Move method to copy files from one location to another. What i would like to do is only move files with certain extensions (.dbf, .ini & .txt). If the original folder doesn't contain any of these files then i just want to create an empty directory
Current code I'm using is...
Dim n As Integer
If lb1.SelectedItems.Count = 0 Then Exit Sub
For n = 0 To UBound(AllDetails)
If AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps = lb1.SelectedItem Then
If Not My.Computer.FileSystem.DirectoryExists(aMailbox & "\" & AllDetails(n).uFile) Then
Directory.Move(zMailbox & AllDetails(n).uFile, aMailbox & "\" & AllDetails(n).uFile)
lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
Else
lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
Exit Sub
End If
End If
Next
All the variables are declared and this works but moves the entire folder contents
One way to approach this is to use each extension as a search pattern for File.GetFiles, then use Directory.Move on each file returned. Something like this might help:
For Each OldFile As String In (From s In {".dbf", ".ini", ".txt"}
From f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, s)
Select f)
Directory.Move(OldFile, aMailbox & "\" & AllDetails(n).uFile & "\" & Path.GetFileName(OldFile))
Next
if what you want is certain file extensions only? well Open File Dialog can filter that for you
Let's say you call this operation with a button click:
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Open File Dialog"
fd.InitialDirectory = "the initial directory you want to look at first"
'this filters the available files to be opened!
fd.Filter = "dbf files|*.dbf*|ini files|*.ini*|Text files|*.txt*"
fd.FilterIndex = 2 'set's the default files to open first as .ini
fd.RestoreDirectory = True
If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then
'Copy the file to the location using the copyer subroutin
resulta.Text = fd.FileName.ToString
Copyer(fd.FileName.Tostring, "the location where you want to copy")
End If
End Sub
Now for the copying of the file, have a look at this subroutine. This subroutine checks first if the file exists. If it does, it deletes it, then copies the new file.
Public Sub Copyer(ByVal theFile As String, ByVal Lokasyon As String)
Try
Dim resultpath As String = Lokasyon
If System.IO.File.Exists(resultpath) = True Then
System.IO.File.Delete(resultpath)
'this deletes the file so you can overwrite it.
End If
My.Computer.FileSystem.CopyFile(theFile, resultpath)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Please let me know if this has helped you.

List that this enumerator is bound to has been modified

I have this bit of code here, and at the next statement it's giving me an error saying:
List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.
I really don't know how to further explain this issue, but if you need me to I can try.
For Each itemChecked In storedAuthorsListbox.CheckedItems
Dim selectedAuthor As String = storedAuthorsListbox.SelectedItem.ToString()
Dim authorFile As String = "Authors\" & itemChecked.ToString()
Dim document As XmlReader = New XmlTextReader(authorFile)
metaInfo &= "[Author]" & vbNewLine
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "Name") Then
metaInfo &= "Name=" & document.ReadInnerXml.ToString() & vbNewLine
ElseIf (document.Name = "Website") Then
metaInfo &= "Website=" & document.ReadInnerXml.ToString() & vbNewLine
ElseIf (document.Name = "Notes") Then
metaInfo &= "Notes=" & document.ReadInnerXml.ToString() & vbNewLine
End If
End If
End While
document.Close()
Next
Some code somewhere is changing storedAuthorsListbox while you are iterating it. That code is not visible in the snippet. Do make sure that the posted code is not running in a worker thread, that is not legal. It certainly quacks like the kind of code you'd run in a worker.
The generic solution is to make a copy of the items and work from that copy instead of the control:
Dim copy = storedAuthorsListBox.SelectedItems.OfType(Of String)().ToList()
For Each itemchecked In copy
'' etc..
Next
If this runs in a worker thread then pass the copy to the worker.