Weird strange things happening in repository record! - vb.net

SubSonic 2.2. I use the repository record pattern, with a table "appointment" with an appointmentId as auto-incrementing int.
I am trying to update it, but when I do update the fields with something totally different, dirty columns are always zero, and I get an exception.
System.NullReferenceException: Object reference not set to an instance of an object. at SubSonic.DataService.ExecuteQuery(QueryCommand cmd) at SubSonic.SubSonicRepository.Update[T](RepositoryRecord1 item, String userName) at janji.Janji.Data.DB.Update[T](RepositoryRecord1 item) in A:\Source\VS2008\Web\Apps\janji\janji\Classes\DAL\AllStructs.vb:line 197 at janji.WebForm4.SaveData() in A:\Source\VS2008\Web\Apps\janji\janji\UI\Appt.aspx.vb:line 343
Here's my code:
Try
If Appointment.AppointmentId > 0 Then
Appointment.AddressName = uxHotel.Text
Appointment.Address = uxAddress.Text
Appointment.AppStartTime = Date.Parse(uxApptDate.SelectedDate.Value.ToShortDateString + " " + uxApptStartTime.SelectedDate.Value.ToShortTimeString)
Appointment.ApptEndTime = Date.Parse(uxApptDate.SelectedDate.Value.ToShortDateString + " " + uxApptEndTime.SelectedDate.Value.ToShortTimeString)
Appointment.Completed = uxCOmpleted.Checked
Appointment.DropNumber = uxDropNum.Text
Appointment.Total = 0
Appointment.EmployeeId = 0
Appointment.Model = uxModel.Text
Appointment.DropAmount = Decimal.Parse(uxDropAmount.SelectedValue)
Appointment.RoomNumber = uxRoom.Text
'If Appointment.DirtyColumns.Count > 0 Then
Janji.Data.DB.Update(Of Janji.Data.Appointment)(Appointment)
'End If
End If
Catch ex As Exception
_ErrorMessage = ex.ToString
RetVal = False
lErrors.Text = _ErrorMessage
lErrors.Visible = True
End Try

You're using the Structs we provide instead of instantiating an Appointment object. Do everything you're doing here, but create an Appointment instance and assign it the values. Then pass that instance to the repo.

Related

No matching records found (ODBC -2028) in SAP DI Service Call

When I try to make a new service call I get a No matching records found (ODBC -2028) here is my code:
Dim sC = company.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oServiceCalls)
sC.CustomerCode = recordSet.Fields.Item(2).Value Logging(sC.CustomerCode)
sC.Subject = recordSet.Fields.Item(3).Value
sC.Description = recordSet.Fields.Item(5).Value
sC.InternalSerialNum = recordSet.Fields.Item(11).Value
sC.ItemCode = recordSet.Fields.Item(11).Value
Dim ret = sC.Add()
If ret <> 0 Then company.GetLastError(ErrCode, ErrMsg)
Logging("Error in service call: " + ErrCode.ToString() + " : " + ErrMsg)
End If
Every value is valid. When I remove the InternalSerialNum line. it is working. The InetrnalSerialNum is valid too. And on the other machine, this code is working.
How can I solve that problem?

Remove Duplicate Objects from list in VB.Net

