Automate scanning from multiple scanners on the same computer using WIA and VB - vb.net

Hello Stack overflow !
I'm the ultimate beginner in programming. I have some experience in php and vba, doing my own scripts as I need them, especially in excel.
Recently, for a project at works, I need to be able to scan AUTOMATICALLY (say every 2 minutes) from multiple scanners (say 2 for starters) both connected to the same computer.
I decided to use this project as a start point for me to get a feeling of Visual Basic.
So here we go, I installed visual studio express 2010 and started writing my script trying to find here and there bits of codes that could help me. I found that WIA could help with that (Twain could as well but it seems much more obscure to the newbie I am)
Anyway, I finally came up with an app that is able to automatically scan at the set interval when only one scanner is connected. The trouble arrives when I connect more than one scanner. then, the first scan occurs correctly (Scanner 1 scans, then scanner 2 scans), but when the second scan is supposed to start, nothing happens and the scanners become inaccessible (busy).
I though maybe I forgot to "release" or "disconnect" the last scanner used. Or maybe, something remains in the scanner's buffer memory ?
I have been stuck on this issue for the last 3 days and don't know how to make it work.
here is the function that scans : (i don't past the rest as it is the UI and folder management)
Public Sub scannerloop()
'format constants
Const wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}"
Const wiaFormatPNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}"
Const wiaFormatGIF = "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}"
Const wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
Const wiaFormatTIFF = "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}"
'file format
Dim fileformat As String
If Me.FileExt.SelectedItem = "TIF" Then fileformat = wiaFormatTIFF
If Me.FileExt.SelectedItem = "JPEG" Then fileformat = wiaFormatJPEG
If Me.FileExt.SelectedItem = "BMP" Then fileformat = wiaFormatBMP
If Me.FileExt.SelectedItem = "PNG" Then fileformat = wiaFormatPNG
If Me.FileExt.SelectedItem = "GIF" Then fileformat = wiaFormatGIF
'colors
Dim colorcode As Integer
If Me.Colorbox.SelectedItem = "Black and white" Then colorcode = 4
If Me.Colorbox.SelectedItem = "Greyscale" Then colorcode = 2
If Me.Colorbox.SelectedItem = "Colour" Then colorcode = 1
'Resolution
Dim dpi As Integer
dpi = Me.dpiBox.SelectedItem
Dim horizextent = dpi * 8.2
Dim vertextent = dpi * 11.6
Dim j As String = 1
Dim DeviceManager1 = CreateObject("WIA.DeviceManager") 'wia device manager
For i = 1 To DeviceManager1.DeviceInfos.Count 'loop through all devices
If DeviceManager1.DeviceInfos(i).Type = 1 Then 'Select only scanners, not webcams etc...
'startpoint to calculate how long it is to scan
Dim ScanStart = DateAndTime.Second(Now) + (DateAndTime.Minute(Now) * 60) + (DateAndTime.Hour(Now) * 3600)
'Directory + file
Dim targetdir = Me.ProjectFolderBox.Text & "\scans\Scanner" & j & "\S" & j & "_" & Me.FilePrefix.Text & Me.CurrFileIndex & "." & Me.FileExt.SelectedItem
Form2.CurrentActionLabel.Text = "Scanning from scanner #" & j
Dim Scanner As WIA.Device = DeviceManager1.DeviceInfos(i).connect
If IsNothing(Scanner) Then
Log(Me.logfilename, Now & " | Scanner #" & j & " not found")
Else
Try
Dim Img As WIA.ImageFile
With Scanner.Items(1)
.Properties("6146").Value = colorcode '4 is Black-white,gray is 2, color 1 (Color Intent)
.Properties("6147").Value = dpi 'dots per inch/horizontal
.Properties("6148").Value = dpi 'dots per inch/vertical
.Properties("6149").Value = 0 'x point where to start scan
.Properties("6150").Value = 0 'y-point where to start scan
'Following is A4 paper size. (Not 100% accurate because real A4 Ht errors)
.Properties("6151").Value = horizextent 'horizontal exent DPI x inches wide
.Properties("6152").Value = vertextent 'vertical extent DPI x inches tall
' .Properties("4104").Value = 8 'bits per pixel
End With
'transfer image
Img = Scanner.Items(1).Transfer(fileformat) 'scans the image.
'kill previous file if exists to avoid errors
If System.IO.File.Exists(targetdir) = True Then
Kill(targetdir)
End If
Img.SaveFile(targetdir)
'last scan
Form2.LastFileLabel.Text = "\Scanner" & j & "\S" & j & "_" & Me.FilePrefix.Text & Me.CurrFileIndex & "." & Me.FileExt.SelectedItem
Form2.LastScanLabel.Text = Now
Catch ex As Exception
MsgBox(ex.Message)
Finally
Scanner = Nothing
End Try
End If
'End time for the scan
Dim ScanEnd = DateAndTime.Second(Now) + (DateAndTime.Minute(Now) * 60) + (DateAndTime.Hour(Now) * 3600)
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " | Scanned " & targetdir & " | duration: " & (ScanEnd - ScanStart))
j = j + 1
Next
DeviceManager1 = Nothing
Me.CurrFileIndex = Me.CurrFileIndex + 1
Me.ScanCount = Me.ScanCount + 1
Me.NextScan = DateAdd("n", Me.IntervalBox.Value, Now)
Form2.ScanCountLabel.Text = Me.ScanCount
Form2.NextScanLabel.Text = Me.NextScan
Form2.CurrentActionLabel.Text = "Waiting..."
'Increment next file index and update in config file
Me.FileIndexBox.Value = Me.CurrFileIndex
SaveCfg()
End Sub
Please be indulgent with me, I am aware that the code is probably a nightmare for programming pros with lots of bad stuff, but it is literally my first VB program, and I am eager to learn.
So basically, the rest of the program is a form where I enter the target directory for the scan, the filenames, resolution etc, and when I click on 'start scanning', it
- runs scannerloop one first time
- starts a 'scantimer' which launches scannerloop each time it ticks.
As I said, it works perfectly with 1 scanner (files created as expected, logfile updated, etc) but as soon as I have 2 scanners, only the first scan works and then, when scanner#1 is supposed to start scanning, it doesn't and the led of scanner#2 starts blinking (as if it was scanning, but it's not scanning)
I hope someone will be able to help me.
Thanks in advance.
Vince
UPDATE - thing that I tried which may be of interest :
I just tried to add a for loop to make it scan from both scanners several times (so, independantly from the timer and the rest of the program basically) :
Dim DeviceManager1 = CreateObject("WIA.DeviceManager") 'wia device manager
For k = 1 To 3
Dim j As String = 1
For i = 1 To DeviceManager1.DeviceInfos.Count 'loop through all devices
[...]
Next i
Next k
DeviceManager1 = Nothing
That showed that the first occurence of the loop works (scans once from each scanner) but that's it, the scanners never scan the second time and start blinking, so basically exactly the same problem.
I also tried to include the Devicemanager declaration in the new loop :
For k = 1 To 3
Dim DeviceManager1 = CreateObject("WIA.DeviceManager") 'wia device manager
Dim j As String = 1
For i = 1 To DeviceManager1.DeviceInfos.Count 'loop through all devices
[...]
Next i
DeviceManager1 = Nothing
Next k
but it did not change anything.
The next thing I did wat to log the events within the loop so that I can know where exactly things stop :
Dim DeviceManager1 = CreateObject("WIA.DeviceManager") 'wia device manager
Dim j As String = 1
For i = 1 To DeviceManager1.DeviceInfos.Count 'loop through all devices
If DeviceManager1.DeviceInfos(i).Type = 1 Then 'Select only scanners, not webcams etc...
'startpoint to calculate how long it is to scan
Dim ScanStart = DateAndTime.Second(Now) + (DateAndTime.Minute(Now) * 60) + (DateAndTime.Hour(Now) * 3600)
'Directory + file
Dim targetdir = Me.ProjectFolderBox.Text & "\scans\Scanner" & j & "\S" & j & "_" & Me.FilePrefix.Text & Me.CurrFileIndex & "." & Me.FileExt.SelectedItem
Form2.CurrentActionLabel.Text = "Scanning from scanner #" & j
Dim Scanner As WIA.Device = DeviceManager1.DeviceInfos(i).connect
If IsNothing(Scanner) Then
Log(Me.logfilename, Now & " | Scanner #" & j & " not found")
Else
Try
Dim Img As WIA.ImageFile
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " | Img initialized")
With Scanner.Items(1)
.Properties("6146").Value = colorcode '4 is Black-white,gray is 2, color 1 (Color Intent)
.Properties("6147").Value = dpi 'dots per inch/horizontal
.Properties("6148").Value = dpi 'dots per inch/vertical
.Properties("6149").Value = 0 'x point where to start scan
.Properties("6150").Value = 0 'y-point where to start scan
'Following is A4 paper size. (Not 100% accurate because real A4 Ht errors)
.Properties("6151").Value = horizextent 'horizontal exent DPI x inches wide
.Properties("6152").Value = vertextent 'vertical extent DPI x inches tall
' .Properties("4104").Value = 8 'bits per pixel
End With
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " | properties initialized")
'transfer image
Img = Scanner.Items(1).Transfer(fileformat) 'scans the image.
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " |Transfer done")
'kill previous file if exists to avoid errors
If System.IO.File.Exists(targetdir) = True Then
Kill(targetdir)
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " | deleted existing " & targetdir)
End If
Img.SaveFile(targetdir)
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " | saved " & targetdir)
'last scan
Form2.LastFileLabel.Text = "\Scanner" & j & "\S" & j & "_" & Me.FilePrefix.Text & Me.CurrFileIndex & "." & Me.FileExt.SelectedItem
Form2.LastScanLabel.Text = Now
Catch ex As Exception
MsgBox(ex.Message)
Finally
Scanner = Nothing
End Try
End If
'End time for the scan
Dim ScanEnd = DateAndTime.Second(Now) + (DateAndTime.Minute(Now) * 60) + (DateAndTime.Hour(Now) * 3600)
'log
Log(Me.logfilename, Now & " | Scanner #" & j & " | Scanned " & targetdir & " | duration: " & (ScanEnd - ScanStart))
j = j + 1
End If
Next i
and here is the logfile generated :
Scan starts 29/11/2012 9:24:31 AM | Interval :Start scanning with 5 min | Res:100 DPI |
29/11/2012 9:24:31 AM | Scanner #1 | Img initialized
29/11/2012 9:24:31 AM | Scanner #1 | properties initialized
29/11/2012 9:24:49 AM | Scanner #1 |Transfer done
29/11/2012 9:24:49 AM | Scanner #1 | saved C:\__2\scans\Scanner1\S1_img_1.TIF
29/11/2012 9:24:49 AM | Scanner #1 | Scanned C:\__2\scans\Scanner1\S1_img_1.TIF | duration: 18
29/11/2012 9:24:49 AM | Scanner #2 | Img initialized
29/11/2012 9:24:49 AM | Scanner #2 | properties initialized
29/11/2012 9:25:08 AM | Scanner #2 |Transfer done
29/11/2012 9:25:08 AM | Scanner #2 | saved C:\__2\scans\Scanner2\S2_img_1.TIF
29/11/2012 9:25:08 AM | Scanner #2 | Scanned C:\__2\scans\Scanner2\S2_img_1.TIF | duration: 19
29/11/2012 9:25:08 AM | Scanner #1 | Img initialized
29/11/2012 9:25:08 AM | Scanner #1 | properties initialized
it appears that things go wrong at this line :
Img = Scanner.Items(1).Transfer(fileformat) 'scans the image.
It looks like WIA is happy to switch from scanner 1 to 2 but refuses to come back to scanner 1 for the next round. also, I should precise, when the second scan is supposed to occur, scanner #2 blinks (and not 1 which surprises me).
Is it possible that scanner#2 is selected as "default scanner" or something like that and if so, is there a way to revert that ?
thanks for your help

