Merge pdf using Docotic.Pdf Library - pdf

I already have a class that does this but I want you to finish programming a NEW class using the Docotic.Pdf Library Their website for your reference is: http://bitmiracle.com/pdf-library/
this code which I write.
`Public Class Form1
Private Sub butMergePdfs_Click(sender As System.Object, e As System.EventArgs) Handles butMergePdfs.Click
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Load some sample PDF files into the string arrays
'In production it will read the files into the string arrays
'from a database.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim strMergeFiles(3) As String
Dim strMergeTitles(3) As String
strMergeFiles(0) = "D:\Nayeem_Mansoori\Cis_Projects\Cis_Projects\SanjayVerma\PdfMergeTest\PDF_1.pdf"
strMergeFiles(1) = "D:\Nayeem_Mansoori\Cis_Projects\Cis_Projects\SanjayVerma\PdfMergeTest\PDF_2.pdf"
strMergeFiles(2) = "D:\Nayeem_Mansoori\Cis_Projects\Cis_Projects\SanjayVerma\PdfMergeTest\PDF_3.pdf"
'strMergeFiles(0) = "C:\Temp\PDF_1.pdf"
'strMergeFiles(1) = "C:\Temp\PDF_2.pdf"
'strMergeFiles(2) = "C:\Temp\PDF_3.pdf"
strMergeTitles(0) = "OUTLINE_1"
strMergeTitles(1) = "OUTLINE_2"
strMergeTitles(2) = "OUTLINE_3"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'This shows how the old class worked. The new class needs to work
'with exactly the same parameters.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Dim myMerge As New clsMerge_OLD
'Dim strFileName As String = System.IO.Path.GetRandomFileName & ".pdf"
'Dim strOutputFileAndPath As String = "C:\temp\" & strFileName
Dim myMerge As New clsMerge_NEW
Dim strFileName As String = System.IO.Path.GetRandomFileName & ".pdf"
Dim strOutputFileAndPath As String = "C:\temp\" & strFileName
'Merge the files.
myMerge.MergeFiles(strMergeFiles, strMergeTitles, strOutputFileAndPath)
'Shop any merge errors.
If myMerge.Errors <> "" Then
MsgBox(myMerge.Errors)
End If
'Open the merged PDF
Process.Start(strOutputFileAndPath)
myMerge = Nothing
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)
MsgBox(System.IO.Directory.GetCurrentDirectory())
End Sub
End Class
Imports BitMiracle.Docotic.Pdf
Public Class clsMerge_NEW
Private mstrErrors As String
Private mboolCurrentFileIsIrefStream As Boolean
Private mboolPadPageCountToEven As Boolean
Private mRand As Random
Public ReadOnly Property Errors() As String
Get
Return mstrErrors
End Get
End Property
Public Sub New()
mstrErrors = ""
End Sub
Public Function MergeFiles(ByVal SourceFiles() As String _
, ByVal SourceTitles() As String _
, ByVal DestinationFile As String) As Boolean
Dim boolReturnVal As Boolean = True
'clear error variable
mstrErrors = ""
'If the destination merged PDF file exists, then delete it.
Try
If System.IO.File.Exists(DestinationFile) = True Then
System.IO.File.Delete(DestinationFile)
End If
Catch ex As Exception
mstrErrors = mstrErrors & " Cannot delete destination file:" & DestinationFile & ". Error is: " & ex.Message & vbCrLf
boolReturnVal = False
End Try
If boolReturnVal = True Then 'if still true then continue!
'Iterate the string array.
For i As Int32 = 0 To UBound(SourceFiles) - 1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
' !!!! FINISH THIS CODE - MERGE THE PDF's !!!!!!!
'
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Ensure OUTLINES are created in the destination PDF file!!!!!
'The TITLES passed in SourceTitles are the OUTLINES.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Next
End If
Return boolReturnVal
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'
' Here is a C# example of how to use the class.
'
'-------------------------------------------------------------------------------
'
' using (PdfDocument pdf = new PdfDocument())
' {
' pdf.PageMode = PdfPageMode.UseOutlines;
' pdf.Append("d:\\0000-2981A.pdf");
'
' pdf.Append("d:\\0000-2981B.pdf");
' pdf.RemovePage(0);
'
'
' PdfOutlineItem root = pdf.OutlineRoot;
'
' for (int i = 0; i < pdf.PageCount; ++i)
' {
' int pgcount = i + 1;
' PdfOutlineItem outlineForPage = root.AddChild("Page " + pgcount.ToString(), i);
' }
'
' pdf.Save(pathToFile);
' }
End Class
Please can any one help me.

Your question could be more specific. I am not sure I understood it right, but please try following sample code.
The sample code combines different documents into one PDF file and creates bookmarks. Each bookmark points to the first page of original document. Bookmarks titles are provided as parameter to the function.
Please note that the code is auto-converted from C#.
Public Shared Sub MergeFiles(sourceFiles As String(), bookmarkTitles As String(), destination As String)
Using pdf As New PdfDocument()
Dim targetPageIndex As Integer = 0
For i As Integer = 0 To sourceFiles.Length - 1
Dim currentName As String = sourceFiles(i)
If i = 0 Then
pdf.Open(currentName)
Else
pdf.Append(currentName)
End If
pdf.OutlineRoot.AddChild(bookmarkTitles(i), targetPageIndex)
targetPageIndex = pdf.PageCount
Next
pdf.PageMode = PdfPageMode.UseOutlines
pdf.Save(destination)
End Using
End Sub
Here is the C# version for the reference:
public static void MergeFiles(string[] sourceFiles, string[] bookmarkTitles, string destination)
{
using (PdfDocument pdf = new PdfDocument())
{
int targetPageIndex = 0;
for (int i = 0; i < sourceFiles.Length; i++)
{
string currentName = sourceFiles[i];
if (i == 0)
pdf.Open(currentName);
else
pdf.Append(currentName);
pdf.OutlineRoot.AddChild(bookmarkTitles[i], targetPageIndex);
targetPageIndex = pdf.PageCount;
}
pdf.PageMode = PdfPageMode.UseOutlines;
pdf.Save(destination);
}
}

Related

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

Proxy Authenticaton VBA - How to not prompt?

I track POD's Online. I do it from behind a proxy and use Microsoft Access in a query to execute the function to download the tracking information and parse it out. The base code is below. The function I use is TrackNew(trackingNumber). Each morning when I run this access.exe is asking for my credentials. I track from UPS and FedEx xml gateways and it doesn't ask for the proxy credentials. Is there a way that I can add the credentials inside my code so it doesn't prompt for this?
Here at the top is everything that makes this work. At the bottom is the actual function.
Private Enum HTTPequestType
HTTP_GET
HTTP_POST
HTTP_HEAD
End Enum
#If VBA7 Then
' 64-bit
Private Declare PtrSafe Function InternetGetConnectedState Lib "wininet"
(ByRef dwflags As LongPtr, _
ByVal dwReserved As Long) As Long
#Else
' pre 64-bit
Private Declare PtrSafe Function InternetGetConnectedState Lib "wininet"
(ByRef dwflags As Long, _
ByVal
dwReserved As Long) As Long
#End If
Private Const CONNECT_LAN As Long = &H2
Private Const CONNECT_MODEM As Long = &H1
Private Const CONNECT_PROXY As Long = &H4
Private Const CONNECT_OFFLINE As Long = &H20
Private Const CONNECT_CONFIGURED As Long = &H40
' Application Objects
Private xl As Access.Application
' misc symbols
Private Const CHAR_SPACE As String = " "
Private Const CHAR_UNDERSCORE As String = "_"
Private Const CHAR_COMMA As String = ","
Private Const CHAR_SLASH As String = "/"
Private Const AT_SYMBOL As String = "#"
' list of carriers (must be UPPER CASE, comma-delimited)
Private Const CARRIER_LIST As String =
"UPS,UPS1,UPS2,UPS3,UPS4,UPS5,UPS6,UPS7,UPS8,NEW,DHL,DHL1,FEDEX,FEDEX2,FEDEX3,FEDEX4,FEDEX5,HOLLAND,CONWAY,ABF,CEVA,USPS,TNT,YRCREGIONAL,YRC,NEMF,A1,RWORLDCOURIER,BLUEDART,TCIXPS,PUROLATOR,EXPINT,CMACGM,SAFM,PLG,DHL,ONTRAC,AAACT,RLC,ODFL,SAIA,DHLGLOBAL,LASERSHIP"
' MSXML stuff
Private Const MSXML_VERSION As String = "6.0"
' error Msgs
Private Const UNKNOWN_CARRIER As String = "Unknown carrier"
Private Const ERROR_MSG As String = "Error"
Private Const PACKAGE_NOT_FOUND As String = "Package Not Found"
Private Const MSIE_ERROR As String = "Cannot start Internet Explorer."
Private Const MSXML_ERROR As String = "Cannot start MSXML 6.0."
Private Const MSHTML_ERROR As String = "Cannot load MSHTML Object library."
' URLs for each carrier
Private Const NEWUrl As String = "https://www.newpenn.com/embeddable-tracking-results/?track="
'
' system functions
'
Private Function GetAppTitle() As String
GetAppTitle = App.Title & " " & App.Major & "." & App.Minor & "." & App.Revision
End Function
Private Function IsWindowsOS() As Boolean
' true if operating system is Windows
IsWindowsOS = (GetWindowsOS Like "*Win*")
End Function
'
' required addin procedures
'
Private Sub AddinInstance_OnAddInsUpdate(custom() As Variant)
' needed for operation
Exit Sub
End Sub
Private Sub AddinInstance_OnStartupComplete(custom() As Variant)
' needed for operation
Exit Sub
End Sub
' helper functions
Private Function GetRequestType(reqType As HTTPequestType) As String
Select Case reqType
Case 1
GetRequestType = "POST"
Case 2
GetRequestType = "HEAD"
Case Else ' GET is default
GetRequestType = "GET"
End Select
End Function
Private Function IsValidCarrier(CarrierName As String) As Boolean
' returns TRUE if the given carrier is on the global list
Dim carriers() As String
carriers = Split(CARRIER_LIST, ",")
IsValidCarrier = (UBound(Filter(carriers, CarrierName)) > -1)
End Function
Private Function GetHTMLAnchors(htmlDoc As Object) As Object ' MSHTML.IHTMLElementCollection
On Error Resume Next
Set GetHTMLAnchors = htmlDoc.anchors
End Function
Private Function LoadError(xmlDoc As Object) As Boolean
' checks if a xml file load error occurred
LoadError = (xmlDoc.parseError.ErrorCode <> 0)
End Function
Private Function GetRootNode(xmlDoc As Object) As Object
' returns root node
Set GetRootNode = xmlDoc.DocumentElement
End Function
Private Function GetNode(parentNode As Object, nodeNumber As Long) As Object
On Error Resume Next
' if parentNode is a MSXML2.IXMLDOMNodeList
Set GetNode = parentNode.Item(nodeNumber - 1)
' if parentNode is a MSXML2.IXMLDOMNode
If GetNode Is Nothing Then
Set GetNode = parentNode.ChildNodes(nodeNumber - 1)
End If
End Function
Private Function CreateFile(fileName As String, contents As String) As String
' creates file from string contents
Dim TempFile As String
Dim nextFileNum As Long
nextFileNum = FreeFile
TempFile = fileName
Open TempFile For Output As #nextFileNum
Print #nextFileNum, contents
Close #nextFileNum
CreateFile = TempFile
End Function
Here is where it prompts me for the windows domain credentials for the proxy.
Private Function GetResponse(xml As Object, requestType As HTTPequestType, _
destinationURL As String, Optional async As Boolean, _
Optional requestHeaders As Variant, Optional postContent As String) As String
Dim reqType As String
Dim response As String
Dim i As Long
reqType = GetRequestType(requestType)
With xml
.Open reqType, destinationURL, async
' check for headers
If Not IsMissing(requestHeaders) Then
For i = LBound(requestHeaders) To UBound(requestHeaders)
.setRequestHeader requestHeaders(i, 1), requestHeaders(i, 2)
Next i
End If
' if HTTP POST, need to send contents
' will not harm GET or HEAD requests
.Send (postContent)
' if HEAD request, return headers, not response
If reqType = "HEAD" Then
response = xml.getAllResponseHeaders
Else
response = xml.responseText
End If
End With
GetResponse = response
End Function
Private Function GetRequestHeaders() As Variant
Dim tempArray(1 To 1, 1 To 2) As Variant
tempArray(1, 1) = "Content-Type"
tempArray(1, 2) = "application/x-www-form-urlencoded"
GetRequestHeaders = tempArray
End Function
' major objects
Private Function GetMSIE() As Object ' InternetExplorer.Application
On Error Resume Next
Set GetMSIE = CreateObject("InternetExplorer.Application")
End Function
Private Function CreateHTMLDoc() As Object ' MSHTML.HTMLDocument
On Error Resume Next
Set CreateHTMLDoc = CreateObject("htmlfile")
End Function
Private Function GetMSXML() As Object ' MSXML2.XMLHTTP60
On Error Resume Next
Set GetMSXML = CreateObject("MSXML2.XMLHTTP" & IIf(Len(MSXML_VERSION) = 0, "", "." & MSXML_VERSION))
End Function
Private Function GetServerMSXML() As Object
On Error Resume Next
Set GetServerMSXML = CreateObject("MSXML2.ServerXMLHTTP" &
IIf(Len(MSXML_VERSION) = 0, "", "." & MSXML_VERSION))
End Function
Private Function CreateXMLDoc() As Object ' MSXML2.DOMDocument60
On Error Resume Next
Set CreateXMLDoc = CreateObject("MSXML2.DOMDocument" & IIf(Len(MSXML_VERSION) = 0, "", "." & MSXML_VERSION))
End Function
' XMLHTTP or MSIE
'''''Private Function GetMSXMLWebResponse(URL As String) As String
''''' Dim webObject As Object ' MSXML2.XMLHTTP60
''''' Set webObject = GetMSXML
''''' If webObject Is Nothing Then ' cannot start MSXML6
''''' Exit Function
''''' End If
''''' ' open URL and scrape result
''''' With webObject
''''' .Open "GET", URL, False
''''' .send
''''' End With
''''' GetMSXMLWebResponse = webObject.responseText
'''''End Function
Private Function GetMSIEWebResponse(URL As String) As String
Dim webObject As Object ' InternetExplorer.Application
Set webObject = GetMSIE
If webObject Is Nothing Then ' cannot start MSIE
Exit Function
End If
'open the url
webObject.navigate URL
'wait for the site to be ready
Do Until webObject.readyState = 4 ' READYSTATE_COMPLETE
DoEvents
Loop
'read the text from the body of the site
GetMSIEWebResponse = webObject.Document.body.innerText
webObject.Quit
End Function
Here is the actual tracking code:
Private Function TrackNEW(trackingNumber As String) As String
Dim xml As Object
Dim tempString As String
Dim htmlDoc As Object ' MSHTML.HTMLDocument
Dim htmlBody As Object ' MSHTML.htmlBody
Dim anchors As Object ' MSHTML.IHTMLElementCollection
Dim anchor As Object ' MSHTML.IHTMLElement
Dim dda As Object ' MSHTML.IHTMLElementCollection
Dim ddb As Object
Dim ddc As Object
Dim ddd As Object
Dim span As Object
Dim div As Object
Dim class As Object ' MSHTML.IHTMLElement
Set xml = GetMSXML
If xml Is Nothing Then ' cannot start MSXML 6.0
TrackNEW = MSXML_ERROR
Exit Function
End If
tempString = GetResponse(xml, HTTP_GET, NEWUrl & trackingNumber, False)
If Len(tempString) = 0 Then
MsgBox "5"
TrackNEW = ERROR_MSG
Exit Function
End If
Set htmlDoc = CreateHTMLDoc
If htmlDoc Is Nothing Then ' cannot reference MSHTML object library
MsgBox "6"
TrackNEW = MSHTML_ERROR
Exit Function
End If
On Error Resume Next
Set htmlBody = htmlDoc.body
htmlBody.innerHTML = tempString
Set dda = htmlDoc.getElementsByTagName("span")
Set ddb = htmlDoc.getElementsByTagName("span")
Set ddc = htmlDoc.getElementsByTagName("span")
Set ddd = htmlDoc.getElementsByTagName("div")
Item = 1
For Each Strg4 In ddd
For ItemNumber4 = 400 To 450
Strg4 = ddd.Item(ItemNumber4).innerText
If InStr(Strg4, "Projected Delivery Date") >= 1 Then
Why = ItemNumber4
Strg4 = ddd.Item(Why).innerText
GoTo Line8
Else
End If
Next ItemNumber4
Next Strg4
GoTo Line9
Exit Function
Line8:
TrackNEW = "INTRANSIT" & "|" & Right(Strg4, 11)
Exit Function
Line9:
Item = 1
For Each Strg In dda
For ItemNumber = 160 To 200
Strg = dda.Item(ItemNumber).innerText
If InStr(Strg, "DELIVERED") >= 1 Then
That = ItemNumber
Strg = dda.Item(That).innerText
GoTo Line2
Else
End If
Next ItemNumber
Next Strg
GoTo Line1
Line2:
Item2 = 1
For Each Strg2 In ddb
For ItemNumber2 = 160 To 200
Strg2 = ddb.Item(ItemNumber2).innerText
If InStr(Strg2, "DELIVERED") >= 1 Then
This = ItemNumber2 + 3
Strg2 = ddb.Item(This).innerText
GoTo Line3
Else
End If
Next ItemNumber2
Next Strg2
GoTo Line1
Line3:
Item3 = 1
For Each Strg3 In ddb
For ItemNumber3 = 160 To 200
Strg3 = ddb.Item(ItemNumber3).innerText
If InStr(Strg3, "DELIVERED") >= 1 Then
How = ItemNumber3 + 5
Strg3 = ddc.Item(How).innerText
GoTo Line4
Else
End If
Next ItemNumber3
Next Strg3
GoTo Line1
Line4:
TrackNEW = Strg & "|" & Strg2 & "|" & Strg3
Set xml = Nothing
Set htmlDoc = Nothing ' MSHTML.HTMLDocument
Set htmlBody = Nothing ' MSHTML.htmlBody
Set anchors = Nothing ' MSHTML.IHTMLElementCollection
Set anchor = Nothing ' MSHTML.IHTMLElement
Set dda = Nothing
Exit Function
Line1:
TrackNEW = "TRACKING|CANNOT|BE|FOUND"
Set xml = Nothing
Set htmlDoc = Nothing ' MSHTML.HTMLDocument
Set htmlBody = Nothing ' MSHTML.htmlBody
Set anchors = Nothing ' MSHTML.IHTMLElementCollection
Set anchor = Nothing ' MSHTML.IHTMLElement
Set dda = Nothing
Exit Function
End Function
Any help would be appreciated. I need the actual lines of code or reference that would get around it from prompting me for the windows credentials the proxy.
I found this snippet of code. Under the GETMSXML i could add this?
'Set GetMSXML = CreateObject("MSXML2.ServerXMLHTTP" & IIf(Len(MSXML_VERSION) = 0, "", "." & MSXML_VERSION))
'xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'GetMSXML.setProxy 2, "proxy.website.com:8080"
'GetMSXML.setProxyCredentials "user", "password"

Why does Virtual Basic say it cannot access the file?

I am creating a solid edge macro that saves a 3D file in solid edge in three different types simultaneously.
owever, I am new to vb.net some I am having some difficulty.
When I run the program, the first pop up says "this file already exists, do you want to overwrite it?".
The next pop up says "cannot access this file" and then the program stops.
Why can vb.net not access the file? It is open in solid edge in the background.
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub saveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveBtn.Click
Dim objApplication As SolidEdgeFramework.Application = Nothing
Dim objDocument As SolidEdgeFramework.SolidEdgeDocument = Nothing
Dim objPropertySets As SolidEdgeFramework.PropertySets = Nothing
Dim objProperties As SolidEdgeFramework.Properties = Nothing
Dim objProperty As SolidEdgeFramework.Property = Nothing
Dim FileName As String
Dim i, j As Integer
Dim NewFileName1 As String
Dim NewFileName2 As String
Dim NewFileName3 As String
Dim Extensions(2) As String
Extensions(0) = ".step"
Extensions(1) = ".x_t"
Extensions(2) = ".igs"
Try
objApplication = Marshal.GetActiveObject("SolidEdge.Application")
objDocument = objApplication.ActiveDocument
objPropertySets = objDocument.Properties
For i = 1 To objPropertySets.Count
objProperties = objPropertySets.Item(i)
For j = 1 To objProperties.Count
objProperty = objProperties.Item(j)
Next
Next
FileName = objProperty.Name
NewFileName1 = FileName & Extensions(0)
NewFileName2 = FileName & Extensions(1)
NewFileName3 = FileName & Extensions(2)
objDocument.SaveAs("C:\Folder", NewFileName1)
objDocument.SaveAs("C:\Folder", NewFileName2)
objDocument.SaveAs("C:\Folder", NewFileName3)
'objDocument.SaveAs(NewFileName1)
'objDocument.SaveAs(NewFileName2)
'objDocument.SaveAs(NewFileName3)
Catch ex As Exception
txt.Text = " Error"
Finally
If Not (objDocument Is Nothing) Then
Marshal.ReleaseComObject(objDocument)
objDocument = Nothing
End If
If Not (objApplication Is Nothing) Then
Marshal.ReleaseComObject(objApplication)
objApplication = Nothing
End If
End Try
End Sub
End Class

Crystal report export in excel

Having problem in my crystal report, exporting to excel. Can somebody help me how to code or any suggestion code that will catch if the file you exported is already exist?
For example, you exported lotinfo the next will be lotinfo2 then lotinfo3 etc, my code is always exporting single file and single name.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New ExcelFormatOptions
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
CrExportOptions = crypt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.Excel
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
crypt.Export()
MessageBox.Show("LOT ENTERPRISE INFORMATION IS SUCCESSFULLY EXPORTED!, LOCATED AT DRIVE C:", "PLEASE CHECK AT DRIVE C:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox("Please Select Specific date to convert!")
'MsgBox(ex.ToString)
End Try
End Sub
I've been using this function for quite some time now. Just fix it up depending on your use.
Private Function fileExists(ByVal path As String, ByVal filename As String) As String
' This function basically adds a counter when the file already exists
' eg filename
' filename(1)
' filename(2)
Dim counter As Integer = 0
Dim orginialFileName As String = System.IO.Path.Combine(path, filename)
Dim newFileName = orginialFileName
Dim extension As String = ""
Dim testIndex As Integer = 0
While File.Exists(newFileName)
counter = counter + 1
extension = newFileName.Substring(newFileName.LastIndexOf("."))
filename = filename.Substring(0, filename.LastIndexOf("."))
testIndex = filename.LastIndexOf("(")
If testIndex <> -1 Then
filename = filename.Substring(0, testIndex)
End If
newFileName = String.Format("{0}({1})", System.IO.Path.Combine(path, filename), counter.ToString())
filename = String.Format("{0}({1})", filename, counter.ToString())
newFileName += extension
filename += extension
End While
Return filename
End Function
example usage
Dim output as string
output = fileExists("C:\test", "file.xls")
MsgBox(output)
This link might also be useful for you.
EDIT:
You can use it before your Try-Catch block
Dim fullPath As String = "C:\fileinfo.xls"
Dim directory, output, filename As String
If File.Exists(fullPath) Then
directory = fullPath.Substring(0, fullPath.LastIndexOf("\"))
filename = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
output = fileExists(directory, filename)
fullPath = path.combine(directory,output)
End If
Then change this part
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
To
CrDiskFileDestinationOptions.DiskFileName = _
fullPath

How To Download Emails From Junk Folder Using POP3

POP Servers allow for the LIST command that returns a list of all of the emails in the mail box. Unfortunately it does not return ALL of the emails, it only returns the emails from the Inbox. So if an email lands in a junk folder it cannot find it.
Is it possible to download emails from the junk folder using POP?
This is the current class(s) that I am using:
Option Strict On
Option Explicit On
Imports System.Net, System.Text
Public Class POP3
Inherits Sockets.TcpClient
Dim Stream As Sockets.NetworkStream
Dim UsesSSL As Boolean = False
Dim SslStream As Security.SslStream
Dim SslStreamDisposed As Boolean = False
Public LastLineRead As String = vbNullString
Public Overloads Sub Connect(ByVal Server As String, ByVal Username As String, ByVal Password As String, Optional ByVal InPort As Integer = 110,Optional ByVal UseSSL As Boolean = False)
If Connected Then Disconnect()
UsesSSL = UseSSL
MyBase.Connect(Server, InPort)
Stream = MyBase.GetStream
If UsesSSL Then
SslStream = New Security.SslStream(Stream)
SslStream.AuthenticateAsClient(Server)
End If
If Not CheckResponse() Then Exit Sub
If CBool(Len(Username)) Then
Me.Submit("USER " & Username & vbCrLf)
If Not CheckResponse() Then Exit Sub
End If
If CBool(Len(Password)) Then
Me.Submit("PASS " & Password & vbCrLf)
If Not CheckResponse() Then Exit Sub
End If
End Sub
Public Function CheckResponse() As Boolean
If Not IsConnected() Then Return False
LastLineRead = Me.Response
If (Left(LastLineRead, 3) <> "+OK") Then
Throw New POP3Exception(LastLineRead)
Return False
End If
Return True
End Function
Public Function IsConnected() As Boolean
If Not Connected Then
Throw New POP3Exception("Not Connected to an POP3 Server.")
Return False
End If
Return True
End Function
Public Function Response(Optional ByVal dataSize As Integer = 1) As String
Dim enc As New ASCIIEncoding
Dim ServerBufr() As Byte
Dim Index As Integer = 0
If dataSize > 1 Then
ReDim ServerBufr(dataSize - 1)
Dim dtsz As Integer = dataSize
Dim sz As Integer
Do While Index < dataSize
If UsesSSL Then
sz = SslStream.Read(ServerBufr, Index, dtsz)
Else
sz = Stream.Read(ServerBufr, Index, dtsz)
End If
If sz = 0 Then Return vbNullString
Index += sz
dtsz -= sz
Loop
Else
ReDim ServerBufr(255)
Do
If UsesSSL Then
ServerBufr(Index) = CByte(SslStream.ReadByte)
Else
ServerBufr(Index) = CByte(Stream.ReadByte)
End If
If ServerBufr(Index) = -1 Then Exit Do
Index += 1
If ServerBufr(Index - 1) = 10 Then Exit Do
If Index > UBound(ServerBufr) Then
ReDim Preserve ServerBufr(Index + 255)
End If
Loop
End If
Return enc.GetString(ServerBufr, 0, Index)
End Function
Public Sub Submit(ByVal message As String)
Dim enc As New ASCIIEncoding
Dim WriteBuffer() As Byte = enc.GetBytes(message)
If UsesSSL Then
SslStream.Write(WriteBuffer, 0, WriteBuffer.Length)
Else
Stream.Write(WriteBuffer, 0, WriteBuffer.Length)
End If
End Sub
Public Sub Disconnect()
Me.Submit("QUIT" & vbCrLf)
CheckResponse()
If UsesSSL Then
SslStream.Dispose()
SslStreamDisposed = True
End If
End Sub
'*******************************************************************************
' Function Name : List
' Purpose : Get the drop listing from the maildrop
' :
' Returns : Any Arraylist of POP3Message objects
' :
' Typical telNet I/O:
'LIST (submit)
'+OK Mailbox scan listing follows
'1 2532 (record index and size in bytes)
'2 1610
'3 12345
'. (end of records terminator)
'*******************************************************************************
Public Function List() As ArrayList
If Not IsConnected() Then Return Nothing 'exit if not in TRANSACTION mode
Me.Submit("LIST" & vbCrLf) 'submit List request
If Not CheckResponse() Then Return Nothing 'check for a response, but if an error, return nothing
'
'get a list of emails waiting on the server for the authenticated user
'
Dim retval As New ArrayList 'set aside message list storage
Do
Dim response As String = Me.Response 'check response
If (response = "." & vbCrLf) Then 'done with list?
Exit Do 'yes
End If
Dim msg As New POP3Message 'establish a new message
Dim msgInfo() As String = Split(response, " "c) 'separate by spaces, which divide its fields
msg.MailID = Integer.Parse(msgInfo(0)) 'get the list item number
msg.ByteCount = Integer.Parse(msgInfo(1)) 'get the size of the email message
msg.Retrieved = False 'indicate its message body is not yet retreived
retval.Add(msg) 'add a new entry into the retrieval list
Loop
Return retval 'return the list
End Function
Public Function GetHeader(ByRef msg As POP3Message, Optional ByVal BodyLines As Integer = 0) As POP3Message
If Not IsConnected() Then Return Nothing
Me.Submit("TOP " & msg.MailID.ToString & " " & BodyLines.ToString & vbCrLf)
If Not CheckResponse() Then Return Nothing
msg.Message = vbNullString
Do
Dim response As String = Me.Response
If response = "." & vbCrLf Then
Exit Do
End If
msg.Message &= response
Loop
Return msg
End Function
Public Function Retrieve(ByRef msg As POP3Message) As POP3Message
If Not IsConnected() Then Return Nothing
Me.Submit("RETR " & msg.MailID.ToString & vbCrLf)
If Not CheckResponse() Then Return Nothing
msg.Message = Me.Response(msg.ByteCount)
Do
Dim S As String = Response()
If S = "." & vbCrLf Then
Exit Do
End If
msg.Message &= S
Loop
msg.ByteCount = Len(msg.Message)
Return msg
End Function
Public Sub Delete(ByVal msgHdr As POP3Message)
If Not IsConnected() Then Exit Sub
Me.Submit("DELE " & msgHdr.MailID.ToString & vbCrLf)
CheckResponse()
End Sub
Public Sub Reset()
If Not IsConnected() Then Exit Sub
Me.Submit("RSET" & vbCrLf)
CheckResponse()
End Sub
Public Function NOOP() As Boolean
If Not IsConnected() Then Return False
Me.Submit("NOOP")
Return CheckResponse()
End Function
Protected Overrides Sub Finalize()
If Not SslStreamDisposed Then
SslStream.Dispose()
End If
MyBase.Finalize()
End Sub
End Class
Public Class POP3Message
Public MailID As Integer = 0
Public ByteCount As Integer = 0
Public Retrieved As Boolean = False
Public Message As String = vbNullString
Public Overrides Function ToString() As String
Return Message
End Function
End Class
Public Class POP3Exception
Inherits ApplicationException
Public Sub New(ByVal str As String)
MyBase.New(str)
End Sub
End Class
As per the comments, the POP3 standard only allows for downloading from the "Inbox". It's not designed for anything more advanced.
The ideal solution would be to use IMAP4, if the mail server supports it.
IMAP4 allows you to save, flag, copy and delete messages, as well as allowing folders and subfolders and it does not require exclusive access.