Cannot save a freshly created bmp file, help needed - vb.net

Hate to sound like a broken record, but I simply cannot get the program I wrote in Visual Basic to write a file when run standalone; but it works fine when run via the debugger.
Simplified, the code looks like this (and the bitmap image is being created and is being saved, i.e., the file does not already exist):
Using bmp As New Bitmap(imgHorSize, imgVerSize) ‘ the sizes are not too large
<build the bitmap>
Dim fName As String = “C:\Users\<name>\Desktop\temp\foobar.jpg"
bmp.Save(fName, ImageFormat.Jpeg)
End Using
When I run this outside the debugger, I get
System.UnauthorizedAccessException: Access to the path
'C:\Users<name>\Desktop\temp\foobar.jpg' is denied
I saw some notes that suggest there should be a \\ after C:. Other sources show using a / instead of a \. Not sure that either really matters (since the directory name is coming from the result of a FolderBrowserDialog). I have checked the folder permissions on temp and see that my account has full control. I added user Everyone, via the security tab, and gave it full control. Same problem. As an experiment, I changed the above code to
Using bmp As New Bitmap(imgHorSize, imgVerSize)
<build the bitmap>
Dim fName As String = “C:\Users\<name>\Desktop\temp\foobar.jpg"
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(fName, True)
file.WriteLine("Here is the first string.")
End Using
and I got the exact same error. I also tried creating a MemoryStream, but that also didn’t work.
So, the issue is probably not related to the bmp.Save process, but something more fundamental. I have been looking at various things and have tried a few of them, but nothing works. This should be super easy to do, so what am I doing wrong?
== follow up ==
To come up with something to share in its entirety, I just wrote the following, very simple program that basically does the same as the real program:
Imports System.Drawing
Imports System.Drawing.Imaging
Public Class Form1
Structure myImages
Dim strFName As String
Dim imgL As Image
End Structure
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim imgLI As myImages
imgLI.strFName = "C:\Users\<username>\Desktop\EinRiddle\ItemImages\An_Cat.jpg"
imgLI.imgL = New Bitmap(Image.FromFile(imgLI.strFName), 150, 150)
Dim bmp As New Bitmap(300, 400)
Using bmp
Dim gr As Graphics = Graphics.FromImage(bmp)
gr.Clear(Color.WhiteSmoke)
gr.DrawImage(imgLI.imgL, 20, 20)
bmp.Save("C:\Users\<username>\Desktop\testImg.jpg", ImageFormat.Jpeg)
gr.Dispose()
End Using
Application.Exit()
End
End Sub
End Class
I am getting the same error message...

Have you tried another directory? Often one cannot write a file to the desktop.
Have you tried another format (for example ImageFormat.Bmp)?
You use “ instead of " ... Is that the mistake? Ah, I guess this is not the real code and you wrote this from memory and and something made “
Sometimes it takes a while before the picture and graphics can be disposed because the image is saved lazily. Even if this is not welcomed, give it a try
bmp.Save("C:\Users\<username>\Desktop\testImg.jpg", ImageFormat.Jpeg)
Application.DoEvents()
gr.Dispose()
End Using

I found the answer: On this computer, my user files are on the D: drive. Thus, when I changed the path from C: to D:, it worked. Of course, why this is necessary, since there is symbolic link, I don't understand...

Related

inserting data from a text file to textboxes and setting combobox indecies

so I am writing a program and trying to setup the save/open features of the program. I have the Save feature working just fine, but can't get the open feature to work.
The issue I'm running into is pulling the data from the text file to the form to fill in the multiple fields and controls. my example code is below
Imports System.IO
Main 1
Sub openFile_Click(sender, e) handles openFile.Click
Dim lineIndex As Integer = 12 'this is my total lines in my file
ofdRead.ShowDialog()
If ofdRead.FileName <> "" then
sr = New StreamReader(ofdRead.FileName)
For i As Integer = 0 To lineIndex -1
sr.ReadLine()
Next
txtField1.Text = sr.ReadLine
cboBox1.SelectedIndex = sr.ReadLine
'this continues through all fields til complete
sr.Close()
End If
End Sub
End Class
I keep getting an error for anything that is being returned as not being a string, and it seems as though the data is being read in reverse as well according to my error output.
Any help would be much appreciated (been searching and pouring over forums for 2 days looking for help)
Thanks Tim Schmelter for your insight. I was calling the wrong data type for the cboBox1 variable. Here is my corrected code (without the For-Loop, turns out i didn't need it)
cboBox1.SelectedItem = sr.ReadLine
so everytime I run into something like that I just have to tell it to put it in as a string instead of an integer

VB.NET batch pdf printer tool

I'm looking for a tool, but I can't find it. So I thought, maybe I can make one. Seems like a good idea, a program that fits my needs at last! Just one problem.. I don't know how!
Intro
At my work we create production drawings in .dwg format. Once this is done they are exported as .pdf sent to the client for approval. If approved they are issued for production, so they need to be plotted.
So my current workflow is:
Set my default printer preferences (number of copies, paper size, ..)
Go to the folder that has the .pdf files
Select 15 files
Right click print.
The problem here is
The files are printed in the order the printer receives them and not the order in the folder. So I would need to sort them out ( this x number times the number of copies sometimes this goes up to 6 times. )
I can only do 15 at a time (large projects are +100 documents)
I have to reset my preferences each time the sizes change.
Our file numbering system has some "intelligence" into it. Its build like this:
A1-12345-001 rev1
A1 = page size
12345 = document number, the same within a project. Other project means other number. (mostly irrelevant as I only print a project at a time)
001 = sequence number, next drawing will be 003,004,005,007,... you get the drift.
rev1 = revision number. Normally only the highest revision should be located in the folder, but it could be used to check for documents with a lower revision.
Now, I would like to automate my happy printing task, as this makes my week very bad if a large projects needs to go into production or, there are revisions mid-production and we need to re-issue them for production.
So far the situation sketch
Program sketch
So I've started to make a sketch of what the program should do.
User should be able to add .pdf files into a list. file browser object for starters, can be drag and drop later (the drawings are in one folder so there is no real need for drag and drop).
The list should contain 4 columns. paper size, document number, sequence, revision. Could be a data-grid view.
The list should be sorted by the drawing sequence. This how I would like to pass the drawing so, no sorting is required anymore! You can look at the sequence as page numbers.
Select the desired printer to do the job. (usually the same but other departments also have a printer so that would be a nice option.)
Set the number of copies. When printed, it shouldn't be 5x -001 then 5x -002 .. it should print them still in order of the sequence number and the re-loop the process x times.
Print the documents.
Adding PDF files
I started out with creating a dialog.. easy enough I guess.(please keep in mind that I'm a very low level programmer and nothing seems easy to me..) I added an open file dialog to my windows-form set multiple select true. Also made a filter to have only .pdf files
added a button with this code:
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim file As String
For Each file In FileDialog.FileNames
Debug.Print(file)
Next
End If
End Sub
So this should give me all the info I need from the file. I will edit this later, I know how to access it now!
The document object
I guess it would be wise to use some o.o.p. for this. As each file is a document and have the same required properties to make this work.
So I made a Public class for the document called PDF_Document
Public Class PDF_Document
Public FullFilePath As String
Public Property Size As String
Public Property DocNumber As String
Public Property Sequence As String
Public Property Revision As String
Public Sub New(ByVal oFilePath As String)
' Set the FullFilePath
FullFilePath = oFilePath
' Get the filename only without path.
Dim oFileName As String
oFileName = Path.GetFileName(oFilePath)
' Get the document size from the file name
Size = oFileName.Substring(0, 2)
' Get the document number from the file name
DocNumber = oFileName.Substring(3, 5)
' Get the sequence from the file name
Sequence = oFileName.Substring(9, 3)
' Chop of the .pdf from the name to get access the revision
Revision = oFileName.Substring(oFileName.Length - 5, 1)
End Sub
End Class
Well this should result into the info I need from the document..
creating a list(of t)
Wow, it seems to be getting somewhere.. Now to hold the list I'll have this collection I think don't know whats best for this? Public oPrintList As New List(Of PDF_Document)
So I think I should populate my list like this?
Public oPrintList As New List(Of PDF_Document)
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim oFile As String
For Each oFile In FileDialog.FileNames
Dim oPDF As New PDF_Document(oFile)
oPrintList.Add(oPDF)
Next
End If
End Sub
Making things visual for the user
Hmm okay, were getting somewhere, I got a list of all the files I need! But I want to see them in a viewer. I'm gonna use a data-grid view maybe? It should show my properties and it looks good I think.
So I made a binding that binds my List(of T) and added this binding as data-source for the data-grid view. I also change the ADD_FILES_Click a little, the PDF_Document is now added into the binding and not in the List(of T).
Public Class Form1
Public oPrintList As New List(Of PDF_Document)
Public oBinding As BindingSource
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim oFile As String
For Each oFile In FileDialog.FileNames
Dim oPDF As New PDF_Document(oFile)
oBinding.Add(oPDF)
Next
End If
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
oBinding = New BindingSource(oPrintList, Nothing)
DataGridView1.DataSource = oBinding
End Sub
End Class
Printing the list
Well I managed to do quite some things now. But.. the main essence still isn't reached! I now got a form with a bunch of buttons that don't work yet, a list of select documents in queue for printing and .. thats it :)
Now I'm trying to create a method that prints a .pdf file.. easier sad than done. I need some help with this.. I search the net, but I can find samples that don't work, or I don't understand. All users PC's are equiped with acrobat reader.
Also feel free to comment me on the other parts of the program. ( yes I know there is no sorting function yet etc. ) but getting a page from the printer is more important now.
Sorry for the long post!
If your users have Adobe Acrobat Reader installed, the following code should do the trick. I recommend Acrobat Reader 11 or lower version. With Acrobat DC the window from Acrobat does not close anymore, that is a "design" decision by Adobe.
Dim pr As New Process()
pr.StartInfo.FileName = "c:\myfile.pdf"
pr.StartInfo.UseShellExecute = True
pr.StartInfo.Verb = "print"
pr.Start()
pr.WaitForExit()
I work with DWG and PDF files for 20+ years. If you are interested in a solution that fully automates all steps you explained in your "wishlist" software and does a ton more feel free to contact me at pdfmagick at gmail dot com
Another way to print PDF files with the Print Drivers dialog is as follows:
Dim starter As ProcessStartInfo
starter = New ProcessStartInfo(<pathToAdobeAcrobatExecutable>, String.Format(" /s /N /P ""{0}""", Filename))
Dim Process As New Process()
Process.StartInfo = starter
Process.Start()
Process.WaitForExit()
Process = Nothing
starter = Nothing
More command line switches are explained here
Adobe Reader Command Line Reference
Regards

GetFullPath no output ?! VB.NET

Good evening to all of you!
I have a problem that I can't solve with the method GetFullPath in vb.net.
What I want to do :
I would like to get the full path of a text file (test.txt) which is located in the same folder as the app.exe, the one I am working on. I need the full path to use an other method. To know more about the reason it doesn't work, I put the GetFullPath output in a MsgBox.
What is happening :
The MsgBox just shows a blank. This is really strange because, even if the test.txt doesn't exist, the output should exist (as if the file exists).
WARNING : IN MY CASE THE FILE EXISTS
Documentation : https://msdn.microsoft.com/en-us/library/system.io.path.getfullpath(v=vs.100).aspx Cf. "Remarks"
What I think about that :
Is it possible that the app.exe doesn't see test.txt which is in the same folder ? I don't think so, it would give an outpout.
Maybe it is a problem of permission ? I really don't know why the MsgBox is empty.
My peace of code :
Dim file1 As String = "test.txt"
MsgBox(GetFullPath(file1))
Thankyou to everyone who will try to help me.
Have a nice day ! :)
Please excuse my poor english.
Microsoft Visual Studio 2010.
It appears something in your code is changing the working directory (or in the case of Windows XP, it is not being set properly). The GetFullPath function I have provided below will return the path I believe you are expecting regardless of the working directory.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show(GetFullPath("file.txt"))
End Sub
Private Function GetFullPath(fileName As String) As String
Return IO.Path.Combine(Application.StartupPath, fileName)
End Function
Or you can do this ,
Label1.Text = Application.StartupPath
You do all with this code ^^

