Streaming a pdf file to the browser from a LotusScript web agent - pdf

I'm creating a LotusScript web agent that reads the content of a pdf file somewhere on the network and returns it as a stream to the browser.
the agent will be called like this : getPDF?openAgent&pdfId=123456 and it should directly returns the pdf stream. (I didn't implement yet the url parameter catching)
Here's my current try, I still have an issue to convert the read buffer to the final stream
Sub Initialize
On Error GoTo errrorhandle
Dim session As New NotesSession
Dim stream As NotesStream
Set stream = session.CreateStream
Dim buffer As variant
Dim fileNum As Integer
Dim txt As String
Dim filename As String
Dim filecontent As String
filename = "C:\temp\test.PDF"
If Not stream.Open(filename,"binary") Then
MessageBox filename,, "Open failed"
Exit Sub
End If
If stream.Bytes = 0 Then
MessageBox filename,, "File has no content"
Exit Sub
End If
Print "content-type:application/pdf"
Do
buffer = stream.read(1)
Print buffer(0)
Loop Until stream.IsEOS
Call stream.Close
Exit Sub
errrorhandle :
Print "Error :" & Error & " at line : " & Erl
Exit sub
End Sub

It is not possible to output the pdf from a stream in Lotusscript.
I suggest you attach the pdf to a notesdocument and redirect the user to attached file url and later on remove the document.
you can get a hold of the saved pdf using the following syntax
http://server/database/unid/$File/myfile.pdf

Following on Thomas Adrian response, attaching the pdf into a document in a database and then serve the link as described is the best solution.
Keep in mind that this will require the user to be authenticated, if said database has or needs restricted access.
If the web users are not authenticated users, you'll need to give at least reader access to "Anonymous" in the ACL of the hosting database for this to work... which is not always advisable if the database has other purposes.
You can however create a dedicated database just for this purpose, with unrestricted ACL access.

Related

How to use Web browser object to display a pdf file

I am trying do display a pdf file on a form which contains a Web browser. I have previously used the below code which sometimes works but now I am constantly getting an error at line webBrowser2.Navigate pdfFilePath. The pdf file exists in the path and is named correctly. Please see the rest of code and help if you can:
Sub loadPDFFile()
Dim webBrowser2 As WebBrowser
Dim pdfPath As String
Set webBrowser2 = webControl.Object
pdfPath = Application.CurrentProject.Path & "\Internal Framework Summary.pdf"
webBrowser2.Navigate pdfPath
End Sub
Private Sub Form_Open(Cancel As Integer)
Me.webControl.ControlSource = Application.CurrentProject.Path & "\Internal Framework Summary.pdf"
End Sub
Private Sub Form_Load()
loadPDFFile
End Sub
Current Registry setting:
You may need a Registry setting:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
Try setting it to 0 (zero) to make the control to use the current browser emulation.
Source: Everything You Never Wanted to Know About the Access WebBrowser Control
and my comment of 2020-11-13.
Bonus tip:
After setting MSACCESS.EXE to your preferred value, do
check the setting for OUTLOOK.EXE. Adjusting that will probably make
most of your received e-mail newsletters render as intended.
To display the file, use this ControlSource:
="=" & [URL]
where URL is the field holding the full path to the file wrapped in octothorpes, for example:
#http://africau.edu/images/default/sample.pdf#

Saving image from php id URL using webbrowser in VB.net

I am trying to save a image from webbrowser but can't find an answer for it.
Example of the problem is the URL is hxxp://domain[.]com/image/?img=1234 on webbrowser it shows the image and the source is <img src='hxxp://domain[.]com/image/?img=1234'>..
I was unable to save it using the My.Computer.Network.DownloadFile and MemoryStream(tClient.DownloadData methods.
In order to download the file, I will need to session cookie also?
How can I do this?
Any image that you see in the WebBrowser has already been downloaded to your computer. It is normally cached in the folder:
C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files
or whatever other folder is set in Internet Options. You can get your image from that folder.
The following program shows how to copy file TDAssurance_Col.png from the Temporary Internet Files folder to the C:\Temp folder.
Module Module1
Sub Main()
CopyFileFromTemporaryInternetFolder("TDAssurance_Col.png", "C:\Temp")
End Sub
Public Sub CopyFileFromTemporaryInternetFolder(filename As String, destinationFolder As String)
' Search actual path of filename.
Dim temporaryInternetFilesFolder As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), "Content.IE5")
Dim pattern As String = Path.GetFileNameWithoutExtension(filename) & "*" & Path.GetExtension(filename)
Dim pathnames() As String = Directory.GetFiles(temporaryInternetFilesFolder, pattern, SearchOption.AllDirectories)
' If file found, copy it.
If pathnames.Count > 0 Then
File.Copy(pathnames(0), Path.Combine(destinationFolder, filename))
End If
End Sub
End Module

