# VBForums CodeBank > CodeBank - Visual Basic .NET >  Trial Period code - VB.NET

## techgnome

Originally wrote this up as a reply to a thread where the OP had asked for a way to check to see if the user had used their app for X days... The problem with most approaches is that they use date comparisons. That means the user can get around it by moving the system date back. 

Here's something I threw together... it's nothing complicated, still has a loop hole, but for as basic as it is, not too bad. Rather than just storing the install or first-run date, I grab the current date, hash it, and check to see if the hash exists in the settings collection. If not, and we still have "slots" open... then it's considered to be a new date of usage, and the hash gets added to the collection. Once all of the slots have been used, the trial period is over and the function returns false.

Written in VB2008... should work in 2005, and will work in 2010 (although it's only tested in vb2008)

First the setup - From Project properties, go to the settings and create a user scoped setting "UsageDates" Set the type to "Specialized.StringCollection" and leave the default value blank.

Then add these two functions somewhere where your start up form or sub can get to them (like in the form itself, or the module where the Main sub is... where ever)

vb Code:
Private Function CheckDate(ByVal dateToCheck As Date) As Boolean
        'In reality, CheckDate would get the date (current date) itself and not have it passed in
        Dim retValue As Boolean = False 'Fail safe, default to false
        Dim usageDatesLeft As Int16 = 3 ' set it to 4 just for testing
        'Dim usageDatesLeft As Int16 = 30 ' set this to the number of days of application access 
         'Hash the date
        Dim hashedDate As String = HashDate(dateToCheck)
        'Check to see if the hash value exists in the UsageDates
         'Initialize the container if necessary
        If My.Settings.UsageDates Is Nothing Then
            My.Settings.UsageDates = New System.Collections.Specialized.StringCollection
        End If
         If My.Settings.UsageDates.Contains(hashedDate) Then
            'then we are ok...  it's already been checked
            retValue = True
            usageDatesLeft -= My.Settings.UsageDates.Count
             'sanity check... if the system date is backed up to a previous date in the list, but not the last date
            If usageDatesLeft <= 0 AndAlso My.Settings.UsageDates.IndexOf(hashedDate) <> My.Settings.UsageDates.Count - 1 Then
                retValue = False
            End If
        Else
            If My.Settings.UsageDates.Count < usageDatesLeft Then
                My.Settings.UsageDates.Add(hashedDate)
            End If
            usageDatesLeft -= My.Settings.UsageDates.Count
              'If not, and the remining count has "slots" open, add it
            If usageDatesLeft > 0 Then
                retValue = True
            Else
                'If not and tree are no more slots, tell user, exit app
                retValue = False
            End If
         End If
        'Display to the user how many days are remianing:
        MessageBox.Show(String.Format("You have {0} day(s) remaining.", usageDatesLeft))
         Return retValue
    End Function
     Private Function HashDate(ByVal dateToHash As Date) As String
        'Get a hash object
        Dim hasher As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
        'Take date, make it a Long date and hash it
        Dim data As Byte() = hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(dateToHash.ToLongDateString()))
        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New System.Text.StringBuilder()
         ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim idx As Integer
        For idx = 0 To data.Length - 1
            sBuilder.Append(data(idx).ToString("x2"))
        Next idx
         Return sBuilder.ToString
     End Function

To use it, is fairly simple... NOTE: the messageboxes in the CheckDate function were for testing... you could change CheckDate to return the number of days left, or leave it as is...
Here's how I tested it... add a button to a form (strictly for testing... in reality your main sub or the form_load event - or the from constructor - would call checkDate) and add this to the click event:

vb Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim aCount As Integer = 0
        Dim loopIt As Boolean = True
        'My.Settings.Reset() 'This is here for design time support... otherwise you won't get your app to run agin
         Do While loopIt
            MessageBox.Show(String.Format("Checking Date: {0}.", Date.Now.AddDays(aCount)))
            loopIt = CheckDate(Date.Now.AddDays(aCount))
            If Not loopIt Then
                MessageBox.Show("Trial Period Ended! Application closing!")
                Me.Close()
            Else
                MessageBox.Show("You can keep using the app")
            End If
            aCount += 1
        Loop
     End Sub

