Coustom Counter

P

Paul Ilacqua

I'm a VB6 convert with 6 months into VB2005... I'm a Database developer and
like to roll my own "counters" for my front end programs. Instead of using
IDENTITY I use my counters.
Is this code even close to being efficient or am I off base. It does work
though... I just want to get off the ground correctly with the new VB
Thanks
Paul

'-----------------------------------------------------------------------------------------------------------
Function Increment_Counter() As Integer
Dim sFile As String = "L:\Warranty\Secure\123.dat"

Dim CurrentValue As Integer = 0
Dim NewValue As Integer = 0
Dim fs As New System.IO.FileStream(sFile, IO.FileMode.Open,
IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim r As New IO.BinaryReader(fs)

fs.Lock(0, 5)

CurrentValue = (r.ReadInt32())

fs.Unlock(0, 5)
fs.Close()

fs = New System.IO.FileStream(sFile, IO.FileMode.Open,
IO.FileAccess.ReadWrite)

Dim w As New IO.BinaryWriter(fs)

NewValue = CurrentValue + 1
fs.Lock(0, 5)
w.Write(NewValue)
r = New IO.BinaryReader(fs)
CurrentValue = (r.ReadInt32())
fs.Unlock(0, 5)
r.Close()
w.Close()
fs.Close()
Return NewValue

End Function
'-----------------------------------------------------------------------------------------------------------
 
P

Paul Ilacqua

Cor....
I will look at isolated storage... I wasn't aware of it... In your opine,
is a file as I describe better offf in isolated storage?
Thanks again
Paul
 
P

Phill W.

Paul said:
I'm a Database developer and like to roll my own "counters"
for my front end programs. Instead of using IDENTITY I use my counters.

Even so, shouldn't the counters themselves be /in/ the database, along
with the data they're "indexing" into?

If you already have a database then putting anything "out" in the file
system strikes me as a [big] step backwards.

I'd use a "last number" table, something like

Create Table Last_X
( X as Integer )

(with a single row in it)

then to get the "next" number to put into a "key" column, I'd use
something like ...

update Last_X set X = X + 1;
select X [into ?] from Last_X;

.... and (possibly) wrap that up into a stored procedure of some sort, to
streamline things even further.
It does work though...

And it's probably completely reliable, too - on a single-user system.
As soon as you have to think concurrent, multiple users, managing the
contention around those "index" files is going to be a massive headache
compared to the [relative] simplicity of doing it with a table (and
having the /database/ take care of it /for/ you).

HTH,
Phill W.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top