File Being Used By .NET Mail

I wrote a simple program written to collect files, send the files, then delete said files. I am sending them via Email using System.Net.Mail
If Label6.Text = "" Then
mail.Attachments.Add(New Attachment(zipPath))
End If
'Enables SSL, if required
ssl = Provider.ssl
If skipAhead = True Then
ssl = True
End If
If ssl = True Then
SmtpServer.EnableSsl = True
End If
'Sends the email
SmtpServer.Send(mail)
'Allows the user to either keep testing, or quit.
If skipAhead = True Then
My.Computer.FileSystem.DeleteFile(unalteredPath)
My.Computer.FileSystem.DeleteFile(unalteredPath1)
My.Computer.FileSystem.DeleteFile(zipPath)
Else
Dim keepOpen As Integer = MsgBox("The Email was sent. You can keep testing if you would like to. Press ok to close, and cancel to keep testing", MsgBoxStyle.OkCancel)
If keepOpen = 1 Then
Close()
End If
End If
As seen in line 2, the attachment is added to the email, and I do not attempt to delete the attachment until after the email is sent, however when the code is running, it throws an error that the file is being used by another process.
I am also wondering if this could be lingering from the .zip being created itself. Here is the code that does that:
Public Sub Zipping()
'Copies files to the folder where they will be zipped from
My.Computer.FileSystem.CopyFile(unalteredPath, outputs & "\ExIpOutput.txt")
My.Computer.FileSystem.CopyFile(unalteredPath1, outputs & "\IpConfig.txt")
'Deletes the old output files
My.Computer.FileSystem.DeleteFile(unalteredPath)
My.Computer.FileSystem.DeleteFile(unalteredPath1)
'Starts the zip Sub
ZipFile.CreateFromDirectory(outputs, zipPath, CompressionLevel.Fastest, True)
My.Computer.FileSystem.DeleteDirectory(outputs, FileIO.DeleteDirectoryOption.DeleteAllContents)
End Sub
Here is the CreateFromDirectory sub:
Public Shared Sub CreateFromDirectory(sourceDirectoryName As String, destinationArchiveFileName As String, compressionLevel As Compression.CompressionLevel, includeBaseDirectory As Boolean)
End Sub
Is there something I'm missing here, or do I need to have the program sleep for a bit to let the email send, then delete the .zip file?
You can load the file into an array: File.ReadAllBytes(String) Method.
Then get a MemoryStream from that: How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?
And finally, you can use a MemoryStream for an attachment: Attach a file from MemoryStream to a MailMessage in C#.
As the data to be sent is in memory, you should be able to delete the file. Note that if there is a crash, the data is gone.
The examples are in C#, but if you have problems using the methods in VB.NET, please edit your question to show how far you've got and tell us what the problem is.
A better solution to this issue is to dispose the Attachment object that is locking the file. Any object you create that has a Dispose method should have that method called when you're done with the object and an Attachment is no different.
Dim fileAttachment As Attachment
If Label6.Text = "" Then
fileAttachment = New Attachment(zipPath)
mail.Attachments.Add(fileAttachment)
End If
'...
SmtpServer.Send(mail)
If fileAttachment IsNot Nothing Then
fileAttachment.Dispose()
End If

