How to return from ienumerable function in vb.net - vb.net

Public Shared Function GetDataSet() As IEnumerable(Of SerialData)
Dim sCon As New SQLConnect
Dim strsql As String
Dim p As New Control
sCon.sqlAdp = New SqlDataAdapter
strsql = "select serialid," & _
" serialno," & _
" serialdesc," & _
" b.materialname," & _
" b.drawing," & _
" a.workorder," & _
" isnull((select top 1 patno from patternmaster where patid = a.patid),'Not Defined') as patno," & _
" case when a.activeflag = 1 then 'True' else 'False' end as activeflag" & _
" from serialmaster a," & _
" materialmaster b" & _
" where 1 = 1" & _
" and a.materialid = b.materialid" & _
" and b.activeflag = 1"
sCon.sqlCmd.CommandText = strsql
sCon.sqlAdp.SelectCommand = sCon.sqlCmd
sCon.sqlAdp.Fill(sCon.DS, "Listing")
Dim dtTable As DataTable
dtTable = sCon.DS.Tables("Listing")
' For Each row As DataRow In dtTable.Rows
' Return dtTable.AsEnumerable().[Select](Function(row) New With { _
' Key .serialid = row("serialid"), _
' Key .serialno = row("serialno"), _
' Key .serialdesc = row("serialdesc"), _
' Key .materialname = row("materialname"), _
' Key .drawing = row("drawing"), _
' Key .workorder = row("workorder"), _
' Key .patno = row("patno") _
'})
' Next
For Each row As DataRow In dtTable.Rows
p.serialid.Add(row("serialid"))
p.serialno.Add(row("serialno"))
p.serialdesc.Add(row("serialdesc"))
p.materialname.Add(row("materialname"))
p.drawing.Add(row("drawing"))
p.workorder.Add(row("workorder"))
p.patno.Add(row("patno"))
Next
Return p
End Function
Control class:
Public Class Control
Public serialid As New Generic.List(Of String)
Public serialno As New Generic.List(Of String)
Public serialdesc As New Generic.List(Of String)
Public materialname As New Generic.List(Of String)
Public drawing As New Generic.List(Of String)
Public workorder As New Generic.List(Of String)
Public patno As New Generic.List(Of String)
Public result As New Generic.List(Of String)
End Class
ServerSidePro class:
Public Class ServerSidePro
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim d As New Control
' Those parameters are sent by the plugin
Dim iDisplayLength = Integer.Parse(context.Request("iDisplayLength"))
Dim iDisplayStart = Integer.Parse(context.Request("iDisplayStart"))
Dim iSortCol = Integer.Parse(context.Request("iSortCol_0"))
Dim iSortDir = context.Request("sSortDir_0")
'Fetch the data from a repository (in my case in-memory)
'Dim p = SerialData.GetDataSet()
Dim p = DirectCast(SerialData.GetDataSet(), IEnumerable(Of SerialData))
' prepare an anonymous object for JSON serialization
Dim aaData2 = p.select(Function(h) New With {h.serialid, h.serialno, h.serialdesc, _
h.materialname, h.drawing, h.workorder, h.patno}).Skip(iDisplayStart).Take(iDisplayLength)
Dim str As New List(Of String())
For Each item In aaData2
Dim arr As String() = New String(6) {item.serialid, item.serialno, item.serialdesc, _
item.materialname, item.drawing, item.workorder, item.patno}
str.Add(arr)
Next
Dim result = New With { _
Key .iTotalRecords = p.Count(), _
Key .iTotalDisplayRecords = p.Count(), _
Key .aaData = str
}
Dim serializer As New JavaScriptSerializer()
Dim json = serializer.Serialize(result)
context.Response.ContentType = "application/json"
context.Response.ClearHeaders()
context.Response.Write(json)
context.Response.End()
'Return d
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
How to return dataset from this function it is giving error Unable to cast object of type 'Control' to type 'System.Collections.Generic.IEnumerable'.

Easiest way is to use a List() object. I would restructure your class
Public Class Control
Public LControl As New List(Of Control)
Public serialid As String
Public serialno As String
Public serialdesc As String
Public materialname As String
Public drawing As String
Public workorder As String
Public patno As String
Public result As String
End Class
​

Related

I now am getting this error "The type initializer for 'iTrac.SalesOrder' threw an exception."

