Я хочу проверить бронирование, чтобы избежать оперлапинга - PullRequest
0 голосов
/ 17 августа 2011

Я делаю систему бронирования для спортивного клуба. Основная цель - избежать дублирования в бронировании. Мой код работает нормально, и есть только 1 случай, в котором нельзя избежать перекрытия.

Если бронирование присутствует в базе данных 12/27/2011 в 17:00 в течение 2 часов, и я пытаюсь сделать новое бронирование 12/27/2011 с 17:00 до 19:00, тогда мой код генерирует сообщение об ошибке , Даже если я попытаюсь забронировать в 4:00 вечера на 2 часа, он выдаст сообщение об ошибке, так как 2-й час будет перекрываться с уже сделанным бронированием с 5:00 до 7:00.

Теперь наступает проблемная часть. При смене дня сообщение об ошибке не генерируется, т. Е. Если бронирование было 12/27/2011 в 23:00 в течение 3 часов, оно не должно разрешать новое бронирование до 28/12/2011 2:00, но когда попытаться забронировать 28/12/2011 в 1:00 утра, он сохраняет его в базе данных и не генерирует сообщение об ошибке. Я хочу сообщение об ошибке, сгенерированное в таком случае.

Я использую два отдельных поля в базе данных, одно для времени и одно для даты. Оба они имеют тип данных DateTime.

Вот мой код:

    Dim str2 As String  ' defines string variable for taking select query

    str2 = "select booking_date, booking_time, booking_duration, game, poolno, courtno, tableno from Bookings"

    Dim dbdate, dbtime As Date                              'defines variables to store values of date and time after reading from the database
    Dim dbonlytime As Date                                  'defines variable to store just time value after separating it from DateTime value read from the database
    Dim dbpoolno, dbtblno, dbcrtno, dbgame As String        'defines variables to store values of poolno, courtno, tableno, game after reading from the database

    Dim dbdur As Integer                                    'defines variable to store duration value after reading from the database

    Dim cmd2 As New SqlCommand(str2, con)                   'defines a new sql command with str2 as query string and con as connection string
    con.Open()                                              'sets the connection state to open

    Dim bookchk As SqlDataReader = cmd2.ExecuteReader       'Defines and initiates the datareader to read data from database using cmd2 command
    While bookchk.Read()                                    ' iterates the datareader to read values of booking date, booking time, booking duration, game, poolno, courtno and tableno from the database
        dbdate = bookchk("booking_date")
        dbtime = bookchk("booking_time")
        dbonlytime = dbtime.ToLongTimeString                'Converts the DateTime value read from the database for booking time into LongTime format and stores in dbonlytime variable
        dbdur = bookchk("booking_duration")

        dbgame = bookchk("game")


        If CmboGame.SelectedItem = "Swimming" Then                  'if selected item on cmbogame is swimming then reads poolno value from database otherwise puts an empty string in the dbpoolno variable
            If bookchk("poolno") IsNot System.DBNull.Value Then
                dbpoolno = bookchk("poolno")

            End If

        Else : dbpoolno = ""

        End If

        If CmboGame.SelectedItem = "Table Tennis" Then              'if selected item on cmbogame is table tennis then reads tableno value from database otherwise puts an empty string in the dbtblno variable
            If bookchk("tableno") IsNot System.DBNull.Value Then
                dbtblno = bookchk("tableno")

            End If
        Else : dbtblno = ""
        End If
        If CmboGame.SelectedItem IsNot "Table Tennis" And CmboGame.SelectedItem IsNot "Swimming" Then   'if selected item on cmbogame is other than swimming and table tennis then reads courtno value from database otherwise puts an empty string in the dbcrtno variable
            If bookchk("courtno") IsNot System.DBNull.Value Then
                dbcrtno = bookchk("courtno")

            End If
        Else : dbcrtno = ""
        End If


        'checks if the entered values match exactly to any record in the database. If yes then generates an error message

        If TxtBookDate.Text = dbdate And TxtBookTime.Text = dbonlytime And TxtPoolNo.Text = dbpoolno And TxtCrtNo.Text = dbcrtno And TxtTblNo.Text = dbtblno And CmboGame.SelectedItem = dbgame Then
            MessageBox.Show("The date and time you have entered has already been booked " & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub

        End If

        Dim newtime, addednewtime, addeddbtime, changetime, newdate As DateTime                'defines variables 
        addeddbtime = dbonlytime.AddHours(dbdur)
        newtime = TxtBookTime.Text
        addednewtime = newtime.AddHours(TxtBookDur.Text)



        changetime = "12:00:00 AM"
        newdate = dbdate.AddDays(1)

        If TxtBookDate.Text = dbdate And TxtPoolNo.Text = dbpoolno And TxtCrtNo.Text = dbcrtno And TxtTblNo.Text = dbtblno And CmboGame.SelectedItem = dbgame And ((newtime > dbonlytime And newtime < addeddbtime) Or (addednewtime > dbonlytime And addednewtime < addeddbtime) Or (newtime > dbonlytime And newtime < addeddbtime And addeddbtime > changetime And addednewtime > dbonlytime And addednewtime < addeddbtime And TxtBookDate.Text = newdate)) Then 'the problem lies here
            MessageBox.Show("The date and time you have entered has already been booked " & vbCrLf & " Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)

            Exit Sub

        End If


    End While
    bookchk.Close()
    con.Close()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...