I am trying to remove duplicate object from a list based on the companyID.
How do I integrate through a list and remove the object based on a companyID.
While reader.Read()
companys.Add(New CompanySearch)
companys(companys.Count - 1).StartDate = reader("StartDate").ToString & " (" & count & ")"
companys(companys.Count - 1).CompanyID = reader("company").ToString
companys(companys.Count - 1).Origin = reader("Origin").ToString
companys(companys.Count - 1).OriginName = reader("OriginName").ToString
companys(companys.Count - 1).Status = reader("status").ToString
companys(companys.Count - 1).StatusName = reader("statusname").ToString
companys(companys.Count - 1).Status = reader("status").ToString
companys(companys.Count - 1).FullLegalBusinessName = reader("fullLegalBusinessName")
companys(companys.Count - 1).AmountRequestedText = reader("amountRequestedText")
companys(companys.Count - 1).HowSoonNeededText = reader("howSoonNeededText")
companys(companys.Count - 1).QueueID = reader("QueueID")
companys(companys.Count - 1).Company = reader("Company")
End While
For counter As Integer = 0 To companys.Count
counter += 1
If i <> CInt(companys(companys.Count - 1).CompanyID) Then
i = CInt(companys(companys.Count - 1).CompanyID)
Else
companys.Remove()
End If
Next
Don't add them in the first place. Use either aDictionary (if you will look them up by ID later) or a HashSet (if you won't) to check before adding to the results. Here's the HashSet example:
Dim companyIDs As New HashSet(Of String)()
While reader.Read()
If Not companyIDs.Contains(reader("company").ToString()) Then
companys.Add(New CompanySearch() With {
.StartDate = reader("StartDate").ToString() & " (" & count & ")",
.CompanyID = reader("company").ToString(),
.Origin = reader("Origin").ToString(),
.OriginName = reader("OriginName").ToString(),
.Status = reader("status").ToString(),
.StatusName = reader("statusname").ToString(),
.Status = reader("status").ToString(),
.FullLegalBusinessName = reader("fullLegalBusinessName"),
.AmountRequestedText = reader("amountRequestedText"),
.HowSoonNeededText = reader("howSoonNeededText"),
.QueueID = reader("QueueID"),
.Company = reader("Company"),
})
End If
companyIDs.Add(reader("company").ToString())
End While
I also noticed that both the .Company and .CompanyID properties in this object are populated from the company column in the reader. Is this intentional, or do you mean to look at a different column for .CompanyID?
Additionally, while I understand your existing search SQL already considers these company rows as distinct, you should probably go back to the drawing board there and rethink the SQL, so that you truly do get distinct records. Perhaps use a nested query or CTE to first find a projection of CompanyID values that match your query, and then join back to your company table to get the details for each company with an ID included in those initial results. If that's not possible, you should consider what it is that makes the rows different, because I promise you that some column IS different, and if you just cull one record or the other you're potentially showing the user bad data from the wrong row.
Use this :
Dim distinctCompanys = companys.GroupBy(Function(x) x.CompanyID).Select(Function(y) y.First())
You can easily filter the collection with LINQ:
Dim companies = companys.Distinct(Function(c) c.CompanyID).ToList
Or use Dictionary(Of String, CompanySearch) instead, for Example:
Dim companies As Dictionary(Of String, CompanySearch)
While reader.Read()
Dim companyID = reader("company").ToString
companies(companyID) = New CompanySearch() With {
.StartDate = reader("StartDate").ToString & " (" & count & ")",
.CompanyID = companyID,
.Origin = reader("Origin").ToString,
.OriginName = reader("OriginName").ToString,
.Status = reader("status").ToString,
.StatusName = reader("statusname").ToString,
.Status = reader("status").ToString,
.FullLegalBusinessName = reader("fullLegalBusinessName"),
.AmountRequestedText = reader("amountRequestedText"),
.HowSoonNeededText = reader("howSoonNeededText"),
.QueueID = reader("QueueID"),
.Company = reader("Company")
}
End While
But I recommend grouping instead, so that you can check for duplicates after:
Dim companiesLookup = companys.ToLookup(Function(c) c.CompanyID)
Dim duplicates = companiesLookup.Where(Function(c) c.Count > 1).ToList

Error: Conversion from type 'DBNull' to type 'String' is not valid