this code for scanning image :"dont forget adding wiaaut.DLL from windows\sys32 to solution ref."
first check if scanner device is attached
Dim tempfile As String
Dim mydevice As WIA.Device
Dim item As WIA.Item
Dim imfile As WIA.ImageFile
Dim Commondialog1 As WIA.CommonDialog
sub check()
On Error Resume Next
Commondialog1 = New WIA.CommonDialog
mydevice = Commondialog1.ShowSelectDevice
MsgBox(mydevice.Type)
On Error GoTo Err_btnTakePicture_click
end sub
'then connect to scanner
sub scan()
'put the path and name for the location of your temp file here.
tempfile = ("d:\filename.jpg")
'the next 4 lines deletes the old temp file if it exists
Dim filesystemobject = CreateObject("Scripting.FileSystemObject")
If filesystemobject.fileExists(tempfile) Then
Kill(tempfile)
End If
'the next two lines set up the configuration
Dim Commondialog1 As New WIA.CommonDialog
mydevice = Commondialog1.ShowSelectDevice
Dim wiaFormatJPEG As String = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}"
item = mydevice.Items(1)
imfile = DirectCast(Commondialog1.ShowTransfer(item, wiaFormatJPEG, False), WIA.ImageFile)
'this line saves the picture to a specified file
imfile.SaveFile(tempfile)
MsgBox("Picture taken")
PictureBox1.ImageLocation = tempfile
Exit_btnTakePicture_click:
mydevice = Nothing
item = Nothing
Exit Sub
Err_btnTakePicture_click:
MsgBox(Err.Description, vbOKOnly + vbCritical, "Error Taking Picture")
Resume Exit_btnTakePicture_click
end sub

