Lesson 13 - Diary with a database in VB.NET

Visual Basic .NET OOP Diary with a database in VB.NET

In the previous lesson, Lists in VB.NET, we learned about the List collection in Visual Basic .NET. We now know that it allows us to add new items at run-time so we don't have to worry about its size. In today's tutorial, we're going to make a program that involves storing objects in a List.

At first, I was going to have us create a user database, but we've already dealt with users several times in this course. Since we now know how to deal with dates and times, we're going to make a digital diary/journal. We'll store entries into a database and print today's and tomorrow's entries. This database won't be an "actual" database, we will cover databases later on. All it will be is a List in computer memory which will allow the user to add entries, search for them by date and remove them by specifying a date and time.

Let's create a new console application and name it Diary.

The entry

First of all, we'll have to create a class whose instances we will store. Let's name it Entry. Diary entries will be related to a certain date and time. It will also contain text, e.g.: January 12, 2016 - Walk the dog. Our class might look something like this:

Class Entry
        Public Property Occurs As DateTime
        Public Property Text As String

        Public Sub New(occurs As DateTime, text As String)
                Me.Occurs = occurs
                Me.Text = text
        End Sub

        Public Overrides Function ToString() As String
                Return Occurs & " " & Text
        End Function
End Class

All this class is meant to do is store data, so it has no methods, other than the constructor and ToString().

The database

Since our program will be a bit more complex, we'll use multiple objects to keep things nice and neat. We've already made the entry class, now let's create a Database object in which our entries will be stored. There will be a private list as there was on the Lottery application in the previous lesson. The List will be of the Entry data type this time. Our diary will allow us to add, delete and search entries by date. Let's add the Database class to the project. It will be very similar to the Lottery app from last time:

Class Database
        Private entries As List(Of Entry)

        Public Sub New()
                entries = new List(Of Entry)()
        End Sub
End Class

The class will only be used for data manipulation. It will contain an internal collection of entries that will be initialized in the constructor. We could also initialize it directly without a constructor in the attribute declaration:

Private entries As List(Of Entry) = New List(Of Entry)

Now let's add some methods that will add, delete and search an entry.

Adding an entry is very simple and straightforward:

Public Sub AddEntry(occurs As DateTime, text As String)
        entries.Add(New Entry(occurs, text))
End Sub

As for the second method, we'll allow the user to search for entries by day. The method will return the List of found entries since there could be multiple entries per day in the database. We'll be able to search for entries both by date and time or just by date. This way, we can find entries on a particular day no matter what time they occur. We'll specify our search settings using a byTime Boolean parameter. If it is False, our search will be by date only. First, we'll create a List and add entries that match the given date. We'll match either full date and time if the Boolean parameter is True, or just the Date component of it in case the Boolean parameter is False. Lastly, we'll return the list containing all related entries.

Public Function FindEntries(dateTime As DateTime, byTime As Boolean) As List(Of Entry)
        Dim found As New List(Of Entry)()
        For Each entry As Entry In entries
                ' filtered by time and date or filtered by date only
                If ((byTime) AndAlso (entry.Occurs = dateTime)) OrElse ((Not byTime) AndAlso (entry.Occurs.Date = dateTime.Date))
                        found.Add(entry)
                End If
        Next
        Return found
End Function

We'll finish up the class by adding a method that deletes entries based on a given time. We'll perform it using the FindEntries() method, iterating over its result and removing found entries from the list. We'll be deleting entries of a specific date and time so the second parameter of the FindEntries() method will be True:

Public Sub DeleteEntries(dateTime As DateTime)
        Dim found As List(Of Entry) = FindEntries(dateTime, True)
        For Each entry As Entry in found
                entries.Remove(entry)
        Next
End Sub

Diary

Now let's add the last class to our project, which will represent the diary itself. We'll name it Diary to keep things simple and clear. It will include methods for interacting with the user. Notice how we divide our application and encapsulate its individual parts. The List is encapsulated in the Database class which provides various methods that help handle its contents safely. Let's create a Database instance in our diary. This way, we separate the data logic from the user communication logic, and even that from other program inputs/outputs. The Diary class is supposed to interact with the user and pass the entered data to the database.

Let's add a private Database instance and initialize it in the constructor:

Class Diary

        Private database As Database

        Public Sub New()
                database = New Database()
        End Sub

End Class

Next, we'll add a ReadDateTime() utility method which prompts the user to enter a date and time and returns the DateTime instance set to the entered value. The only problem here is validating the user's input (date formats depend on your OS regional settings):

Private Function ReadDateTime() As DateTime
        Console.WriteLine("Enter date and time as e.g. [01/13/2016 14:00]:")
        Dim dateTime As DateTime
        While Not DateTime.TryParse(Console.ReadLine(), dateTime)
                Console.WriteLine("Error. Please try again: ")
        End While
        Return dateTime
End Function

