Cities - persistence Learn programming Visual Basic (VB.net)

Lesson:

Object Persistence


Exercise:

Cities - persistence 15


Objetive:

Create a new version of the "cities database" (which you improved on March 13th), using persistence to store its data instead of text files.


Code:

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Namespace PersistenceCities
    [Serializable]
    Class City
        Private name As String
        Private inhabitants As UInteger

        Public Sub New()
        End Sub

        Public Sub New(ByVal name As String, ByVal inhabitants As UInteger)
            Me.name = name
            Me.inhabitants = inhabitants
        End Sub

        Public Property Name As String
            Get
                Return name
            End Get
            Set(ByVal value As String)
                name = value
            End Set
        End Property

        Public Property Inhabitants As UInteger
            Get
                Return inhabitants
            End Get
            Set(ByVal value As UInteger)
                inhabitants = value
            End Set
        End Property
    End Class
End Namespace

Namespace PersistenceCities
    Class Serializador
        Private nombre As String

        Public Sub New(ByVal nombreFich As String)
            nombre = nombreFich
        End Sub

        Public Sub Guardar(ByVal objeto As City)
            Dim formatter As IFormatter = New BinaryFormatter()
            Dim stream As Stream = New FileStream(nombre, FileMode.Create, FileAccess.Write, FileShare.None)
            formatter.Serialize(stream, objeto)
            stream.Close()
        End Sub

        Public Function Cargar() As City()
            Dim objeto As City
            Dim formatter As IFormatter = New BinaryFormatter()
            Dim stream As Stream = New FileStream(nombre, FileMode.Open, FileAccess.Read, FileShare.Read)
            objeto = CType(formatter.Deserialize(stream), City)
            stream.Close()
            Return objeto
        End Function
    End Class
End Namespace

Namespace PersistenceCities
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim cities As ArrayList = New ArrayList()
            Dim currentCityNumber As Integer
            Dim [option] As String
            Dim textToSearch As String
            Dim found As Boolean
            Dim textToModify As String
            Dim finished As Boolean = False
            Dim line As String
            Dim city As City() = New City(1999) {}
            Dim count As Integer = 0

            If File.Exists("data.dat") Then
                Dim s As Serializador = New Serializador("data.dat")
                city = CType(s.Cargar(), City())
            End If

            Do
                Console.WriteLine()
                Console.WriteLine("Cities database")
                Console.WriteLine()
                Console.WriteLine("1.- Add a new city")
                Console.WriteLine("2.- View all cities")
                Console.WriteLine("3.- Modify a record")
                Console.WriteLine("4.- Insert a new record")
                Console.WriteLine("5.- Delete a record")
                Console.WriteLine("6.- Search in the records")
                Console.WriteLine("7.- Correct the capitalization of the names")
                Console.WriteLine("0.- Exit")
                Console.WriteLine()
                Console.Write("Choose an option: ")
                [option] = Console.ReadLine()

                Select Case [option]
                    Case "0"
                        finished = True
                    Case "1"
                        Console.WriteLine("Entering data for city number {0}", cities.Count + 1)
                        Console.Write("Enter the city name: ")
                        Dim newcity As City = New City()
                        newcity.Name = Console.ReadLine()
                        Console.Write("Enter the inhabitants numbers: ")
                        newcity.Inhabitants = Convert.ToUInt32(Console.ReadLine())
                        cities.Add(newcity)
                        Console.WriteLine("The data was entered correctly")
                    Case "2"

                        For i As Integer = 0 To cities.Count - 1
                            currentCity = CType(cities(i), city)
                            Console.WriteLine("{0}: {1}, {2} inhabitants", i + 1, currentCity.name, currentCity.inhabitants)
                        Next

                        Console.WriteLine()
                    Case "3"
                        Console.Write("Enter the city number: ")
                        currentCityNumber = Convert.ToInt32(Console.ReadLine())
                        currentCity = CType(cities(currentCityNumber - 1), city)
                        Console.WriteLine("Enter a new data for a city number: {0}", currentCityNumber)
                        Console.Write("City name (was {0}; hit ENTER to leave as is): ", currentCity.name)
                        textToModify = Console.ReadLine()
                        If textToModify <> "" Then currentCity.name = textToModify
                        Console.Write("Inhabitants (was {0}; hit ENTER to leave as is): ", currentCity.inhabitants)
                        textToModify = Console.ReadLine()
                        If textToModify <> "" Then currentCity.inhabitants = Convert.ToUInt32(textToModify)
                        cities(currentCityNumber - 1) = currentCity
                        Console.WriteLine()
                    Case "4"
                        Console.Write("Enter the number of the city to modify: ")
                        currentCityNumber = Convert.ToInt32(Console.ReadLine())
                        currentCity = CType(cities(currentCityNumber - 1), city)
                        Console.WriteLine("Insert a new data at {0} position: ", currentCityNumber)
                        Console.Write("City name: ")
                        currentCity.name = Console.ReadLine()
                        Console.Write("Inhabitants: ")
                        currentCity.inhabitants = Convert.ToUInt32(Console.ReadLine())
                        cities.Insert(currentCityNumber - 1, currentCity)
                    Case "5"
                        Console.Write("Enter the city number for delete: ")
                        currentCityNumber = Convert.ToInt32(Console.ReadLine())
                        Console.WriteLine("Deleting the number {0}", currentCityNumber)
                        cities.RemoveAt(currentCityNumber - 1)
                    Case "6"
                        Console.Write("Enter the text to search: ")
                        textToSearch = Console.ReadLine()
                        found = False

                        For i As Integer = 0 To cities.Count - 1
                            currentCity = CType(cities(i), city)

                            If currentCity.name.ToUpper().IndexOf(textToSearch.ToUpper()) >= 0 Then
                                Console.WriteLine("{0} found in {1}", textToSearch, currentCity.name)
                                found = True
                            End If
                        Next

                        If Not found Then Console.WriteLine("Not found.")
                    Case "7"

                        For i As Integer = 0 To cities.Count - 1
                            currentCity = CType(cities(i), city)
                            Dim lowerCaseName As String = currentCity.name.ToLower()
                            Dim correctedName As String = lowerCaseName.Substring(0, 1).ToUpper() & lowerCaseName.Substring(1)

                            For j As Integer = 1 To correctedName.Length - 2 - 1
                                If correctedName(j) = " "c Then correctedName = correctedName.Substring(0, j) & " " & correctedName.Substring(j + 1, 1).ToUpper() & correctedName.Substring(j + 2)
                            Next

                            currentCity.name = correctedName
                        Next

                    Case Else
                        Console.WriteLine("Wrong option ")
                End Select
            Loop While Not finished

            outputFile = File.CreateText("data.dat")

            For i As Integer = 0 To cities.Count - 1
                currentCity = CType(cities(i), city)
                outputFile.WriteLine(currentCity.name)
                outputFile.WriteLine(currentCity.inhabitants)
            Next

            outputFile.Close()
        End Sub
    End Class
End Namespace