I have a function that works fine iTrac.SalesOrder.SalesOrdersByBody_JB, when I try to call it from the web service, it fails and throws the exception
"The type initializer for 'iTrac.SalesOrder' threw an exception."
I see this is a fairly common situation and I did go through ALL of the similar questions but I did not see any answer to my problem, or maybe I am too much of a newbie to recognize the answer...?
went through all the similar questions.
Private Sub BrowserMailSender(obj As Object, e As EventArgs)
Dim x As New List(Of iTrac.JBSODetail)
Try
FileIO.WriteToFile("service is started:" + Now + vbNewLine)
x = iTrac.SalesOrder.SalesOrdersByBody_JB(241)
FileIO.WriteToFile(x.ToString)
Catch ex As Exception
FileIO.WriteToFile(ex.Message + vbNewLine)
End Try
End Sub
function that throws the exception
Public Shared Function SalesOrdersByBody_JB(ByVal BodyID As String) As List(Of JBSODetail)
Dim SalesOrderList As New List(Of JBSODetail)
Using context = New iTracContext
Dim BOMList = New List(Of Integer)
Dim StatusList As New List(Of String)
BOMList = context.BillOfMaterials.Where(Function(b) b.Child =
BodyID And b.ParentClass = "RTS").Select(Function(b)
b.Parent).ToList
If BOMList Is Nothing Then
Return Nothing
Else
StatusList.Add("OPEN")
StatusList.Add("HOLD")
StatusList.Add("BACKORDER")
End If
Dim query =context.JBSODetails.Include
("Part").Include("SOHeader").AsQueryable
If Not String.IsNullOrEmpty(BodyID) Then
query = query.Where(Function(s)
BOMList.Contains(s.pid) And
StatusList.Contains(s.status.ToUpper))
End If
Return query.OrderBy(Function(s) s.promised_date).ToList
End Using
End Function
Imports System.Data.SqlClient
Imports System.ComponentModel.DataAnnotations
Imports iTrac
<Table("tblSODetails")>
Public Class SalesOrder
<Key()>
Public Property sid As Decimal
Public Property SalesOrderNumber As String
Public Property SalesOrderLine As String
Public Property NeedDate As Date
Public Property PromisedDate As Date
Public Property ShipTo As String
Public Property Customer As String
<Column("UnitPriceOfOrder")>
Public Property UnitPrice As Decimal?
<Column("PriceUnitOfOrder")>
Public Property PriceUnit As String
Public Property OrderQuantity As Decimal?
Public Property OrderBalance As Decimal?
Public Property OrderEntryDate As Date
<Column("Material")>
Public Property CustomerPartNumber As String
Public Property LastUpdated As Date
Public Property CustomerPO As String
<NotMapped()>
Public Property NormalizedPartNumber As String
Public Property OfficeNote As String
Public Property pid As Integer?
Public Property aid As Integer?
Public Property cid As Integer?
Public Property TransferTime As Date
Public Property ShipVia As String
<NotMapped>
Public Property RunningTotal As Integer?
<ForeignKey("pid")>
Public Property Inventory As CompiledInventory
<ForeignKey("pid")>
Public Property Part As Part
<NotMapped()>
Public Property RTS
<NotMapped()>
Public Property Plate
<NotMapped()>
Public Property Machined
<NotMapped()>
Public Property Status
Private Shared ConnectionString As String = BrowserUtilities.Settings.ConnectionString
Public ReadOnly Property Blocked As Boolean
Get
Return ShippingBlock.BlockExists(SalesOrderNumber, SalesOrderLine)
End Get
End Property
Public Shared Function OpenSalesOrderList(ByVal CustomerName As String,
ByVal ShipToAddress As String,
ByVal CustomerPartNumber As String,
ByVal CutOffDate As String,
ByVal NormalizedID As String,
ByVal UpdatedWindow As String,
Optional ByVal CustomerPO As String = "") As List(Of SalesOrder)
Dim SalesOrderList As New List(Of SalesOrder)
Using Connection As New SqlConnection(ConnectionString)
Connection.Open()
Dim sqlString = ""
Dim sqlWhereClause = ""
If CustomerName <> "" Then
sqlWhereClause = " where customer = '" & CustomerName & "'"
End If
If ShipToAddress <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and shipto = '"
Else
sqlWhereClause += " where shipto = '"
End If
sqlWhereClause += ShipToAddress + "'"
End If
If CustomerPartNumber <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and material like '"
Else
sqlWhereClause += " where material like '"
End If
sqlWhereClause += CustomerPartNumber + "'"
End If
If CustomerPO <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and customerpo = '"
Else
sqlWhereClause += " where customerpo = '"
End If
sqlWhereClause += CustomerPO + "'"
End If
If NormalizedID <> "" Then
If NormalizedID <> "0" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and pid = '"
Else
sqlWhereClause += " where pid = '"
End If
sqlWhereClause += NormalizedID + "'"
End If
End If
If CutOffDate <> "" And CustomerPO = "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and promiseddate <= '"
Else
sqlWhereClause += " where promiseddate <= '"
End If
sqlWhereClause += CutOffDate + "'"
End If
If UpdatedWindow <> "" Then
If sqlWhereClause > "" Then
sqlWhereClause += " and "
Else
sqlWhereClause += "where "
End If
sqlWhereClause += "lastupdated between '" & Now.AddHours(-Val(UpdatedWindow)) & "' and '" & Now & "'"
End If
sqlString = "Select s.*, (select NormalizedPartNumber from tblPart where id = pid) as NormalizedPartNumber from tblSODetails as s" & sqlWhereClause
If UpdatedWindow <> "" Then
sqlString += " order by customer, normalizedpartnumber, promiseddate"
Else
sqlString += " order by promiseddate"
End If
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
Dim so = New SalesOrder()
so.MapDataReader(dataReader, 1)
SalesOrderList.Add(so)
End While
End Using
Return SalesOrderList
End Function
Private Sub MapDataReader(ByVal dataReader As IDataReader, ByVal Method As Integer)
Select Case Method
Case 0, 1
sid = If(IsDBNull(dataReader("sid")), "", dataReader("sid"))
SalesOrderNumber = If(IsDBNull(dataReader("salesordernumber")), "", dataReader("salesordernumber"))
SalesOrderLine = If(IsDBNull(dataReader("salesorderline")), "", dataReader("salesorderline"))
PromisedDate = If(IsDBNull(dataReader("promiseddate")), "", dataReader("promiseddate"))
ShipTo = If(IsDBNull(dataReader("shipto")), "", dataReader("shipto"))
Customer = If(IsDBNull(dataReader("customer")), "", dataReader("customer"))
UnitPrice = If(IsDBNull(dataReader("unitpriceoforder")), 0, dataReader("unitpriceoforder"))
PriceUnit = If(IsDBNull(dataReader("priceunitoforder")), "", dataReader("priceunitoforder"))
OrderQuantity = If(IsDBNull(dataReader("orderquantity")), "", dataReader("orderquantity"))
OrderBalance = If(IsDBNull(dataReader("orderbalance")), "", dataReader("orderbalance"))
OrderEntryDate = If(IsDBNull(dataReader("orderentrydate")), "", dataReader("orderentrydate"))
CustomerPartNumber = If(IsDBNull(dataReader("material")), "", dataReader("material"))
LastUpdated = If(IsDBNull(dataReader("lastupdated")), "", dataReader("lastupdated"))
CustomerPO = If(IsDBNull(dataReader("customerpo")), "", dataReader("customerpo"))
OfficeNote = If(IsDBNull(dataReader("officenote")), "", dataReader("officenote"))
pid = If(IsDBNull(dataReader("pid")), 0, dataReader("pid"))
aid = If(IsDBNull(dataReader("aid")), 0, dataReader("aid"))
cid = If(IsDBNull(dataReader("cid")), 0, dataReader("cid"))
TransferTime = dataReader("transfertime")
ShipVia = If(IsDBNull(dataReader("shipvia")), "", dataReader("shipvia"))
NeedDate = If(IsDBNull(dataReader("new_promised_date")), dataReader("promiseddate"), dataReader("new_promised_date"))
If Method = 1 Then NormalizedPartNumber = If(IsDBNull(dataReader("normalizedpartnumber")), "", dataReader("normalizedpartnumber"))
Case 2
Customer = If(IsDBNull(dataReader("customer")), "Unknown", dataReader("customer"))
End Select
End Sub
Public Shared Function SalesOrdersByBody(ByVal BodyID As String, ByVal CustomerPartNumber As String) As List(Of SalesOrder)
Dim SalesOrderList As New List(Of SalesOrder)
Dim CP As New Part
Using Connection As New SqlConnection(ConnectionString)
Dim sqlString = ""
Connection.Open()
If BodyID > "" Then
sqlString = "Select s.*, d.new_promised_date from tblPart as p " &
"inner join tblSODetails as s on p.id = s.pid " &
"inner join tblJBSODetails d on d.sales_order = s.salesordernumber " &
"inner join tblBillOfMaterial as b on p.id = b.parent and parentclass = 'rts' " &
"where b.child = " & BodyID & " order by s.promiseddate"
Else
sqlString = "Select s.*, d.new_promised_date from tblPart as p " &
"inner join tblSODetails as s on s.pid = p.id " &
"inner join tblJBSODetails d on d.sales_order = s.salesordernumber " &
"where p.CustomerPartNumber = '" & CustomerPartNumber & "' " &
"order by s.promiseddate"
End If
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
Dim so = New SalesOrder()
so.MapDataReader(dataReader, 0)
SalesOrderList.Add(so)
End While
End Using
Return SalesOrderList
End Function
Public Shared Function SalesOrdersByBody_JB(ByVal BodyID As String) As List(Of JBSODetail)
Dim SalesOrderList As New List(Of JBSODetail)
Using context = New iTracContext
Dim BOMList = New List(Of Integer)
Dim StatusList As New List(Of String)
BOMList = context.BillOfMaterials.Where(Function(b) b.Child = BodyID And b.ParentClass = "RTS").Select(Function(b) b.Parent).ToList
If BOMList Is Nothing Then
Return Nothing
Else
StatusList.Add("OPEN")
StatusList.Add("HOLD")
StatusList.Add("BACKORDER")
End If
Dim query = context.JBSODetails.Include("Part").Include("SOHeader").AsQueryable
If Not String.IsNullOrEmpty(BodyID) Then
query = query.Where(Function(s) BOMList.Contains(s.pid) And StatusList.Contains(s.status.ToUpper))
End If
Return query.OrderBy(Function(s) s.promised_date).ToList
End Using
End Function
Public Shared Function SalesOrdersByPartID(ByVal PartID As Integer) As List(Of SalesOrder)
Dim SalesOrderList As New List(Of SalesOrder)
Using Connection As New SqlConnection(ConnectionString)
Dim sqlString = ""
Connection.Open()
sqlString = "Select s.*, d.new_promised_date from tblPart as p " &
"inner join tblSODetails as s on p.id = s.pid " &
"inner join tblJBSODetails d on d.sales_order = s.salesordernumber " &
"inner join tblBillOfMaterial as b on p.id = b.parent and parentclass = 'rts' " &
"where b.parent = " & PartID & " order by s.promiseddate"
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
Dim so = New SalesOrder()
so.MapDataReader(dataReader, 0)
SalesOrderList.Add(so)
End While
End Using
Return SalesOrderList
'Using context = New iTracContext
' Return context.SalesOrders.Where(Function(s) s.pid = PartID).ToList
'End Using
End Function
Public Shared Function SalesOrdersByPartID_JB(ByVal PartID As Integer) As List(Of JBSODetail)
Dim SalesOrderList As New List(Of JBSODetail)
Using context = New iTracContext
Dim query = context.JBSODetails.Include("SOHeader").Include("Part").AsQueryable
If Not String.IsNullOrEmpty(PartID) Then query = query.Where(Function(s) s.pid = PartID)
query = query.Where(Function(s) s.status = "Open")
Return query.OrderBy(Function(s) s.promised_date).ToList
End Using
End Function
Public Function CustomerList(ByVal CutoffDate As Date) As List(Of String)
Dim CList As New List(Of String)
Using Connection As New SqlConnection(ConnectionString)
Connection.Open()
Dim sqlString = "select customer from tblSODetails where promiseddate <= '" & CutoffDate.ToShortDateString & "' " &
"group by customer order by customer"
Dim command = New SqlCommand(sqlString, Connection)
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
MapDataReader(dataReader, 2)
CList.Add(Customer)
End While
End Using
Return CList
End Function
Public Shared Function OpenList(ByVal CutoffDate As Date, ByVal Customer As String, ByVal ShipVia As String) As List(Of SalesOrder)
Using context = New iTracContext
Dim query = context.SalesOrders.Include("Inventory").Include("Part").AsQueryable
query = query.Where(Function(s) s.PromisedDate <= CutoffDate)
If Not String.IsNullOrEmpty(Customer) Then query = query.Where(Function(s) s.Customer = Customer)
If Not String.IsNullOrEmpty(ShipVia) Then query = query.Where(Function(s) s.ShipVia = ShipVia)
Return query.OrderBy(Function(l) l.PromisedDate).ToList
End Using
End Function
Public ReadOnly Property PartNumber As String
Get
If Part IsNot Nothing Then
Return Part.NormalizedPartNumber
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsOk As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_ok
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsHold As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_hold
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsRejected As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_rejected
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsOut As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_out
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsInReceving As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_receiving
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsInShipping As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_in_shipping
Else
Return Nothing
End If
End Get
End Property
Public ReadOnly Property rtsIssued As Integer?
Get
If Inventory IsNot Nothing Then
Return Inventory.rts_issued
Else
Return Nothing
End If
End Get
End Property
End Class
This line is throwing the exception:
Private Shared ConnectionString As String = BrowserUtilities.Settings.ConnectionString
Something in the expression BrowserUtilities.Settings.ConnectionString is throwing an exception. It's unclear what it is but I would say that NullReferenceException is the most likely candidate. Maybe BrowserUtilities.Settings is Nothing. It's just guesswork at this point. You'll have to debug it to find out.
When a Shared (static in C#) field, such as ConnectionString in your code, has an initialization expression, that initialization occurs in a special method called a "type initializer". All initialization expressions for the Shared fields in a type are grouped into the type initializer and executed before the first time that type is used*.
*This is a slight simplification for the sake of this explanation.
The first time you called the SalesOrdersByBody_JB function, it first had to initialize the type, which means running the type initializer to initialize ConnectionString. It looked like SalesOrdersByBody_JB threw the exception, but it was really happening slightly before that.

VB linq to entities Field called FIELD_NAME does not exist

I have spent the last hours trying to figure out what is causing this exception : Field called GENDER_DESC does not exist. Here are my codes:
Public Class RelationPatient
Public PatNetId As String
Public PatNetIdRel As String
Public Nom As String
Public Prenom As String
Public Sexe As String
Public TypeRel As String
Public Ordre As String
Public DateEnrol As Date
End Class
Public Shared Function GetRelPatient(ByVal PatNetId As String) As List(Of RelationPatient)
Using context As New DAL.SanteReprodEntities
context.Database.Connection.Open()
Dim patient As List(Of RelationPatient)
patient = (From p In context.PAT_REL
Join pa In context.PATIENTS.Include("GENDER_REF") On p.PAT_NET_ID_REL Equals (pa.PAT_NET_ID)
Join pn In context.PAT_NAME On pn.PAT_NET_ID Equals (p.PAT_NET_ID_REL)
Where p.PAT_NET_ID = PatNetId _
And p.VOIDED = 2 Select New RelationPatient With {.PatNetId = p.PAT_NET_ID, .PatNetIdRel = p.PAT_NET_ID_REL, .Nom = pn.LASTNAME, .Prenom = pn.FIRSTNAME, .Sexe = pa.GENDER_REF.GENDER_DESC, .TypeRel = p.REL_TYPE_ID, .Ordre = p.PATIENT_INDEX_TEMOIN, .DateEnrol = pa.ENROL_DATE}).ToList
Return patient
context.Database.Connection.Close()
End Using
End Function
Private Sub FrmLienPatient_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
DsEnrolement.PAT_REL.Clear()
DsEnrolement.Merge(DAL.dalManager.GetPatRelation(PAT_NET_ID))
Dim patRel As List(Of DAL.RelationPatient)
Dim sexe As String = String.Empty
patRel = DAL.dalManager.GetRelPatient(PAT_NET_ID)
If patRel IsNot Nothing Then
If patRel.Count > 0 Then
For Each rel As DAL.RelationPatient In patRel
MsgBox(rel.PatNetIdRel + ", " + rel.Nom + ", " + rel.Prenom + ", " + rel.Sexe + ", " + rel.TypeRel + ", " + rel.Ordre + ", " + rel.DateEnrol.ToShortDateString) 'This message is displayed well
PATI_RELDataGridView.Rows.Add(New String() {rel.PatNetIdRel, rel.Nom, rel.Prenom, sexe, rel.TypeRel, rel.Ordre, rel.DateEnrol.ToShortDateString}) 'Even if I put any string there like PATI_RELDataGridView.Rows.Add(New String() {"", "", "", "", "", "", ""}) the result is the same
Next
End If
End If
End Sub
Thanks in advance for your help.

How would I write formatted data to a file and then read it? VB.NET (2012 edition)

I'm practicing VB.NET and I've got a problem with Reading and writing to a .dat file. I have made a structure to store data temporarily (below).
Structure CustomerType
Dim AccountNum As String
Dim Surname As String
Dim Forename As String
Dim Balance As Decimal
End Structure
I then Dim everything.
Dim Customers(9) As CustomerType
Dim Filename As String = "Accounts.dat"
Dim NumberOfRecords As Short = 0
Dim myFormat As String = "{0,-15}|{1,-15}|{2,-10}|{3,-10}"
I have a button that creates a new account and this is where I get the problem.
FileOpen(1, Filename, OpenMode.Random, , , )
For i = 1 To Customers.Length() - 1
With Customers(i)
.Forename = InputBox("First name", "Forename")
Do Until .Forename <> "" And TypeOf .Forename Is String
.Forename = InputBox("First name", "Forename")
Loop
.Surname = InputBox("Surname", "Surname")
Do Until .Surname <> "" And TypeOf .Surname Is String
.Surname = InputBox("Surname", "Surname")
Loop
.AccountNum = InputBox("Account Number of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Account Number")
Do Until .AccountNum.Length = 8 And TypeOf .AccountNum Is String
.AccountNum = InputBox("Account Number of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Account Number")
Loop
.Balance = InputBox("Balance of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Balance")
Do Until .Balance > -1
.Balance = InputBox("Balance of " & Customers(i).Forename & " " & Customers(i).Surname & ".", "Balance")
Loop
FilePut(1, Customers, NumberOfRecords + 1)
NumberOfRecords += 1
lblNumberOfRecords.Text = NumberOfRecords
End With
Next
FileClose(1)
I have another button that displays the data in a listbox. I can only get one item to display before I get a bad length error.
Dim Index As Integer
ListBox1.Items.Clear()
ListBox1.Items.Add(String.Format(myFormat, "Forename", "Surname", "Acc. Num.", "Balance"))
ListBox1.Items.Add("_____________________________________________________")
FileOpen(1, Filename, OpenMode.Random, , , )
For Index = 1 To NumberOfRecords
FileGet(1, Customers)
ListBox1.Items.Add(String.Format(myFormat, Customers(Index).Forename, Customers(Index).Surname, Customers(Index).AccountNum, Format(Customers(Index).Balance, "currency")))
Next Index
FileClose(1)
The main question that I have is What am I doing wrong, and how can I fix it?
Many Thanks in advance,
Jordan
First you'll need to import these namespaces:
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
Model
Change your customertype model to this:
<Serializable()> _
Public Class CustomerType
Implements ISerializable
Public Sub New()
End Sub
Protected Sub New(info As SerializationInfo, context As StreamingContext)
Me.AccountNum = info.GetString("AccountNum")
Me.Surname = info.GetString("Surname")
Me.Forename = info.GetString("Forename")
Me.Balance = info.GetDecimal("Balance")
End Sub
Public AccountNum As String
Public Surname As String
Public Forename As String
Public Balance As Decimal
Public Sub GetObjectData(info As System.Runtime.Serialization.SerializationInfo, context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
info.AddValue("AccountNum", Me.AccountNum)
info.AddValue("Surname", Me.Surname)
info.AddValue("Forename", Me.Forename)
info.AddValue("Balance", Me.Balance)
End Sub
End Class
Your model do now support serialization. Next step is to create functions to read/write a model collection to/from a file.
Write
Friend Shared Sub Write(filePathAndName As String, list As List(Of CustomerType))
Dim formatter As IFormatter = New BinaryFormatter()
Using stream As New FileStream(filePathAndName, FileMode.Create, FileAccess.Write, FileShare.None)
formatter.Serialize(stream, list)
End Using
End Sub
Read
Friend Shared Function Read(filePathAndName As String) As List(Of CustomerType)
Dim formatter As IFormatter = New BinaryFormatter()
Dim list As List(Of CustomerType) = Nothing
Using stream As New FileStream(filePathAndName, FileMode.Open, FileAccess.Read, FileShare.None)
list = DirectCast(formatter.Deserialize(stream), List(Of CustomerType))
End Using
Return list
End Function
Usage
Drop a button named Button1 onto a form named Form1 and add this code:
Public Class Form1
Public Sub New()
Me.InitializeComponent()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim path As String = "C:\test.dat" '<- Change to desired path
Dim list As New List(Of CustomerType)
'Create test item1 and add to list.
Dim item1 As New CustomerType()
With item1
.AccountNum = "1"
.Balance = 1000D
.Forename = "Forename 1"
.Surname = "Surname 1"
End With
list.Add(item1)
'Create test item2 and add to list.
Dim item2 As New CustomerType()
With item2
.AccountNum = "2"
.Balance = 2000D
.Forename = "Forename 2"
.Surname = "Surname 2"
End With
list.Add(item2)
'Write to file:
Write(path, list)
'Read from file into new list:
Dim list2 As List(Of CustomerType) = Read(path)
MsgBox(String.Format("Count={0}", list2.Count))
End Sub
Friend Shared Sub Write(filePathAndName As String, list As List(Of CustomerType))
Dim formatter As IFormatter = New BinaryFormatter()
Using stream As New FileStream(filePathAndName, FileMode.Create, FileAccess.Write, FileShare.None)
formatter.Serialize(stream, list)
End Using
End Sub
Friend Shared Function Read(filePathAndName As String) As List(Of CustomerType)
Dim formatter As IFormatter = New BinaryFormatter()
Dim list As List(Of CustomerType) = Nothing
Using stream As New FileStream(filePathAndName, FileMode.Open, FileAccess.Read, FileShare.None)
list = DirectCast(formatter.Deserialize(stream), List(Of CustomerType))
End Using
Return list
End Function
End Class

asp.net vb website loop through database rows

I am working on my first website and need help with a loop. I have a database table containing food items named Menu with 8 categories (such as Burgers, Appetizers). I also have a menu page on website with 8 different pics to display items from each category. I need to loop through rows of database. What is happening is it's only looping through columns and repeating first line over and over. I'm aware I need a loop but for some reason cannot get that right.
This is code behind:
Partial Class Burger
Inherits System.Web.UI.Page
'String Used to build the necessary markup and product information
Dim str As String = ""
'Var used to interact with SQL database
Dim db As New Interaction
'Adds the necessary markup for each menu item, using its productName
Protected Sub printMenuBlock(ByVal productName As String)
'Set up variable storing the product
Dim product As Product
'Pull the product in from our database using the productName
product = db.ReadProduct(productName)
'Add necessary markup to str variable, with products information within
str += "<div class='storeItem'>"
' str += " <img alt='Item Picture' class='itemPicture' src='" + product.ImagePath.Substring(3).Replace("\", "/") + "' />"
' str += " <div class='itemInfo'>"
str += " <h1 class='itemName'>"
str += " " + product.Name + "</h1>"
str += " <h3 class='itemDescription'>"
str += " " + product.Description + "</h3>"
str += " <p class='itemPrice'>"
str += " " + product.Price.ToString("c") + "</p>"
str += " "
str += " </div>"
str += " </div>"
End Sub
'Uses
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim productNames As New List(Of String)
'Pull the product names using the database
productNames = db.getProductNames
'Loop through all product names
For Each name As String In productNames
'Add necessary markup and product info to str variable
printMenuBlock(name)
Next
'Print the str variable in our menuPlace div
menuPlace.InnerHtml = str
End Sub
End Class
This is functions from interaction class:
Private Sub GetProduct(ByVal CatIn As String)
' SQL String
Dim strSelect As String
strSelect = "SELECT * "
strSelect &= " FROM Menu "
' strSelect &= " WHERE (ProductCat = 'Burgers')"
' Set up the connection to the datebase
cmdSelect.Connection = conIn.Connect
' Add the SQL string to the connection
cmdSelect.CommandText = strSelect
' Add the parameters to the connection
cmdSelect.Parameters.Add("#CatIn", SqlDbType.NVarChar).Value = CatIn
End Sub
'Executes the SQL statement to find a Product by ProductId
Public Function ReadProduct(ByVal CatIn As String) As Product
' Product object initalized to nothing
Dim prod As Product = Nothing
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
Dim strCat As String
Dim strName As String
Dim strDesc As String
Dim decPrice As Decimal
Dim strPath As String
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
dbr.Read()
' Check if there are any returned values
If dbr.HasRows Then
' Assign the value in column two to strName
strCat = dbr.GetString(1)
' Assign the value in column two to strName
strName = dbr.GetString(2)
' Assign the value in column three to strDesc
strDesc = dbr.GetString(3)
' Assing the value in column four to intPrice
decPrice = ToDecimal(dbr.GetValue(4))
'Assign the value in column five to strPath
'strPath = dbr.GetString(3)
' Create the new Product object from the returned values
prod = New Product(strName, strDesc, decPrice, strCat, strPath)
End If
' Clear the SQL parameters and close the connection
cmdSelect.Parameters.Clear()
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return prod
End Function
'Returns a list of Product Names
Public Function getProductNames() As List(Of String)
Dim list As New List(Of String)
Dim sql As String = "SELECT ProductName FROM Menu " +
"WHERE (ProductCat) = 'Burgers'"
'"DISTINCT 'ProductName'"
cmdSelect.CommandText = sql
cmdSelect.Connection = conIn.Connect
Dim dbr As SqlDataReader
dbr = cmdSelect.ExecuteReader
If dbr.HasRows Then
Do While dbr.Read()
list.Add(dbr.GetString(0))
Loop
End If
dbr.Close()
Return list
End Function
There is obviously a Product Class but don't think that is necessary to show on here.
Also, ignore the string path, that will be for images later. Thanks for any help. I'm pretty sure instead of do while I need a for each somewhere but just can't get her done. Thanks in advance.
Products Class:
Public Class Product
Private pName As String
Private pDescription As String
Private pPrice As Integer
Private pPath As String
Private pCat As String
'Constructor, uses database to populate properties based on productName
Public Sub New(ByVal productName As String)
Dim data As New Interaction
Dim work As Product
work = data.ReadProduct(productName)
pCat = work.Cat
pName = work.Name
pDescription = work.Description
pPrice = work.Price
End Sub
'Constructor, populates properties from passed in values
Public Sub New(ByVal NameIn As String,
ByVal DescriptionIn As String, ByVal PriceIn As Integer, ByVal CatIn As String, ByVal ImagePathIn As String)
pName = NameIn
pDescription = DescriptionIn
pPrice = PriceIn
pPath = ImagePathIn
pCat = CatIn
End Sub
'Stores name of product
Public ReadOnly Property Name() As String
Get
Return pName
End Get
End Property
'Stores a description of the product
Public ReadOnly Property Description() As String
Get
Return pDescription
End Get
End Property
'Stores the price of the product
Public ReadOnly Property Price() As Integer
Get
Return pPrice
End Get
End Property
'Stores the path to the image associated with this product
Public ReadOnly Property ImagePath() As String
Get
Return pPath
End Get
End Property
'Stores name of product
Public ReadOnly Property Cat() As String
Get
Return pCat
End Get
End Property
End Class
Use this instead
Public Function ReadProduct(ByVal CatIn As String) As List(Of Dictionary(String, Of String))
Dim ReturnProducts As New List(Of Dictionary(String, Of String))
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
Dim FieldCount = dbr.FieldCount()
Dim ColumnList as New List(Of String)
For i as Integer = 0 to FieldCount - 1
ColumnList.Add(dbr.GetName(i))
Next
While dbr.Read()
Dim ReturnProduct As New Dictionary(String, Of String)
For i as Integer = 0 to FieldCount - 1
ReturnProduct.Add(ColumnList(i), dbr.GetValue(i).toString())
Next
ReturnProducts.Add(ReturnProduct)
End While
cmdSelect.Parameters.Clear()
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return ReturnProducts
End Function
then, inside printMenuBlock, you declare product with
Dim product = db.ReadProduct(productName)
and later, you access it like so
For i as Integer = 0 to product.Count - 1
'do everything normally for building str except, for example, if you want
'to acccess product.Name as before, access it with product(i).Item("Name"),
'assuming that your column name/alias for "Name" is in fact "Name"
'i personally like to align column names to variable names for laziness's sake
'bad obfuscation practice tho if you don't use aliases
Next

Sort list alphabetically

How can I get the resulting generated list of links sorted out alphabetically according to "sTitle"? My sort function on line 272 is not giving me the results I need. Please help.
<script language="VB" runat="server">
Function sectionTitle(ByRef f As String)
'Open a file for reading
'Dim FILENAME As String = Server.MapPath("index.asp")
Dim FILENAME As String = f
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(FILENAME)
'Now, read the entire file into a string
Dim contents As String = objStreamReader.ReadToEnd()
'search string for <title>some words</title>
Dim resultText As Match = Regex.Match(contents, "(<title>(?<t>.*?)</title>)")
'put result into new string
Dim HtmlTitle As String = resultText.Groups("t").Value
Return HtmlTitle
' If HtmlTitle <> "" Then
'Response.Write(HtmlTitle)
' Else
'Response.Write("<ul><li>b: " & contents & "</a></li></ul>")
' End If
End Function
Public Class linkItem
Public myName As String
Public myValue As String
Public Sub New(ByVal myName As String, ByVal myValue As String)
Me.myName = myName
Me.myValue = myValue
End Sub 'New
End Class 'linkItem
Sub DirSearch(ByVal sDir As String)
Dim d As String
Dim f As String
Dim mylist As New List(Of linkItem)
Try
For Each d In Directory.GetDirectories(sDir)
'Response.Write("test c")
For Each f In Directory.GetFiles("" & d & "", "index.asp")
'Response.Write("test a")
Dim sTitle As String = sectionTitle(f)
'remove wilbur wright college - from sTitle string
sTitle = Regex.Replace(sTitle, "My College - ", "")
'print section title - must come before search n replace string
f = Regex.Replace(f, "C:\\inetpub\\wwwroot\\mypath\\", "")
'add to list
mylist.Add(New linkItem(f, sTitle))
'print links as list
'Response.Write("<ul><li><a href='" & f & "'>" & sTitle & "</a></li></ul>")
Next
DirSearch(d)
Next
Catch excpt As System.Exception
'Response.Write("test b")
Response.Write(excpt.Message)
End Try
mylist.Sort(Function(p1, p2) p1.myValue.CompareTo(p2.myValue))
mylist.ForEach(AddressOf ProcessLink)
End Sub
Sub ProcessLink(ByVal P As linkItem)
If (True) Then
Response.Write("<ul><li><a href='" & P.myName & "'>" & P.myValue & "</a></li></ul>")
End If
End Sub
</script>
<%
'Dim sDir As New DirectoryInfo(Server.MapPath(""))
Call DirSearch((Server.MapPath("")))
%>
Check out the IComparable interface to help with this.
Basically, you need to teach your program what to use as a comparison point of reference for your class.
IComparable will allow you to make use of the CompareTo() method.
Here's the sample code if you're interested:
Public Class Temperature
Implements IComparable
Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
Implements IComparable.CompareTo
If TypeOf obj Is Temperature Then
Dim temp As Temperature = CType(obj, Temperature)
Return m_value.CompareTo(temp.m_value)
End If
Throw New ArgumentException("object is not a Temperature")
End Function
' The value holder
Protected m_value As Integer
Public Property Value() As Integer
Get
Return m_value
End Get
Set(ByVal Value As Integer)
m_value = Value
End Set
End Property
Public Property Celsius() As Integer
Get
Return (m_value - 32) / 2
End Get
Set(ByVal Value As Integer)
m_value = Value * 2 + 32
End Set
End Property
End Class