How to read an Atom Feed in VB.Net

I have searched and searched and searched enough until my Head aches! What I am trying to do is take an ATOM feed from here: National Weather Service Alerts and incorporate it into my program, however, I don't even KNOW where to begin :( What I want to do eventually is download the Atom feed and place it in a scrolling label. I don't want to parse it pulling out sections or anything. Just want to display the NWS alert for my area. I don't expect anyone to just write out the code or anything, but any help pointing me in the right direction for programming it simply and painlessly for an intermediate vb programmer would be greatly appreciated. Please Help!
Here is a code sample that should work for your case. Assuming you already downloaded your Atom feed and saved it to your disk. If not, you may need a slight modification:
Imports System.Xml
Imports System.ServiceModel.Syndication
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim messageList As New Generic.List(Of String)
Using feedReader = XmlReader.Create("X:\vi.php.webintents")
Dim feedContent = SyndicationFeed.Load(feedReader)
If feedContent Is Nothing Then Return
For Each item As Object In feedContent.Items
messageList.Add(Convert.ToString(item.Title.Text))
Next
End Using
lbl_warnings.Text = String.Join(vbNewLine & vbNewLine, messageList)
End Sub
End Class
Replace "X:\vi.php.webintents" with your file location.
For System.ServiceModel.Syndication to be available, you need to add System.ServiceModel.dll to your references (.NET 4.0). For .NET 3.5 you would use System.ServiceModel.Web.dll
I used this answer as a base for SyndicationFeed usage in this example.