I'm working on a project where I get data from a database.
Now I get this error message:
Conversion from type 'DBNull' to type 'String' is not valid
I know what the error means, I just need a way to fix it.
I have the following code:
Private Function ParseSeamansNames(ByVal seaman As ItemsDataSet.SeamenRow) As String
If (seaman Is Nothing) Then Return String.Empty
Dim name As String
Dim firstNames() As String = Split(seaman.FirstName.Replace("-", " "))
Dim index1 As Integer = CInt(seaman.GivenNameNumber.Substring(0, 1))
Dim index2 As Integer = CInt(seaman.GivenNameNumber.Substring(1, 1))
If (index1 > firstNames.Length - 1) Then
index1 = 0
End If
If (index2 > firstNames.Length - 1) Then
index2 = 0
End If
If (index1 = 0 And index2 = 0) Then
name = seaman.FirstName
ElseIf (index1 > 0 And index2 = 0) Then
name = firstNames(index1 - 1)
ElseIf (index1 = 0 And index2 > 0) Then
name = firstNames(index2 - 1)
Else
name = firstNames(index1 - 1) & "-" & firstNames(index2 - 1)
End If
name = name & " " & seaman.LastName
Return name
End Function
I tried to change it to If (seaman Is Nothing) Then Return DBNull but I get error:
dbnull is a type and cannot be used as an expression
I don't really know how to fix it. Can anyone help me?
UPDATE:
I get this error:
[InvalidCastException: Conversion from type 'DBNull' to type 'String'
is not valid.]
Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object
Value) +715847
BUMSSeamenWebb.ItemsService.SeamenRow.get_FirstName() in C:\BUMS
LOKAL\Dev\Projects\BUMSSeamenWebb\Web
References\ItemsService\Reference.vb:51036
That line is this code:
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property FirstName() As String
Get
Try
Return CType(Me(Me.tableSeamen.FirstNameColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'FirstName' in table 'Seamen' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSeamen.FirstNameColumn) = value
End Set
End Property
In particular:
Return CType(Me(Me.tableSeamen.FirstNameColumn),String)
I can't see the problem here
UPDATE 2:
This is another function that checks other columns
Private Sub SetSeamanData(ByRef itemRow As ItemsDataSet.ItemsRow, ByVal seaman As ItemsDataSet.SeamenRow)
itemRow.PersonalIdentityNumber = seaman.PersonalIdentityNumber
itemRow.Name = ParseSeamansNames(seaman)
itemRow.CitizenShipCode = seaman.CitizenshipCode
If Not seaman.IsEmailNull() Then
itemRow.EmailAddress = seaman.Email
Else
itemRow.EmailAddress = Nothing
End If
If Not seaman.IsTelephoneNull() Then
itemRow.TelephoneNumber = seaman.Telephone
Else
itemRow.TelephoneNumber = Nothing
End If
If Not seaman.IsMobiletelephoneNull() Then
itemRow.MobilephoneNumber = seaman.Mobiletelephone
Else
itemRow.MobilephoneNumber = Nothing
End If
End Sub
These generated DataRow classes are coded in such a way that if you try to read a property (column value) that has a database null value, it will throw an exception.
You are expected to check for null before attempting to read from it.
As you can tell from the message, in this case it's complaining that you are trying to read the value of FirstName, but it's null (DbNull).
Usually, when a column can be null, these DataRow classes also include a convenience function to check for null on that specific column. So in this case, ItemsDataSet.SeamenRow should also have a IsFirstNameNull function. If so, call that first, and handle that specific case. If IsFirstNameNull returns false, then you can safely read from the FirstName property.
If you have other columns that can be null in your database, you will need to follow a similar pattern.

VB.NET not deleting records from SQL DB

I'm having some rather annoying issues with an app I'm trying to write.
I have a DB with a small table ("main") that i entered data into manually when i created the table. I can delete one of the 3 rows that I manually inputted, no problem, but if I add a row from the app it doesn't save to the database and I can't delete it.
Additionally, none of the values that I've edited save to the DB. I suspect that these two issues are related and was hoping you could help me figure out what's wrong.
here's the code for the "delete" button:
Private Sub btnSearchDelete_Click(sender As Object, e As EventArgs) Handles btnSearchDelete.Click
Try
Me.MainTableAdapter.Delete(searchIP.Text, searchSubnet.Text, searchVLAN.Text, searchAlive.Checked, searchReserved.Checked, searchUser.Text, searchDate.Text, searchFail.Text)
' updates system message bar for 1 second
Dim tmCurTime As DateTime = Date.Now
Dim wait As Int16 = 1 ' Time in seconds
Do
sysmsg.Text = "Deleted record."
sysmsg.ForeColor = Color.Red
Application.DoEvents()
Loop Until DateDiff(DateInterval.Second, tmCurTime, Date.Now) = wait
sysmsg.Text = ""
Catch ex As Exception
MsgBox("Delete failed!" - ex.Message)
End Try
Ds.AcceptChanges()
Me.MainTableAdapter.Update(Me.Ds.main)
'clears search filter
Me.MainBindingSource.Filter = Nothing
Me.MainTableAdapter.Fill(Me.Ds.main)
grid.Refresh()
End Sub
(grid is referring to the datagridview on the main app page)
i realize my code is probably, um, extremely messy -- I'm super new the development side of things and this is only the 3rd app I've worked on so far.
Any help you could give would be appreciated.
::EDIT::
ok, so this is what MainTableAdapter.Delete() is calling in SQL-speak:
DELETE FROM [dbo].[main] WHERE (([IP] = #Original_IP) AND ((#IsNull_SUBNET = 1 AND [SUBNET] IS NULL) OR ([SUBNET] = #Original_SUBNET)) AND ((#IsNull_VLAN = 1 AND [VLAN] IS NULL) OR ([VLAN] = #Original_VLAN)) AND ((#IsNull_ALIVE = 1 AND [ALIVE] IS NULL) OR ([ALIVE] = #Original_ALIVE)) AND ((#IsNull_RESERVED = 1 AND [RESERVED] IS NULL) OR ([RESERVED] = #Original_RESERVED)) AND ((#IsNull_USR = 1 AND [USR] IS NULL) OR ([USR] = #Original_USR)) AND ((#IsNull_DATE = 1 AND [DATE] IS NULL) OR ([DATE] = #Original_DATE)) AND ((#IsNull_FAIL = 1 AND [FAIL] IS NULL) OR ([FAIL] = #Original_FAIL)))

Enable / disable menu items using session in vb.net

If Session IsNot Nothing And Session("Admin") = "ftghgy" Then
Dim rptMenuItem As MenuItem = Menu1.FindItem("Home")
rptMenuItem.Selectable = True
Label9.Text = ("Welcome")
Else
Label9.Text = ("Welcome " + "" + Session("UserName").ToString)
endif
I am getting this error...
"Object reference not set to an instance of an object" on this line "rptMenuItem.Selectable = True"
I and am not using a master page.
Well, then probably this line is returning null value :
Menu1.FindItem("Home")
Meaning that an item with id "Home" couldn't be found in your Menu1.
I think it must be integer Menu1.FindItem(Type)