Let's add a PrintEntries() method that will find entries for the given day and print them:

Public Sub PrintEntries(day As DateTime)
        Dim entries As List(Of Entry) = database.FindEntries(day, False)
        For Each entry As Entry In entries
                Console.WriteLine(entry)
        Next
End Sub

We will also need a method for prompting the user to enter a new entry and adding it to the database:

Public Sub AddEntry()
        Dim dateTime As DateTime = ReadDateTime()
        Console.WriteLine("Enter the entry text:")
        Dim text As String = Console.ReadLine()
        database.AddEntry(dateTime, text)
End Sub

Also, we still have to add methods for searching and deleting entries. The searching method will return a List of found entries (we will only search by date, time doesn't matter). We'll prompt the user to enter the date and pass it to the database. Then we'll display the result.

Public Sub SearchEntries()
        ' Entering the date
        Dim dateTime As DateTime = ReadDateTime()
        ' Searching for entries
        Dim entries As List(Of Entry) = database.FindEntries(dateTime, False)
        ' Printing entries
        If entries.Count() > 0 Then
                Console.WriteLine("Entries found: ")
                For Each entry As Entry In entries
                        Console.WriteLine(entry)
                Next
        Else
                ' Nothing found
                Console.WriteLine("No entries were found.")
        End If
End Sub

Deleting entries is trivial:

Public Sub DeleteEntries()
        Console.WriteLine("Entries with the same exact date and time will be deleted")
        Dim dateTime As DateTime = ReadDateTime()
        database.DeleteEntries(dateTime)
End Sub

Last of all, we'll add a method for printing a home screen, showing the current date and time and entries for today and tomorrow.

Public Sub PrintHomeScreen()
        Console.Clear()
        Console.WriteLine("Welcome to your virtual diary!")
        Console.WriteLine("Today is: {0}", DateTime.Now)
        Console.WriteLine()
        ' printing the home screen
        Console.WriteLine("Today:{0}------", vbCrLf)
        PrintEntries(DateTime.Today)
        Console.WriteLine()
        Console.WriteLine("Tomorrow:{0}---------", vbCrLf)
        PrintEntries(DateTime.Now.AddDays(1))
        Console.WriteLine()
End Sub

Now we can proudly move to Module1.vb and create an instance of the diary, knowing that everything will work as expected. We will add the main loop here including a response to the user's choice:

Sub Main((
        ' diary instance
        Dim diary As New Diary()
        Dim choice As Char = "0"C
        ' main loop
        While choice <> "4"
                diary.PrintHomeScreen()
                Console.WriteLine()
                Console.WriteLine("Choose an action:")
                Console.WriteLine("1 - Add an entry")
                Console.WriteLine("2 - Search for entries")
                Console.WriteLine("3 - Delete entries")
                Console.WriteLine("4 - End")
                choice = Console.ReadKey().KeyChar
                Console.WriteLine()
                ' reaction to the choice
                Select Case choice
                        Case "1"
                                diary.AddEntry()
                        Case "2"
                                diary.SearchEntries()
                        Case "3"
                                diary.DeleteEntries()
                        Case "4"
                                Console.WriteLine("Press any key to quit the program...")
                        Case Else
                                Console.WriteLine("Error. Press any key to choose another action.")
                End Select
                Console.ReadKey()
        End While
End Sub

The code above isn't complicated at this point since we've already made similar applications in previous lessons. I gave the finalized app to my girlfriend as a present, here's what it looks like :)

Console application
Welcome to diary!
Today is: 5/12/2016 11:34:55

Today:
-----
5/12/2016 10:00:00 Shopping - Pankrac Arcade
5/12/2016 7:30:00 PM - Pet my Yorkshire Terrier Fred

Tomorrow:
--------
5/13/2016 2:00:00 PM Go jogging


Choose an action:
1 - Add an entry
2 - Search for entries
3 - Delete entries
4 - End
2
Enter date and time as e.g. [1/13/2016 10:00]
5/15/2016
Found entries:
5/15/2016 9:30:00 Economy exam

Now you know how to use List and rest assured that it will suffice as data storage container for a quite a long time. In conclusion, I'd like to congratulate you in now being able to create in-memory databases. Use it for anything you want! You could, for example, use it on the User class from the Properties lesson or pretty much anything else. You can store articles, tasks, elephants, anything you want to manage in the database. What's up next, you may ask? Next time, in Interfaces in VB.NET, we'll be talking about interfaces. There's still a lot to learn about OOP :)


 

 

Article has been written for you by Michal Zurek
Avatar
Do you like this article?
1 votes
Thumbnail
Previous article
Lists in VB.NET
Thumbnail
All articles in this section
Object-oriented programming in VB.NET
Activities (6)

 

 

Comments

Avatar
Chen 琛
Member
Avatar
Chen 琛:26. April 3:31

Nice example!

 
Reply 26. April 3:31
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

1 messages from 1 displayed.