Related

word vba - remove manually typed list number

I have lot of documents with list number typed manually, so my intent is to remove those manual list number and the tab or space following it.
e.g
1. Text 1
1.1 Text 2
1.1.1 Text 3
1.1.1.1 Text 4
become
Text 1
Text 2
Text 3
Text 4
I'm not sure how to do this with vba and I'd really appreciate your help.
I have figured it out by using below code:
Sub RemoveManualListNumber()
Dim strInitialPar As String
Dim intSpace As Integer, intTab As Integer
Dim strFinalPar As String
Dim iPar
For iPar = 1 To ActiveDocument.Paragraphs.Count
strInitialPar = ActiveDocument.Paragraphs(iPar).Range.Text
intSpace = InStr(1, strInitialPar, " ")
intTab = InStr(1, strInitialPar, Chr(9))
Debug.Print "Paragraph " & iPar & ": " & "Index space = " & intSpace & ", Index tab = " & intTab
If intTab > 0 And intTab < intSpace Then
strFinalPar = Right(strInitialPar, Len(strInitialPar) - intTab)
Else
strFinalPar = Right(strInitialPar, Len(strInitialPar) - intSpace)
End If
ActiveDocument.Paragraphs(iPar).Range.Text = strFinalPar
Next iPar
End sub

PrintDialog ToPage should be less than the page count