Like I said, it's not perfect, I'll provide minimal support for it, in that I'll help you get it going if you want it, but other than that, you're on your own. Ff some one wants to take it and run with it and do something worthwhile with it, or even beef it up some... go right ahead... just let me know, as it would be interesting to see what could be done with it. Or better yet, add the modifications to this thread. 

-tg

----------


## Tyr0n3

Thankyou! This is beautiful!

----------


## cnuser1

it Useful for me,thank you so much.

----------


## Dwight-Pre

Thanks!

----------


## romanos8

I have a question, when the trial finished the user can uninstall and reinstall the app again?

Also the form never show my app, only show the MessageBox when I make click on the button the MessageBox appear again and again.

----------


## techgnome

THat's because the code in the button click is just an example of how to use it,... it's up to you to incorporate it properly into your app.

-tg

----------


## SJWhiteley

What if the settings file is deleted or modified?

----------


## techgnome

> Like I said, it's not perfect


Odds are, you probably have other issues besides the trial period starting over...

-tg

----------


## vacano

it's perfect for my needs, i was able to modify it just a little to get it to do what i wanted.

Great Work!!

Thanks.

----------


## ApDev

thanks! I'll try later or when I have time!

----------


## nemuchan

I test in Smart Device Win CE 5 some syntax dont work any help?

----------


## techgnome

The code was written in VS2008 (might have been 2005, I forget)... and works against FW2.0 ... how ever it was neither tested, nor guaranteed, against CF... 

That said, since you didn't specify the errors, I can only guess as to what the problem is. So, I'll guess that the problem is that you've got some eels in your hover craft.

-tg

----------


## nemuchan

this is the error techgnome sorry for not putting it...
Smart Device WinCE5

System.Collections.Specialized.StringCollection

----------


## Norseman

question very nob question after a search of this forum.  

Where does it store this string data? 

Thanks

----------


## techgnome

as suggested by the name "My.Settings.UsageDates" ... in the settings file. (user level config file).

-tg

----------


## Norseman

thanks.

----------


## premshankar

Hi

I have used your code and it worked. However, now even when I remove the code still the application checks for the usage dates. I want to undo it. Can you help? Thanks!

----------


## Miklogak

This Project is pretty awesome. Thanks for the hard work. 

The sad part is that I was using it for some of my project, and later my users reported that they could bypass the Trial time by deleting the files inside Windows Appdata and Temprorary Folder[/B]. True enough thats what happened. But again thank you. It is very usefull for basic project thoug!

----------


## techgnome

I did say that it was basic... it does have a loop hole... that being it...  it was never meant to be be bullet proof. It will stop some people, but it won't stop those who know how to look for the config file and manipulate it. For the purposes of the thread from which I wrote it for, it was adequate. 



> Like I said, it's not perfect


-tg

----------


## t3cho

I see this thread is from 2010th . But seems as a really good method. 

The main problem with this is reinstallation ? When user reinstall aplication he can use 15 days once again ? I'm I right ?

Or is there any better method. 
Anel

----------


## Miklogak

@T3cho, I dont think its the Re-Installation. I have tested many times now after my users reported an issue, but the re-installation doesnt change anything. But as soon as use my Cleaning Tool I get to re-use the software again. Just like my users reported. I believe its because when deleting the files in APP DATA and TEMP folder then you can bypass it.

I am working on something different using the same method because its so simple. Hope I get to find a solution. If I do I will post it below this topic.

----------


## techgnome

re-installation won't change it... as Miklogak noted, it's all just in a config file in the app data folder (or more accurately it's in the user's app data folder)... so clearing that out would re-start it. If your users are savy enough to know how to go looking for it, and where to look for it, then you likely need something more. This code was written for a very basic need of a poster. It was half-way decent enough that I posted it here. Would I use it myself? not likely. I'd probably prefer something a bit more robust. If someone wants to take it and make it more tamper proof, by all means go ahead.

-tg

----------


## JuggaloBrotha

Just a suggestion, but putting it in the current user's appdata folder will cause it to only expire on that user's profile, if another user logs in and uses the app, then they will get a different expire date. Maybe that's what you want, but if not, then I would suggest putting the config file (and encrypting it of some kind) in the Public User AppData folder so it'll expire at the same time for all users on the machine.
Be sure to have the installer for your app create the config file, otherwise they'll get extra days to use it if the file is created on first run.

----------