Using Visual Basic to Select a Google Search Result in Internet Explorer

I have VB code that goes to Google, fills in the search bar, and hits the search button. Is there a way to have my program select a particular result after my search? ie. I search for "cheese", I would like for my program to select the 2nd to last result (in this case, it is wwww.chuckecheese.com)
I ended up using Sendkeys to emulate the tab and down arrow keys on the keyboard. You can then navigate to your desired search results using these 2 keys
Or you can bypass using an API and avoid ads or cost using speech recognition to improve your Dictation searches. Programming isn't programming if you aren't thinking outside the box and innovating your own solutions.
Coding comes with creativity and you won't know what that is if you don't try. This site is excellent for this very purpose and many have contributed to innovation in coding.
You will have to add a text file to your project and call it whatever you want, then change the path below in the code to your own path. The text file stays blank. The program will write your spoken search to file and then execute the search, constantly over-writing itself.
For some odd reason, this method greatly improves the fusion of speech recognition and dictation. You can speak an entire phrase and it will conduct the search. A good mic is a must and speaking clearly without background disturbances.
Imports System.Speech.Recognition
'Declarations:
Private ReadOnly Drone As New SpeechRecognitionEngine()
Private ReadOnly Qa As New DictationGrammar()
Private Sub Form1_Load(sender As Object,
e As EventArgs) Handles MyBase.Load
'Dictation Mode | Google Engine
Drone.LoadGrammarAsync(Qa)
Drone.RequestRecognizerUpdate()
Drone.SetInputToDefaultAudioDevice()
Drone.InitialSilenceTimeout = TimeSpan.FromSeconds(2.5)
Drone.BabbleTimeout = TimeSpan.FromSeconds(1.5)
Drone.EndSilenceTimeout = TimeSpan.FromSeconds(1.2)
Drone.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.5)
AddHandler Drone.SpeechRecognized, AddressOf Drone_SpeechRecognized
Drone.RecognizeAsync(RecognizeMode.Multiple)
End Sub
Private Sub Drone_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs)
Dim google As String = e.Result.Text.ToString
Select Case (google)
Case google
If google <> "+" Then
'This section will take spoken word, write to file then execute search.
Dim sb As New StringBuilder
'Be sure to change the text file path below to your path if you are new to this program.
sb.AppendLine(google)
'Add your own path below here. you can also change google to youtube and conduct youtube searches
File.WriteAllText("C:\Users\justin.ross\source\repos\ScarlettCenturium\Scarlett Centurium\Scarlett Centurium\File.txt", sb.ToString())
google = "https://www.google.com/search?q=" & Uri.EscapeUriString(google)
Dim proc As New Process()
Dim startInfo As New ProcessStartInfo(google)
proc.StartInfo = startInfo
proc.Start()
'This sendkey will close out previous tab on new search
SendKeys.Send($"^{{w}}")
Return
End If
End Select
End Sub
well you can use google api for that
goto http://code.google.com/p/google-api-for-dotnet/
download GoogleSearchAPI_0.4_alpha.zip
extract it and add reference to the dll file in your project ( in folder .net 2)
and you can use it like this
first import the library
Imports Google.API.Search
then in a sub or function put your code as
Dim rf As String = "http://www.google.com"
Dim v As New Google.API.Search.GwebSearchClient(rf)
Dim result = v.Search(TextBox1.Text, 40)
' number (40) is the amount of fetched results ( change it if you want )
For Each item In result
If item.Url.Contains("chuckecheese") Then
' your code goes here
End If
Next