I recently upgraded my computer to Windows 10, and now one of the programs is acting weird since the upgrade.
Trying to print a page range out of a PDF, and when I print pages 1 to 100 (out of 477 pages) I get an error saying ToPage should be less than the page count even though 100 is less than 477.
If I skip the page range part and just have it print all of the pages, it works fine.
Sub PrintToPaperSync(ByVal InputfilePath As String, Optional ByVal DeleteAfter As Boolean = False)
On Error GoTo sError
Dim tError As String = ""
Dim toPage As Integer = 0
Console.WriteLine("PrintToPaper " & InputfilePath)
Dim File As String = Split(InputfilePath, "\")(Split(InputfilePath, "\").Length - 1)
Dim viewer As New Syncfusion.Windows.Forms.PdfViewer.PdfDocumentView
viewer.Load(InputfilePath)
Dim print As New System.Windows.Forms.PrintDialog()
print.Document = viewer.PrintDocument
print.Document.DocumentName = File
'print 100 pages at a time
Do While toPage < viewer.PageCount
print.Document.PrinterSettings.PrintRange = Drawing.Printing.PrintRange.SomePages
print.Document.PrinterSettings.FromPage = toPage + 1
toPage += 100
print.Document.PrinterSettings.ToPage = IIf(toPage < viewer.PageCount, toPage, viewer.PageCount)
tError = "From: " & print.Document.PrinterSettings.FromPage & " | To: " & print.Document.PrinterSettings.ToPage & " | PageCount: " & viewer.PageCount & " - "
print.Document.Print()
Application.DoEvents()
Loop
viewer.Unload()
viewer.Dispose()
Console.WriteLine("Printing: " & InputfilePath)
Exit Sub
sError:
Dim ErrorStr As String = ErrorToString()
WriteLine("PrintToPaper " & tError & " " & InputfilePath & " - " & ErrorStr)
End Sub
Full text of the error:
PrintToPaper From: 1 | To: 100 | PageCount: 477 - F:\Process\LogTag-10-30-15-104122.pdf - ToPage should be less than the page count
We want to only print 100 pages at a time, because the printer begins to slow down after 100 pages for some reason.
This printing problem is caused due to the issue with Syncfusion Control. You can contact the Syncfusion Software Support team to get the issue resolved. Please follow the below link to contact Syncfusion Support Team
Click Here

Find height and width of pdf using iTextSharp

In my window application i am using Quick pdf to find height,width of pdf.please refer the below code.But sometimes quickpdf can't able to find correct value.so i want to do the task using iTextSharp. How to find pdf height,width using iTextSharp?
Try
Dim qp1 As New iSED.QuickPDF
Dim sPDFHei, sPDFWid As Double
Dim iPgCnt As Integer
qp1.UnlockKey("6510E9D5C3938A920B3A8D7293C6DF00")
qp1.LoadFromFile(sFilePath & "\" & cmbArticles.Text)
qp1.SetMeasurementUnits(0)
iPgCnt = qp1.PageCount
For i As Integer = 1 To iPgCnt
'MsgBox("pagecount=" & iPgCnt)
qp1.SelectPage(i)
'MsgBox("PageNumber=" & i)
sPDFHei = qp1.PageHeight : sPDFWid = qp1.PageWidth
sPDFHei = Math.Round(sPDFHei, 2) : sPDFWid = Math.Round(sPDFWid, 2)
''If sPDFWid <> 8.26 And sPDFHei <> 11.69 Then
If sPDFWid > 520 Or sPDFHei > 600 Then
MsgBox("Article PDF size should not exit 7.22 x 8.33" & vbCrLf & "Problem in template:" & i)
Exit Function
End If
Next
qp1.clear()
Checkpdfsize = True
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "CheckPdfSize")
End Try
Thanks in Advance
Youll find what you need in chapter 6 of their documentation here. Its under Action by the way.

VBA Text File Input for Reading and Writing

I'm writing in VB 2010 with a form with one button to be completely idiot. I haven't done VB in awhile and noticed 2010 has a lot of changes compare when I did it a couple of years ago.
What I need done is it to read from a file and write two new separate files while writing to original. It will read from a text file to get some contents and compare the current date.
The text content will be a serial and the next two columns will be dates.
Dim iFileName As New StreamReader("G:\SAP In and Out\test.txt", False)
Dim sFileExport As New StreamWriter(DateValue(Now)) + " SAP Export", False)
Dim sFileImport As New StreamWriter(DateAdd(DateInterval.Day, 10, DateValue(Now)) + " SAP Import", False)
Dim VTS As String 'Will be used to grab the VT serial
Dim CurrentDate As Date 'Will be used to compare to grabbed dates
Dim NextDateOut As Date 'Will be used to grab next date out value
Dim NextDateIn As Date 'Will be used to grab next date in value
'Setting a consistant value with daily'
CurrentDate = DateValue(Now)
Do While Not EOF(1)
Input(iFileName),VTS,NextDateOut,NextDateIn
If CurrentDate = NextDateOut Then
'Write to the export File
sFileExport.write(VTS)
'Write under the just read line in the open file
iFileName.write(/newline + VTS + /TAB + (DateAdd(DateInterval.Day, 20, DateValue(Now)) + /tab + (DateAdd(DateInterval.Day, 30, DateValue(Now)))
ElseIf CurrentDate = NextDateIn Then
'Write to import file
sFileImport.Write(VTS)
End If
Loop
End Sub
But my syntax is off and it's obviously not running since I'm asking for help.
Please help and thanks in advance. I've been working on this for hours and haven't had any positive results yet.
Well I think its right now, but i had to add an extra function so i could test it out.
I was receiving errors o the date format because I expect you use US date format (MM/DD/YYYY) and I use UK date format (DD/MM/YYYY).
Anyway you can strip the function out as I dont think you will need it, but I've left it in anyway so you can see whats going on its quite self explanatory and simply converts between the date formats, though it was made more difficult by the fact your days and month are not two digits long (no leading zero).
I hope it helps point you in the right direction and you can chop and change it to your preference.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim iFileName As New System.IO.StreamReader("c:\temp\vttest.txt", False)
Dim iReadData As List(Of String)
Dim Buffer As String
'Read complete file into array
iReadData = New List(Of String)
Do While Not iFileName.EndOfStream()
Try
Buffer = ""
Buffer = iFileName.ReadLine()
iReadData.Add(Buffer)
Catch ex As Exception
'error or end of file
End Try
Loop
iFileName.Close()
'Not needed
'Dim VTS As String 'This is in iLineData(0) after we split the line
'Dim NextDateOut As Date 'This is in iLineData(1) after we split the line
'Dim NextDateIn As Date 'This is in iLineData(2) after we split the line
'Process
Dim iFileUpdated As New System.IO.StreamWriter("c:\temp\vttest_copy.txt", True)
Dim sFileExport As New System.IO.StreamWriter("c:\temp\vttest" & Replace(DateValue(Now), "/", "_") & " SAP Export.txt", True)
Dim sFileImport As New System.IO.StreamWriter("c:\temp\vttest" & Replace(DateAdd(DateInterval.Day, 10, DateValue(Now)), "/", "_") + " SAP Import.txt", True)
Dim iLineData() As String
'Setting a consistant value with daily'
Dim CurrentDate As Date = DateValue(Now)
Dim RowId = 0
Do While RowId < iReadData.Count()
iLineData = Split(iReadData(RowId), " ")
iFileUpdated.WriteLine(iLineData(0) & " " & iLineData(1) & " " & iLineData(2))
If CurrentDate = FormatDate(iLineData(1), "US", "UK") Then
'Write to the export File
sFileExport.WriteLine(iLineData(0))
'Write under the just read line in the open file
iFileUpdated.WriteLine(iLineData(0) & " " & (DateAdd(DateInterval.Day, 20, DateValue(Now))) & " " & (DateAdd(DateInterval.Day, 30, DateValue(Now))))
ElseIf CurrentDate = FormatDate(iLineData(2), "US", "UK") Then
'Write to import file
sFileImport.WriteLine(iLineData(0))
End If
RowId = RowId + 1
Loop
sFileExport.Close()
sFileImport.Close()
iFileUpdated.Close()
MsgBox("Finshed")
End Sub
'This section added because my PC is set to DD/MM/YYYY (UK)
'Expect yours is set to MM/DD/YYYY (US)
Function FormatDate(ThisDate As String, ThisFormat As String, ThisTargetFormat As String) As Date
Dim X As Integer = 0
Dim Day1 As Integer = 0
Dim Month1 As Integer = 0
Dim Year1 As Integer = 0
Dim Buf As String = ""
If ThisFormat = "US" Then
For X = 1 To Len(ThisDate)
If Mid(ThisDate, X, 1) = "/" Then
If Month1 > 0 Then
Day1 = Buf
Buf = ""
Else
Month1 = Buf
Buf = ""
End If
Else
Buf = Buf & Mid(ThisDate, X, 1)
End If
Next
Year1 = Buf
Else
For X = 1 To Len(ThisDate)
If Mid(ThisDate, X, 1) = "/" Then
If Day1 > 0 Then
Month1 = Buf
Buf = ""
Else
Day1 = Buf
Buf = ""
End If
Else
Buf = Buf & Mid(ThisDate, X, 1)
End If
Next
Year1 = Buf
End If
'reformat for output
If ThisFormat = "US" Then
If ThisTargetFormat = "US" Then
'USA
FormatDate = (Format(Month1, "00") & "/" & Format(Day1, "00") & "/" & Format(Year1, "0000"))
Else
'UK
FormatDate = (Format(Day1, "00") & "/" & Format(Month1, "00") & "/" & Format(Year1, "0000"))
End If
Else
If ThisTargetFormat = "US" Then
'USA
FormatDate = (Format(Month1, "00") & "/" & Format(Day1, "00") & "/" & Format(Year1, "0000"))
Else
'UK
FormatDate = (Format(Day1, "00") & "/" & Format(Month1, "00") & "/" & Format(Year1, "0000"))
End If
End If
End Function
Additionally i changed the file names so as not to overwrite the existing files (So i could compare the two files).
Most of the problems were arising from the back slashes in the dates in the FILENAMES - making the pc look for paths like /3/12 i guess it was translating the slashes into folder delimiters so I replaced them with UNDERSCORES on the fly.
Once you have edited the code to your preference you can OVERWRITE the existing file rather than generating a _copy.txt as thats how I tested with a _copy.txt in the sample.
Update
Thanks for the feedback. Well its strange that your (generated) files are empty, because in the ones I have ONE has data the other is empty. This leads me to the assumption that your tweaks may have something to do with it?
For your reference I have posted them below.
ORIGINAL FILE [VTSTEST.TXT]
VT1000 3/26/2013 4/5/2013
VT1100 3/26/2013 4/5/2013
VT2000 3/27/2013 4/6/2013
VT2200 3/27/2013 4/6/2013
COPY OF VTSTEST.TXT (after modification)
VT1000 3/26/2013 4/5/2013
VT1100 3/26/2013 4/5/2013
VT2000 3/27/2013 4/6/2013
VT2000 16/04/2013 26/04/2013
VT2200 3/27/2013 4/6/2013
VT2200 16/04/2013 26/04/2013
Note: I expect the two longer lines are the ones inserted inbetween the existing four lines of text
VTTEST06_04_2013 SAP Import.Txt
This file was empty
VTTEST27_03_2013 SAP Export.TXT
VT2000
VT2000

How to increment and print a serialized bar code in vb.net

I wrote a bar code program sometime ago with vb.net that when the end user clicks the print button, the program will open the text file that contains the ZPL bar code, increment the serial number by 1, write the new serial number back to the text file, and then print out the predetermined amount of bar codes to a zebra printer.
Now I am trying to rewrite the code so that it will print the number of bar codes the end user wants from the number they type into the PrintDialog. In my updated code, I tried putting in a DO UNTIL ......LOOP. It will print out the number of bar codes the user puts into the PrintDialog box, but it doesn't serialize. By that I mean if the user enters 5 into the PrintDialog, the program will print serial # 01 five times instead of printing 02, 03, 04, 05, 06.
Can anyone give me some pointers on how to have the program read, write, and print the desired x amount of times based on the number a user inputs into the PrintDialog?
Here is my original code:
Dim sL() As String = IO.File.ReadAllLines("C:\Labels\loop test.txt")
Dim CurrentBar(2) As String
For i = 0 To 2
CurrentBar(i) = sL(sL.Length - 3 + i)
Next
If CurrentBar(1).Length >= 28 Then
CurrentBar(1) = CurrentBar(1).Substring(0, 18) & Format(CInt(CurrentBar(1).Substring(18, 10) + 1), "0000000000") & CurrentBar(1).Substring(28)
Else
MessageBox.Show("String is not long enough!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Write the updated vaules back to the Text File
IO.File.WriteAllText("C:\Labels\loop test.txt",
CurrentBar(0) & vbNewLine &
CurrentBar(1) & vbNewLine &
CurrentBar(2))
Dim psi As New ProcessStartInfo
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = "C:\Labels\loop test.txt"
Process.Start(psi)
And here is my updated code:
Dim PrintDialog1 As New PrintDialog()
Dim psi As New ProcessStartInfo
Dim sL() As String = IO.File.ReadAllLines("C:\Labels\loop test.txt")
Dim CurrentBar(2) As String
Do Until PrintDialog1.PrinterSettings.Copies - 1
For i = 0 To 2
CurrentBar(i) = sL(sL.Length - 3 + i)
Next
If CurrentBar(1).Length >= 28 Then
CurrentBar(1) = CurrentBar(1).Substring(0, 18) & Format(CInt(CurrentBar(1).Substring(18, 10) + 1), "0000000000") & CurrentBar(1).Substring(28)
Else
MessageBox.Show("String is not long enough!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Write the updated vaules back to the Text File
IO.File.WriteAllText("C:\Labels\loop test.txt",
CurrentBar(0) & vbNewLine &
CurrentBar(1) & vbNewLine &
CurrentBar(2))
'Print the labels
'Get the number of copies to print
If (PrintDialog1.ShowDialog() = DialogResult.OK) Then
'print desired number of copies to target printer
For I = 0 To PrintDialog1.PrinterSettings.Copies - 1
psi.UseShellExecute = True
psi.Verb = "print"
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.Arguments = PrintDialog1.PrinterSettings.PrinterName.ToString()
psi.FileName = "C:\Labels\loop test.txt"
Process.Start(psi)
Next
End If
Loop
And here is my text file:
^XA
^LH20,85^BY3^AE^SN0000000001R,,Y^B3N,,60,,Y^FS
^XZ
I think your problem in your new code is that you are reading in the text file before you do the loop. At the end of the loop, you write out the new values, but never read them back in (or reuse them). Therefore, the input is always going to be what it was before the loop iterates. I think by putting
sl() = IO.File.ReadAllLines("C:\Labels\loop test.txt")
right after your Do Until statement should fix this.