Sunday, October 3, 2010

ItemDone

a simple dialog shows progress on top most window
the progress calculation based on keyword of 'item' and 'done' in a text file.




Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading

Public Class MainFrm
Private strFilePath As String = "c:\itemdone.txt"
Private iIntervalSec As Integer = 5
Private datLastWriteTime As Date
Private strItemKeyword As String = "#item:"
Private strDoneKeyword As String = "#done"
Private iItemsCount As Integer = 0
Private iDoneCount As Integer = 0
Private Thrd As Thread

Private Sub MainFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.TopMost = True

Dim args As String() = Environment.GetCommandLineArgs()
For Each arg As String In args
If arg.StartsWith("/f:") Then
strFilePath = arg.Replace("/f:", "")
ElseIf arg.StartsWith("/t:") Then
If Integer.TryParse(arg.Replace("/t:", ""), iIntervalSec) = False Then
iIntervalSec = 5
End If
ElseIf arg.StartsWith("/ik:") Then
strItemKeyword = arg.Replace("/ik:", "")
ElseIf arg.StartsWith("/dk:") Then
strDoneKeyword = arg.Replace("/dk:", "")
End If
Next

'// set title
Me.Text = strFilePath

'// Thread begin
Dim TStart As New ThreadStart(AddressOf ThreadMain)
Thrd = New Thread(TStart)
Thrd.Priority = ThreadPriority.Highest
Thrd.Start()
End Sub

Private Sub MainFrm_Disposed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Disposed
If Thrd.IsAlive Then
Thrd.Abort()
Thrd = Nothing
End If
End Sub


Private Sub ThreadMain()
Try
While True
UpdateProgress()
Threading.Thread.Sleep(iIntervalSec * 1000)
End While
Catch ex As Exception
Console.WriteLine(ex.ToString)
Console.WriteLine(ex.Message)
End Try
End Sub

Private Sub UpdateProgress()
Dim myReader As StreamReader
Try

Dim fi As FileInfo = New FileInfo(strFilePath)
Dim bToGo As Boolean = False

'// now - save < interval
If datLastWriteTime = Nothing Then
bToGo = True
End If
If fi.LastWriteTime.AddSeconds(iIntervalSec) < Date.Now Then
bToGo = True
End If


If bToGo Then
'// file open
myReader = File.OpenText(strFilePath)
Dim strContent As String = myReader.ReadToEnd
myReader.Close()

'// count "#item:"
Dim regularExpression As Regex = New Regex(strItemKeyword)
Dim matchResult As MatchCollection = regularExpression.Matches(strContent)
iItemsCount = matchResult.Count
Me.lbItems.Text = iItemsCount.ToString

'// count "#done:"
regularExpression = New Regex(strDoneKeyword)
matchResult = regularExpression.Matches(strContent)
iDoneCount = matchResult.Count
Me.lbDone.Text = iDoneCount.ToString

If iDoneCount = 0 Then
Me.lbProgress.Text = "0 %"
Else
Me.lbProgress.Text = String.Format("{0:f2} %", (iDoneCount / iItemsCount) * 100)
End If
End If

datLastWriteTime = Date.Now

Catch ex As Exception
Console.WriteLine(ex.ToString)
Console.WriteLine(ex.Message)
Exit Sub
End Try
End Sub
End Class

No comments: