comparing two ms access backend databases of an asp.net web application - asp.net

at our office we take daily backup of ASP.net application ms access backend
for the next few days we need to evaluate the changes made to records in the database tables
at the end of each day i want to compare 2 access databases first database is the backup of yesterday and second database is the backup of today
i thought of the following algorithm, please read carefully and tell me how to proceed to compare the datatables / gridviews
i need to display th rows / cells containing the differences / updates / deleted data
Imports System.Data
Imports System.Data.OleDb
Partial Class MoKoTrack
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myDB = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|database.mdb;Persist Security Info=True")
Session("CurrentDB") = myDB
myDB.open()
Dim mytables = myDB.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {})
Dim CurrentTable As String
Dim ee As Integer = mytables.Rows.Count
Dim OriginalTables(ee) As String
Dim BackupTables(ee) As String
Dim X As Integer = 0
For i = 1 To mytables.Rows.Count
CurrentTable = mytables.Rows(i - 1).Item(2).ToString
If mytables.Rows(i - 1).Item(3).ToString = "TABLE" Or mytables.Rows(i - 1).Item(3).ToString = "VIEW" Then
If CurrentTable.Contains("Backup") Then
BackupTables(X) = CurrentTable
Else
OriginalTables(X) = CurrentTable
End If
X = X + 1
End If
Next i
For i = 0 To BackupTables.Count - 1
If Not BackupTables(i) = "" Then
CompareTable(BackupTables(i))
End If
Next
myDB.Close()
End Sub
Sub CompareTable(ByVal BackupTableName As String)
Dim OriginalTable As New DataTable
Dim BackupTable As New DataTable
Dim ModificationsTable As New DataTable
Dim myDB = Session("CurrentDB")
Dim FinalSQLString = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand = New OleDbCommand(FinalSQLString, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader As IDataReader = myDBCommand.ExecuteReader()
'Dim myColumns = myReader.GetSchemaTable
'For I = 1 To myColumns.Rows.Count
' OriginalTable.Columns.Add(myColumns.Rows(I - 1).Item(0).ToString())
'Next I
BackupTable.Load(myReader)
Dim OriginalTableName = Left(BackupTableName, Len(BackupTableName) - 6)
Dim FinalSQLString2 = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand2 = New OleDbCommand(FinalSQLString, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader2 As IDataReader = myDBCommand.ExecuteReader()
OriginalTable.Load(myReader2)
'Dim myGrid As New GridView
'myGrid.DataSource = OriginalTable
'myGrid.DataBind()
'Me.form1.Controls.Add(myGrid)
'Dim myGrid2 As New GridView
'myGrid2.DataSource = BackupTable
'myGrid2.DataBind()
'Me.form1.Controls.Add(myGrid2)
For i = 0 To OriginalTable.Rows.Count - 1
For t = 0 To OriginalTable.Columns.Count - 1
Next
Next
End Sub
End Class
i am using the following VBA code to rename backup database tables into "tablebackup"
Private Sub Command0_Click()
Dim tdf As TableDef
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "MSys" Then
tdf.Name = tdf.Name & "backup"
End If
Next
End Sub

Can you add a ModifiedOn field for each table and extract the rows that have been modified since the last day. You can compare the modified ones (the ones that exist in the backup) and write out all new ones (the ones that don't).

Related

SQL data not populating in asp webform

Currently can not get any SQL data to populate the web form. When I run the report in Visual Studio preview mode, the data populates, however when running through my web app it displays nothing.
Imports System.Data.SqlClient
Public Class topvendors
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
getEntity()
' startdate.Text = DateTime.Today.ToShortDateString
End If
End Sub
Protected Sub getEntity()
Dim strConnString As String = Session("strconnection") 'ConfigurationManager.ConnectionStrings("TrialConnectionString").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "pGetProjectsByUser"
cmd.Parameters.Add("#employeeid", SqlDbType.Int).Value = Session("userid")
cmd.Parameters.Add("#reportid", SqlDbType.Int).Value = Request.QueryString("id")
cmd.Connection = con
Try
con.Open()
Dim dt As New DataTable()
Dim ds As New DataSet()
'Dim db As New SqlDataAdapter(cmd)
Dim da = New SqlDataAdapter(cmd)
da.Fill(ds)
'db.Fill(ds)
division.DataSource = ds.Tables(0)
division.DataTextField = "entityname"
division.DataValueField = "entitycode"
division.DataBind()
' If ds.Tables(0).Rows.Count > 1 Then
'divisions.Visible = False
' communities.DataSource = ds.Tables(1)
'communities.DataTextField = "Projectname"
' communities.DataValueField = "projID"
' communities.DataBind()
' Else
' divisions.Text = ds.Tables(0).Rows(0)("entityname").ToString
'division.Visible = False
' communities.DataSource = ds.Tables(1)
'communities.DataTextField = "Projectname"
'communities.DataValueField = "projID"
'communities.DataBind()
'End If
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
End Sub
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
' Dim communities As String = Server.UrlEncode(Request.Form("communities"))
' Response.Write(communities)
' Dim removedays As Integer = Request.Form("removedays")
'getEntity()
' MsgBox(sort.SelectedValue)
Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder = New SqlConnectionStringBuilder(Session("strconnection"))
Dim databasename As String = builder.InitialCatalog
Dim dataname As String
If databasename = "G3Live" Then
dataname = "2fLiveReports"
Else
dataname = "2fTestReports"
End If
Response.Redirect("http://g3reports.danryanbuilders.com/ReportServer/Pages/ReportViewer.aspx?%" + dataname + "%2fPurchasing%2flance_tutorial&rs:Format=Excel&rs%3aCommand=Render&entityid=" & division.SelectedValue & "&begindate=" + begindate.Text + "&enddate=" + enddate.Text + "&sort=" + DropdownList1.SelectedValue)
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim builder As New System.Data.SqlClient.SqlConnectionStringBuilder
builder = New SqlConnectionStringBuilder(Session("strconnection"))
Dim databasename As String = builder.InitialCatalog
Dim dataname As String
If databasename = "G3Live" Then
dataname = "2fLiveReports"
Else
dataname = "2fTestReports"
End If
Response.Redirect("http://g3reports.danryanbuilders.com/ReportServer/Pages/ReportViewer.aspx?%" + dataname + "%2fPurchasing%2flance_tutorial&rs:Format=PDF&rs%3aCommand=Render&entityid=" & division.SelectedValue & "&begindate=" + begindate.Text + "&enddate=" + enddate.Text + "&sort=" + DropdownList1.SelectedValue)
End Sub
End Class
Note: You are storing connection string in Session, it is not recommendable. You can do but it is better you should use web.config
file to store connection string.
You can be refer this: Avoid storing connection string in session for different sql schema
For Solution I recommended
You must check the session variable prior to getting the value for the connection string.
' Check if session is null
If Not (Session("strconnection ") Is Nothing) Then
{
//
}
When it is Null or Nothing or Empty, try to retrieve the connection string again.
You need to cast session variables into their correct types, before use like
Session("strconnection")
Replace it by
Session("strconnection").toString()
And
Cast Session("userid") and Request.QueryString("id") by the help of
Integer.Parse/ Integer.TryParse
you can read this for concept:
Return Value From Session

How do i get access to checkboxes dynamically generated in loop

I am new to asp.net and vb.net programming and i can't find a answer to my problem. I have dynamically generated checkboxes in a loop at runtime within a sub.
This is a grid scheduler program that displays selected day's and selected hours from a location which is selected from a different page. I want to acces the checkboxes by id but i cant get acces to them because the checkboxes are not declared at class level.
Can anyone help me please, i have searched all day long for a solution. I Prefer VB but C# is fine also.
Below is my codebehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindLocationDayTime()
End If
End Sub
Public Sub BindLocationDayTime()
Dim ID As Integer
Dim Name As String
Dim Day As Integer
Dim Time As Integer
Dim StartDate As DateTime
Dim EndDate As DateTime
Dim Locations As SqlDataReader = GetLocations()
For Each Item In Locations
Dim LRow As New TableRow()
Dim LCell As New TableCell()
LCell.Text = Locations.Item("Name")
LCell.Attributes.Add("class", "LocationHeader")
LCell.Attributes.Add("colspan", "5")
LRow.Cells.Add(LCell)
LocationData.Rows.Add(LRow)
Dim Location As SqlDataReader = GetLocation(Convert.ToInt32(Locations.Item("Id")))
While Location.Read()
Name = Location("Name").ToString()
StartDate = Location("StartDate")
EndDate = Location("EndDate")
End While
Dim dtfi As Globalization.DateTimeFormatInfo = Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat
Dim tRowCount As Integer = 0
Do While StartDate <= EndDate
Dim LocationDayTime As SqlDataReader = GetPlayDayTime(Convert.ToInt32(Locations.Item("Id")))
For Each row In LocationDayTime
Day = LocationDayTime.Item("DayID")
Time = LocationDayTime.Item("TimeID")
ID = Locations.Item("Id")
If Day = 1 Then
If StartDate.DayOfWeek = DayOfWeek.Monday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 2 Then
If StartDate.DayOfWeek = DayOfWeek.Tuesday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 3 Then
If StartDate.DayOfWeek = DayOfWeek.Wednesday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 4 Then
If StartDate.DayOfWeek = DayOfWeek.Thursday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
ElseIf Day = 5 Then
If StartDate.DayOfWeek = DayOfWeek.Friday Then
BindDays(StartDate, ID, tRowCount, Time)
tRowCount = tRowCount + 1
End If
End If
Next
StartDate = StartDate.AddDays(1)
Loop
Next
End Sub
Public Sub BindDays(ByVal StartDate As DateTime, ByVal ID As Integer, ByVal tRowCount As Integer, ByVal Time As Integer)
Dim dtfi As Globalization.DateTimeFormatInfo = Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat
Dim tRow As New TableRow()
Dim Cell1 As New TableCell()
Dim strDayOfWeek As String = dtfi.GetDayName(StartDate.DayOfWeek)
Cell1.Text = UppercaseFirstLetter(strDayOfWeek & " ") & (StartDate.Date.ToShortDateString & " om ") & (Time & "uur ")
Cell1.Attributes.Add("class", "MemberCell")
tRow.Cells.Add(Cell1)
Dim Cell2 As New TableCell()
Dim cbAvailible As New CheckBox()
cbAvailible.ID = (StartDate.Date) & "," & (Time)
cbAvailible.Checked = False
Cell2.Controls.Add(cbAvailible)
tRow.Cells.Add(Cell2)
Dim Cell3 As New TableCell()
Dim Label As New Label()
Label.Text = ("(Op deze datum ben ik verhinderd)")
Cell3.Controls.Add(Label)
tRow.Cells.Add(Cell3)
If tRowCount Mod 2 Then
tRow.Attributes.Add("class", "alternatingItemStyle")
Else
tRow.Attributes.Add("class", "itemStyle")
End If
LocationData.Rows.Add(tRow)
End Sub
#End Region
#Region " Events "
Private Sub Insert_Click(sender As Object, e As EventArgs) Handles Insert.Click
' I want to get here al the checkbox id and insert the values to a databse
End Sub
End Region
Solution 1 - Using recursive control search
I have done something similar with a dynamically generated form with a variable number of controls (textboxes, dropdowns, and checkboxes) and control state being data driven. I would not be looking to tie into the events of the generated controls (would require a jerky postback) but have a "Save" button and from that event do a recursive GetChildControls function that starts from the container holding your dynamic controls. Have a convention when assigning an id for each dynamic control so when you later loop back through them you can know which control is related to which record.
The recursive function:
Public Class ControlUtils
Shared Function GetChildControls(ByVal ctrl As Control, Optional ByVal ctrlType As Type = Nothing) As Control()
Dim controls As New ArrayList()
For Each c As Control In ctrl.Controls
' add this control and all its nested controls
If ctrlType Is Nothing OrElse ctrlType.IsAssignableFrom(c.GetType()) Then
controls.Add(c)
controls.AddRange(GetChildControls(c))
End If
Next
' return the result as an array of Controls
Return DirectCast(controls.ToArray(GetType(Control)), Control())
End Function
End Class
Basic idea with a contrived dynamic form...
A class to represent the database info:
Public Class Location
Public Property ID As Integer
Public Property Name As String
Public Property StartDate As Date
Public Property EndDate As Date
Shared Function GetSampleLocations() As List(Of Location)
Dim sample As New List(Of Location)
Dim loc As Location
For j = 1 To 5
loc = New Location
loc.ID = j
loc.Name = "Location " & j
loc.StartDate = Date.Today
loc.EndDate = Date.Today.AddDays(6 - j)
sample.Add(loc)
Next
Return sample
End Function
End Class
The class that has the methods to build the "form" and save its data:
Public Class LocationsDynamicForm
Dim _Locations As IEnumerable(Of Location)
Sub New(locations As IEnumerable(Of Location))
_Locations = locations
End Sub
Sub InsertEditForm(plc As PlaceHolder, setUserInput As Boolean)
'build and add controls to placeholder
Dim tbl As New Table
Dim r As TableRow
Dim c As TableCell
For Each loc As Location In _Locations
r = New TableRow
'add cell for location name
c = New TableCell
c.Controls.Add(New LiteralControl(loc.Name)) 'add plain text through literal control
r.Cells.Add(c)
'add cell for each day in the date range for current location
Dim currentDate As Date = loc.StartDate
Do Until currentDate > loc.EndDate
c = New TableCell
Dim chk As New CheckBox
chk.ID = "chkLocationDate_" & loc.ID & "_" & currentDate.Ticks
chk.Text = currentDate.ToShortDateString
If setUserInput Then
'set the check state based on current database value
Dim pretendValueCameFromDB As Boolean = True
chk.Checked = pretendValueCameFromDB
End If
c.Controls.Add(chk)
r.Cells.Add(c)
currentDate = currentDate.AddDays(1)
Loop
tbl.Rows.Add(r)
Next
plc.Controls.Add(tbl)
End Sub
Sub SaveForm(ByVal plc As PlaceHolder)
Dim ctl As Control
Dim controlIDParts() As String
Dim drp As DropDownList
Dim txt As TextBox
Dim chk As CheckBox
For Each ctl In ControlUtils.GetChildControls(plc, GetType(Control))
If ctl.GetType Is GetType(DropDownList) Then
drp = CType(ctl, DropDownList)
If drp.ID Like "drpIT_*" Then
controlIDParts = drp.ID.Split("_")
'update record...
End If
ElseIf ctl.GetType Is GetType(TextBox) Then
txt = CType(ctl, TextBox)
If txt.ID Like "txtIT_*" Then
controlIDParts = txt.ID.Split("_")
'update record...
End If
ElseIf ctl.GetType Is GetType(CheckBox) Then
chk = CType(ctl, CheckBox)
If chk.ID Like "chkLocationDate_*" Then
controlIDParts = chk.ID.Split("_")
Dim locationID = controlIDParts(1)
Dim ticks As Long = Val(controlIDParts(2))
Dim d As New Date(ticks)
'update record...
End If
End If
Next
'commit record changes...
End Sub
End Class
And its use inside the webform (assuming you have a save button and placeholder control):
Dim _Locations As List(Of Location)
Dim _LocationsForm As LocationsDynamicForm
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
_Locations = Location.GetSampleLocations()
_LocationsForm = New LocationsDynamicForm(_Locations)
_LocationsForm.InsertEditForm(plcLocations, Not Me.IsPostBack)
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
_LocationsForm.SaveForm(plcLocations)
End Sub
Solution 2 - Use AddHandler with Dynamically added controls
This is closer to what you want, but requires a postback on each checkbox change. In your BindDays routine add these lines when you are adding the checkbox.
cbAvailible.AutoPostBack = True
AddHandler cbAvailible.CheckedChanged, AddressOf Insert_Click
You should trim the Handles keyword at the end of your sub Insert_Click signature. The Handles is nice when you have foreknowledge of the control(s) you will be handling but the controls don't exist at design time.
Private Sub Insert_Click(sender As Object, e As EventArgs)
' I want to get here al the checkbox id and insert the values to a databse
Dim chk As CheckBox = CType(sender, CheckBox)
Label1.Text = "ID = " & chk.ID & ", Checked = " & chk.Checked
End Sub
I'm not sure how you are persisting your 'LocationData' across postbacks or adding it to the web page but I was able to get a modified version of your code working.
' Global declaration inside the "Form" class.
Public Checkboxes as New List(of Checkbox)
Each time you create a "new checkbox" add it to the collection.
...
Dim cbAvailible As New CheckBox()
Checkboxes.Add(cbAvailable)
...
Later you can simply refer to the checkbox by Index.
Dim chk as boolean = Checkboxes(2).checked ' example
The other Alternative is to use a Generic.Dictionary to store the checkboxes, in that case each box can have a "Key" like a string that relates to the row or something specific.
Looping through Checkboxes.
For iQ AS integer = 0 to Checkboxes.Count -1
Dim cb as checkbox = Checkboxes(iq) ' just a way to not use long name during operations.
Dim checked as boolean = cb.checked ' ... ' do your work here
' ...
Next iQ
Odds are you will need to do the same with all your objects (per row).
The Last Index should be the same for all of them. Which should be the same as the number of rows in your table object as well.

Persisting datatables in viewstate and databinding

I am passing in a start date, an end date, a SQL stored procedure, and a identifying area code into a shared function to populate five declared datatables.
Public Shared Function getNBOCAPData(ByVal startDate As DateTime, ByVal endDate As DateTime, ByVal sp As String, ByVal orgCode As String) As DataTable
Dim SqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("CancerRegisterConnectionString").ConnectionString.ToString)
Dim sqlCmd As New SqlCommand
getNBOCAPData = New DataTable
Try
SqlConn.Open()
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Connection = SqlConn
sqlCmd.CommandTimeout = 300
sqlCmd.CommandText = sp
sqlCmd.Parameters.AddWithValue("#StartDate", startDate)
sqlCmd.Parameters.AddWithValue("#EndDate", endDate)
sqlCmd.Parameters.AddWithValue("#UserOrgCode", orgCode)
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
getNBOCAPData.Load(reader)
Catch ex As Exception
Common.LogError(ex, True)
Finally
SqlConn.Close()
SqlConn.Dispose()
End Try
End Function
The results of this function are then passed into the datatables like this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim patiDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATI", Request.QueryString("orgCode"))
Dim tumDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_TUM", Request.QueryString("orgCode"))
Dim surDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_SUR", Request.QueryString("orgCode"))
Dim cheDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_CHE", Request.QueryString("orgCode"))
Dim patDataTable As DataTable = getNBOCAPData(Request.QueryString("startDate"), Request.QueryString("endDate"), "NBOCAP_DOWNLOAD_PATH", Request.QueryString("orgCode"))
Dim hidCount As Integer = 0
If patiDataTable.Rows.Count = 0 Then
divPati.Visible = False
hidCount += 1
End If
If tumDataTable.Rows.Count = 0 Then
divTum.Visible = False
hidCount += 1
End If
If surDataTable.Rows.Count = 0 Then
divSur.Visible = False
hidCount += 1
End If
If cheDataTable.Rows.Count = 0 Then
divChe.Visible = False
hidCount += 1
End If
If pathDataTable.Rows.Count = 0 Then
divPath.Visible = False
hidCount += 1
End If
If hidCount = 5 Then
divNoResults.Visible = True
divInstructions.Visible = False
Else
ViewState("patiDataTable") = patiDataTable
ViewState("tumDataTable") = tumDataTable
ViewState("surDataTable") = surDataTable
ViewState("cheDataTable") = cheDataTable
ViewState("pathDataTable") = pathDataTable
End If
End Sub
The databinding is done like this
Public Shared Sub RetRptBySPNBOCAP(ByRef dg As GridView, ByVal dataTable As DataTable)
dg.DataSource = dataTable
dg.DataBind()
End Sub
Then in preparation for the datatables to be sent to an Excel file the data in ViewState is set to a DataTable like this, but the dataTable.Rows.Count() is throwing a NullReferenceException error as though the databind isn't taking place?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cellDate As DateTime = DateTime.MinValue
Dim dataTable As DataTable = Nothing
Dim prefix As String = "Pati_NBOCAP"
Select Case (Request.QueryString("type").ToString)
Case "Pati"
dataTable = ViewState("patiDataTable")
Case "Tum"
dataTable = ViewState("tumDataTable")
prefix = "Tum_NBOCAP"
Case "Che"
dataTable = ViewState("cheDataTable")
prefix = "Che_NBOCAP"
Case "Path"
dataTable = ViewState("pathDataTable")
prefix = "Path_NBOCAP"
Case "Sur"
dataTable = ViewState("surDataTable")
prefix = "Sur_NBOCAP"
End Select
RetRptBySPNBOCAP(Results, dataTable)
Dim rCount As Integer
If dataTable.Rows.Count() > 0 Then
rCount = dataTable.Rows.Count()
End If
End Sub
You must know that viewstate is a per page concept. So if you put data in the viewstate of a particular page you can't retrieve them from another page. Instead of viewstate you can use Session which is the same for all the pages executed within a user session.
Session("patiDataTable") = patiDataTable
Also, viewstate is by default stored client side ans thus is not suitable for large data objects such as datatables.

Time value out of datetime column gets converted to 12 hour format after DataReader.Read

My app allows users to make meeting appointments. Before the appointment is saved to the database, the user selects a date from a Calendar control. Once a date is selected, the page should get a list of appointments for that day out of the database, and examine the time of day for each recorded appointment. Any timeslots that have already been booked are to be removed from a DropDownList that the user will select a convenient time from.
The problem comes in with my time comparisons. Most of the code below is meant to strip the apart the date/time values to get something I can compare with.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
PopulateTime()
End If
End Sub
Protected Sub PopulateTime()
Dim db As New Database
Dim sql As String = "select apptinterval from centres where centreid = #id"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#id", Session("CentreID")))
Dim dr As SqlDataReader = db.GetReader(sql, args.ToArray)
Dim interval As Integer = 0
If dr.Read Then
interval = dr("apptinterval")
End If
Dim time = TimeSpan.FromHours(8)
While time < TimeSpan.FromHours(17)
time += TimeSpan.FromMinutes(interval)
ddlAppointmentTime.Items.Add(New ListItem(time.ToString, time.ToString))
End While
End Sub
Protected Sub calAppointmentDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calAppointmentDate.SelectionChanged
Dim seldate As String = Left(calAppointmentDate.SelectedDate, 10)
Dim dateargs() As String = seldate.ToString.Split("/")
Dim newdate As String = dateargs(0) & "-" & dateargs(1) & "-" & dateargs(2)
GetTimes(newdate)
End Sub
Protected Sub GetTimes(ByVal TargetDate As String)
Dim db As New Database
Dim args As New List(Of SqlParameter)
Dim sql As String = "select apptdate from appointments where apptdate between #date1 and #date2 order by apptdate"
args.Add(New SqlParameter("#date1", TargetDate & " 12:00:00"))
args.Add(New SqlParameter("#date2", TargetDate & " 23:59:59"))
Dim dr As SqlDataReader = db.GetReader(sql, args.ToArray)
If dr.HasRows Then
dr.Read()
For i As Integer = 0 To ddlAppointmentTime.Items.Count - 1
If Left(ddlAppointmentTime.Items(i).Value, 5) = Mid(dr("apptdate"), 12, 5) Then
ddlAppointmentTime.Items.RemoveAt(i)
End If
Next
End If
dr.Close()
End Sub
If the loop here, the value for Mid(dr("apptdate"), 12, 5) is being returned as 01:00. The actual value in the database says 13:00.
Can anyone suggest why this conversion is happening? It's causing the comparison to fail, and so, that timeslot is not being removed from the DropDownList.
Thanks in advance!
It seems it was the Mid that did it. The conversion to string involved here changed the value.
I worked around this by removing the Mid and changing the sql statement as follows:
Dim sql As String = "select left(CONVERT(time, apptdate, 14), 5) as apptdate from appointments"
Dim dr As SqlDataReader = db.GetReader(sql, args.ToArray)
If dr.HasRows Then
While dr.Read
For i As Integer = 0 To ddlAppointmentTime.Items.Count - 1
If Left(ddlAppointmentTime.Items(i).Value, 5) = dr("apptdate") Then
ddlAppointmentTime.Items.RemoveAt(i)
End If
Next
End While
End If
dr.Close()

compare the content of 2 gridviews in one aspx page

we need to compare the content of 2 identical gridviews and extract rows that differ in a third gridview, is this doable?
i tried a lot but faced no luck, please help me.
at our office we take daily backup of ASP.net application ms access backend
for the next few days we need to evaluate the changes made to records in the database tables
at the end of each day i want to compare 2 access databases first database is the backup of yesterday and second database is the backup of today
i thought of the following algorithm, please read carefully and tell me how to proceed to compare the datatables / gridviews
i need to display th rows / cells containing the differences / updates / deleted data
comparing two ms access backend databases of an asp.net web application
my team and myseld figured it out
Imports System.Data
Imports System.Data.OleDb
Partial Class MoKoTrack
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myDB = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|databaseName.mdb;Persist Security Info=True")
Session("CurrentDB") = myDB
myDB.open()
Dim mytables = myDB.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, New Object() {})
Dim CurrentTable As String
For i = 1 To mytables.Rows.Count
CurrentTable = mytables.Rows(i - 1).Item(2).ToString
If CurrentTable.Contains("Backup") Then CompareTable(CurrentTable, mytables.Rows(i - 1).Item(3).ToString)
Next i
' Dim myGrid As New GridView
'myGrid.DataSource = mytables
'myGrid.DataBind()
'Me.Form.Controls.Add(myGrid)
'myDB.Close()
End Sub
Sub CompareTable(ByVal BackupTableName As String, ByVal myPrimKey As String)
Dim OriginalTable As New DataTable
Dim BackupTable As New DataTable
Dim ModificationsTable As New DataTable
Dim AddedTable As New DataTable
Dim DeletedTable As New DataTable
Dim myDB = Session("CurrentDB")
Dim FinalSQLString = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand = New OleDbCommand(FinalSQLString, myDB)
Dim myReader As IDataReader = myDBCommand.ExecuteReader()
BackupTable.Load(myReader)
Dim OriginalTableName = Left(BackupTableName, Len(BackupTableName) - 6)
Dim FinalSQLString2 = "SELECT * FROM [" + OriginalTableName + "]"
Dim myDBCommand2 = New OleDbCommand(FinalSQLString2, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader2 As IDataReader = myDBCommand2.ExecuteReader()
OriginalTable.Load(myReader2)
Dim myPrimColumn(0) As DataColumn
myPrimColumn(0) = OriginalTable.Columns(myPrimKey)
OriginalTable.PrimaryKey = myPrimColumn
Dim myPrimColumn2(0) As DataColumn
myPrimColumn2(0) = BackupTable.Columns(myPrimKey)
BackupTable.PrimaryKey = myPrimColumn2
AddedTable = OriginalTable.Clone
DeletedTable = OriginalTable.Clone
ModificationsTable = OriginalTable.Clone
ModificationsTable.PrimaryKey = Nothing
Dim CurrentVal As String
For i = 0 To OriginalTable.Rows.Count - 1
CurrentVal = OriginalTable.Rows(i).Item(myPrimKey).ToString
Dim foundRow As DataRow = BackupTable.Rows.Find(CurrentVal)
If foundRow IsNot Nothing Then
For t = 0 To OriginalTable.Columns.Count - 1
If Not foundRow.Item(t).ToString = OriginalTable.Rows(i).Item(t).ToString Then
ModificationsTable.ImportRow(OriginalTable.Rows(i))
'ModificationsTable.Rows(ModificationsTable.Rows.Count - 1).Item(t) = ModificationsTable.Rows(ModificationsTable.Rows.Count - 1).Item(t) & "Modified"
ModificationsTable.ImportRow(foundRow)
End If
Next
Else
AddedTable.ImportRow(OriginalTable.Rows(i))
End If
Next
For i = 0 To BackupTable.Rows.Count - 1
CurrentVal = BackupTable.Rows(i).Item(myPrimKey).ToString
Dim foundRow As DataRow = OriginalTable.Rows.Find(CurrentVal)
If foundRow Is Nothing Then
DeletedTable.ImportRow(OriginalTable.Rows(i))
End If
Next
If AddedTable.Rows.Count > 0 Then
Dim myLabel As New Label
myLabel.Text = "<br/> The following records were added to table " & OriginalTableName & "<br/> <br/>"
Me.form1.Controls.Add(myLabel)
Dim myGrid As New GridView
myGrid.DataSource = AddedTable
myGrid.DataBind()
Me.form1.Controls.Add(myGrid)
End If
If ModificationsTable.Rows.Count > 0 Then
Dim myLabel As New Label
myLabel.Text = "<br/> The following records were modified in table " & OriginalTableName & "<br/> <br/>"
Me.form1.Controls.Add(myLabel)
Dim myGrid As New GridView
myGrid.DataSource = ModificationsTable
myGrid.DataBind()
Me.form1.Controls.Add(myGrid)
End If
If DeletedTable.Rows.Count > 0 Then
Dim myLabel As New Label
myLabel.Text = "<br/> The following records were deleted from table " & OriginalTableName & "<br/> <br/>"
Me.form1.Controls.Add(myLabel)
Dim myGrid As New GridView
myGrid.DataSource = DeletedTable
myGrid.DataBind()
Me.form1.Controls.Add(myGrid)
End If
End Sub
End Class
I usually compare it using LINQ
This will give you a head start
var SearchResults1 = from u in YourDB.YourUserTable1
orderby u.YourColumn
select u;
GridView1.DataSource = SearchResults1;
GridView1.DataBind();
var SearchResults2 = from u in YourDB.YourUserTable2
orderby u.YourColumn
select u;
GridView2.DataSource = SearchResults2;
GridView2.DataBind();
var SearchResults3 = from u1 in SearchResults2
where !(from u2 in SearchResults1
select u2.YourTablePrimaryKey).Contains(u1.YourTablePrimaryKey)
orderby u1.YourColumn
select u1;
GridView3.DataSource = SearchResults3;
GridView3.DataBind();
You can further elaborate SearchResults 3 if you want like comparing whats in SearchResults1 but not in SearchResults2 and vice versa

Resources