I have created a winform program in visual studio 2012 that saves a image loaded into a picture box when another button is clicked. I first get the file path from the user with:
PrePath = {FileSave.Text,"RawData",Welcome.File(nextimagecounter)}
Path = IO.**Path**.Combine(PrePath)
Imagea.BackgroundImage.Save(Path)
Where PrePath is a String Array, Path is a string, FileSave.Text is user input in a txt box, Welcome.File(nextimagecounter) is a string that was stored in array File (found using .GetFiles) Path = IO.Path.combine(PrePath), Imagea.Backgroundimage is the background image I want to save.
When I do this my program will freeze and I need to go to the task manager to end it. It also throw this error
An unhandled exception of type
'System.Runtime.InteropServices.ExternalException' occurred in
System.Drawing.dll
Additional information: A generic error occurred in GDI+.
Please note I also tried doing the call by:
Imagea.Background.Save(FileSave.Text+"\RawData\"+Welcome.File(nextimagecounter)+".jpg")
This did not work either, another post lead me to Path.Combine. Any help would be greatly appreciated!
Related
To start with it has been many years since I have done much programming, probably about 15 years, in fact VB 6 was still being taught then so I'm not up to date on anything and can get lost in what I'm reading but I am trying. I'm using Visual Studio 2019 and trying to create a VB Windows Forms App that uses the FileSystemWatcher. Unfortunately the only solutions to my problem that I could find are in C#. I tried to transfer them to my app but couldn't get them to work. Actually Visual Studio wasn't happy with what I put in and wouldn't run at all, probably due to incorrect syntax.
This part of my little app is supposed to copy a file that another program creates, while the other program is running, and place the copy in another folder. It seemed simple, detect that the file had been changed and then copy the changed file. Well I came across a few problems.
The first problem is that if I create an empty file the code works most times with no problems but occassionally 2 copies of the file are created. I could live with that but.
If I replace the empty file with a larger file, the file that it is meant to copy, then it can make 3 or 4 copies and most times produces a messagebox telling me that it can't access the file because it is in use. The main program is also minimised to display the error message, which I don't want.
Even if my app is the only program running and I replace the watched file manually with the larger file I still get the file in use error, so I am assuming that the event has been triggered twice and one of them is the process that is using the file and causing the error.
If I tell the error message to cancel then my program continues and produces only 1 copy of the file. Which is what I do want.
The second problem is that the file being copied is also accessed by another program for a short period imediately after it has been changed and this also causes an extra few copies of it to be made and sometimes a file in use error message box appears, and again the main program is minimised to display the error message. I originally had other IO.NotifyFilters in place that weren't really necassary and thought that they may have been triggering the errors so I removed them, but it made no difference.
The most common error is that the file is in use but there has also been the odd "Unhandled exception has occured in your application. could not find file.". The only reason that I can think of for this error is that the file may have been renamed to a backup file and a new version created by the main program at the exact time my program tried to access it.
From what I have read the FileSystemWatcher can trigger multiple times and I presume that this is what is causing the duplicate copies from both problems.
I need my app to make only 1 copy without the error messagebox appearing as this program needs to run in the background with no user input. Essentially this part of my app is an external program to backup a file when the file changes because the main program changes this file often but only seems to back up the file every few hours.
The following code is what I have used but nothing that I have tried has caught the error so I removed the error event handler. This code was copied from something else that was similar and in C# then modified for my purpose. I thought that the {} were used for C# not VB but it seems to work and if I take them out it won't.
My code for the FileSystemwatcher is:-
WatchFile = New System.IO.FileSystemWatcher With {
.Path = Path.GetDirectoryName(strArkMapFileNamePath),
.Filter = Path.GetFileName(strArkMapFileNamePath),
.NotifyFilter = IO.NotifyFilters.LastWrite
}
' add the handler to each event
AddHandler WatchFile.Changed, New FileSystemEventHandler(AddressOf OnLastWrite)
'Set this property to true to start watching
WatchFile.EnableRaisingEvents = True
The event handler is:-
Private Sub OnLastWrite(sender As Object, e As FileSystemEventArgs)
'Copy the Save file to a new folder and rename it.
My.Computer.FileSystem.CopyFile(
strArkMapFileNamePath,
strBackupPath & "\" & strArkMapFileName & "_" &
DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss") & ".ark",
Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End Sub
I added an error event handler after AddHandler WatchFile.Changed, New FileSystemEventHandler(AddressOf OnLastWrite) but that did nothing.
I tried to add an on error statement before the end sub and that did nothing either, I presume because the Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, caught the error first.
I got frustrated and tried to add a statement before the Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, but it didn't like that and I didn't expect it to work.
So how do I catch the errors before the FileSystemWatcher acts on the error?
I don't know what I am doing wrong so any help would be appreciated.
Also if anybody could offer code for what I need to do can it please be code for a Windows Forms App because I don't seem to have much luck in converting C# or anything else.
Edit
I have replaced the My.Computer.FileSystem.CopyFile with the File.Copy method as suggested and added a few extra bits..
Private Sub OnLastWrite(sender As Object, e As FileSystemEventArgs)
'Verify that source file exists
If File.Exists(strArkMapFileNamePath) Then
'Copy the Save file to a new folder and rename it.
Dim i As Integer
For i = 0 To 3
Try
' Overwrite the destination file if it already exists.
File.Copy(strArkMapFileNamePath, strBackupPath & "\" & strArkMapFileName & "_" & DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss") & ".ark", True)
i = 3
' Catch exception if the file was already copied.
Catch copyError As IOException
'If copy failed reset counter
i += 1
End Try
Next
End If
End Sub
Although this shouldn't be required because this is done before the FileSystemWatcher is enabled I have added an If statement to check that the files exists before attempting to copy the file.
I'm not entirely happy with the loop but I know under normal conditions that it's not going to be an endless loop.
Is there a way to just catch the specific errors that I would need to deal with or will it be fine the way it is?
I will probably still need to work out how to stop the FileSystemWatcher from sending more than 1 event or somehow make multiple events appear as 1.
The If statement was the last thing that I added and for some reason the program now seems to only make 1 copy and appears to be faster.
The other external program that accesses the file being copied must be slower to react than my program because now it displays a message that it's waiting until my program has finished copying the file.
My program is now performing as it was intended but I believe that it is just a matter of timing rather than the correct code.
' Download the thumbnail for a note; then display it on this app's form.
Dim thumbnail As Byte() = ENSession.SharedSession.DownloadThumbnailForNote(myResultsList(0).NoteRef, 120)
Try
Dim ms As New MemoryStream(thumbnail, 0, thumbnail.Length)
ms.Position = 0
Dim image1 As System.Drawing.Image = System.Drawing.Image.FromStream(ms, False, False)
PictureBoxThumbnail.Image = image1
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
' Display a note's content as HTML in a WebBrowser control.
Dim myContent = myDownloadedNote.HtmlContent
WebBrowser1.DocumentText = myContent
End If
with these 2 blocks of code from the included "Sampleapp"
i am getting the following errors....
Error 1 'PictureBoxThumbnail' is not declared. It may be
inaccessible due to its protection level.
H:\Michael-Documents\Visual Studio
2013\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 84
17 WindowsApplication1
Error 2 'WebBrowser1' is not declared. It may be inaccessible
due to its protection level. H:\Michael-Documents\Visual Studio
2013\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 91
13 WindowsApplication1
could anyone give me a helping hand, as to what is wrong. Sometimes the Head does not want to think. :-)
This sample app from the Evernote Windows SDK consists of a form with two controls on it named PictureBoxThumbnail and WebBrowser1. I checked the relevant code on Github and confirmed that they are there in the VB.NET SDK sample.
It sounds like somehow in the copy of the app you have in your Visual Studio, the names of these controls have been altered, or the controls may not be on the form at all.
Double-click on the form ("Form1") in the VS Solution Explorer window so as to open it in the VS Designer. There should be one PictureBox control on the left-hand side, named PictureBoxThumbnail, and one larger WebBrowser control on the right-hand side named WebBrowser1. If you don't have either or both of these controls on your form, add them; or if they are not named PictureBoxThumbnail and WebBrowser1, respectively, then rename them to those names. Then the app should run properly.
I have a Word .dot file which works in older versions of Word but fails with error 432 when run in Word 2013.
When I debug the code I have the line:
Load customerForm
And VBA shows the error:
Run-time error '432': File name or class name not found during Automation operation
The project "pennyscode" includes "Module1" which contains the function being debugged, "ThisDocument" and a form called "customerForm".
I have tried changing the name to "pennyscode.customerForm" but this doesn't make any difference.
This code is being called from a Sub function which is called from Document_New().
Updates
I can place a breakpoint on the Load customerForm line and demonstrate that it is the line that is causing the problem. If at this point I mouse over the word "customerForm" VBA comes up with
customerForm = <Object variable or With block variable not set>
If I delete/skip the Load line then the next line is customerForm.Show and that produces the same error.
If I just open the .dotm file and then use Alt-F11 to open VBA, I can look at the code for selectCustomer, list properties/methods and customerForm appears in the list.
Additional Note
I believe that within the Load function it must be calling GetObject and it is this that is failing. It is as if VBA can't find the customerForm object even though it appears in the project.
I've posted the full code of the function being called from Document_New below.
Sub selectCustomer()
Dim Doc As Document
Set Doc = Application.ActiveDocument
If Doc.CustomDocumentProperties.Item("Customer") = "Nothing" Then
Load customerForm
customerForm.Show
Unload customerForm
Doc.Fields.Update
a$ = Doc.CustomDocumentProperties.Item("InvoiceNumber")
a$ = customerForm.pathBox.Value + "\" + a$
Doc.SaveAs (a$)
End If
End Sub
I've also posted the full .dotm (Excel 2013) and .dot (previous excel) and some sample data (.xls) here:
Dropbox/Public/Invoice 2015-16.dotm
Dropbox/Public/Invoice 2015-16.dot
Dropbox/Public/data.xls
Update
I've not had much luck making progress on this question. Can anyone suggest an approach to investigating this? Or how I might improve the information on the question?
I finally managed to fix this, and I have a few learnings.
Firstly the debugger shows the error as occurring on the Load customerForm line, but this is actually not the case.
The customerForm has an _Initialize function which loads data into it before it is displayed. This function was failing with but the debugger stops on the wrong place.
I was able to debug this more effectively by putting a breakpoint on the start of the _Initialize sub and then stepping through the code.
Once I had discovered this I realized that the code was failing to find the XLSX file due to a wrong path, thus causing the run-time error.
Once I'd fixed up all the paths, I then hit a second error: runtime error '9' which is a subscript problem. This also reported on the Load customerForm line and was also due to a problem with the _Initialize function.
This was the true source of the problem, and demonstrated a functional change between Office 2013 and previous versions of Office.
My code was opening an XLSX file and attempting to read data from it:
Dim myXL As Object
Dim myWS As Object
Set myXL = GetObject("C:\Test\data.xlsx")
myXL.Application.Visible = True
myXL.Parent.Windows(1).Visible = True
Set myWS = myXL.Application.Worksheets("Customers")
The run-time error 9 was due to the index of the Windows property, as their were no windows. In previous versions of Office, there was a single window, with 2013 the array is empty.
After much messing about I tried adding this line:
myXL.Activate
before accessing the Windows() array. Once that was executed Windows(1) existed and the code worked as before.
Hope this can help someone else struggling with similar problems.
I am trying to make a program in Visual Basic that can download files to a directory but unfortunately I keep on getting an error similar to this every time:
'An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.VisualBasic.dll
Additional information: The given file path ends with a directory separator character.'
It also highlights this whenever it gives me the error:
My.Computer.Network.DownloadFile(
"https://copy.com/TUr3BCzMbTf4kWNk/symsrv.yes?download=1",
appdata & "\DownloadedFiles\")
I've tried many google searches but nothing, this code used to work on a previous program I've made with VB.net that downloads a game file and replaces it with the current so that users can access parts of the game they couldn't access before without doing certain tasks. Here is the code that did this:
My.Computer.Network.DownloadFile(
"https://copy.com/4WkvAdu4O7sRb3gd/fn4?download=1",
appdata & "/MMFApplications/fn4")
Is there anything I'm doing wrong that prevents me from making my current project work?
The error message is self-explanatory:
The given file path ends with a directory separator character
You should write a filepath as destination (a file that ends with a file extension), not a directory path neither a filepath that ends with a "\" char.
The My.Computer.Network.DownloadFile function just downloads the data, it does not know the filename.
An example:
My.Computer.Network.DownloadFile(
"https://copy.com/TUr3BCzMbTf4kWNk/symsrv.yes?download=1",
System.IO.Path.Combine(appdata, "\DownloadedFiles\File.ext"))
`Dim medium As String = TextBox1.Text
Dim data_xml = XElement.Load("Assets\Manager.xml")
'next quaries the xml for desired attributes
Dim query = From DataTable1 In data_xml.Descendants("DataTable1")
Where (DataTable1.Attribute("Medium").Value = medium)
Select Uname = DataTable1.Attribute("Username").Value
For Each result In query
'displays results to textbox
TextBox2.Text = result
Next
I try to use this code to read from an xml file in the assets but the file does not seem to exist
At the declaration of the xelement.load("Assets\Manager.xml") I get this error
An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: Could not find file 'C:\Data\SharedData\PhoneTools\AppxLayouts\d5d3a1e7-56d7-477c-bcd2-f949f3374de1VS.Debug_AnyCPU.NAME\Assets\Manager.xml'.
If there is a handler for this exception, the program may be safely continued.
Any ideas?
Steps to make it work:
Change Manager.xml Build action to Content
Change Copy to output directory to Copy if newer
Load file using XElement.Load("Assets/Manager.xml");
Edit:
Ok, since you are not willing to share more of the code even though you ask for help, there's nothing else I can do but put up an example :)
"Software" below, implemented in Visual Basic, reads and displays XML file named Manager.xml, that is set as Content in WP8 project. Working example can be found at https://github.com/mikkoviitala/read-content-xml