VB.net UploadFile

I am trying to send a file up to a server using VB.net. I have found many examples exclaiming it to be simple to do but none of the examples I have found have worked.
The current one I am trying is in the following code:
Dim WithEvents wc As New System.Net.WebClient()
Private Sub oWord_DocumentBeforeClose(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean) Handles oWord.DocumentBeforeClose
Try
Using wc As New System.Net.WebClient()
wc.Credentials = New NetworkCredential("ehavermale", "ernie1")
wc.UploadFile("http://192.168.95.1:83/GraphTest.txt", "C:\Users\EHovermale\Desktop\GraphTest.txt")
End Using
Catch ex As Exception
MsgBox("Error:" + ex.Message)
End Try
'System.IO.File.Delete("C:\Users\EHovermale\Desktop\GraphTest.txt")
MsgBox("See Ya")
End Sub
When I run this program I get the Error: An Exception has occurred during a WebClient Request.
I have access to read/write files to the server I am trying to hit.
Is there another way to upload files or is something wrong with my code for this way?
Thank you!
Since there is no HTTP service to handle the file upload, you could save the file directly using VBA's Scripting.FileSystemObject. This will work if you can access the network share from wherever your document is located. Remember that if the document is moved to another computer then this may not work.
Public Sub MoveFile()
Dim fso As Object
Dim sourceFile As String
Dim targetFile As String
' You must add reference to "Microsoft Scripting Runtime" to your document
' Tools > References... > scroll down the item.
Set fso = CreateObject("Scripting.FileSystemObject")
sourceFile = "C:\Users\davidr\Desktop\foo.txt"
targetFile = "\\192.168.95.1:83\foo.txt"
' Test if destination file already exists
If fso.FileExists(targetFile) Then
MsgBox ("This file exists!")
Exit Sub
End If
' Move the file
fso.CopyFile sourceFile, targetFile
Set fso = Nothing
End Sub

FtpWebRequest.GetRequestStream hang up and fails.

I have wrote a web service, in a nutshell it uses openpop to get email messages does stuff with the content to insert into databases and saves attachments which are images. That works fine when i save images locally, it does exactley what it is suppose to. Now an added requirment was to save images to an FTP directory, so i can create my folders dynamically (they are created based upon timestamp) and that works well. My problem comes from when i try to save them to the ftp. Yes my user name and password are correct, otherwise i wouldn't be creating the directory.
Private Sub UploadFile(ByVal fileToSave As FileInfo, ByVal path As String)
Dim UploadRequest As FtpWebRequest = DirectCast(WebRequest.Create("ftp://UserName:Passowrd#999.99.999.9" & path), FtpWebRequest)
UploadRequest.Credentials = New NetworkCredential("PicService", "grean.matching18")
UploadRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
UploadRequest.UseBinary = True
UploadRequest.UsePassive = True
' Const BufferSize As Integer = 2048
' Dim content(BufferSize - 1) As Byte, dataRead As Integer
Dim bFile() As Byte = System.IO.File.ReadAllBytes(fileToSave.ToString)
'UploadRequest.ContentLength = content.Length
Using FileStream1 As FileStream = fileToSave.OpenRead()
Try
'open request to send
Using RequestStream As Stream = UploadRequest.GetRequestStream
End Using
Catch ex As Exception
Finally
'ensure file closed
FileStream1.Close()
End Try
End Using
End Sub
I have tried using Passive False and Binary False as well, i did more research on my stack trace.
And found this article but no solution as of yet. Any input would be appreciated, i am also posting another question on windows services for different issue. If you would like to take a shot at it, the other question isnt about ftp but permissions for a service on windows server 2003
This may not be the solution but I've found that the URI string has to be 'just right' and that what is 'just right' varies by the ftp server.
So ftp://server/directory/file works on some servers but needs to be ftp://server//directory/file to work on others (note the double slash after the server name)
Aso, your URI has 'password' spelled incorrectly: ftp://UserName:Passowrd#999.99.999.9 and you are supplying the credentials in a separate code line as well.