How to I add an item to a list with class in vb? - vb.net

I have to convert my c# into vb but it didn't convert 100%, I'm stuck on adding items to lists with class objects.
I get error here (Value of type 'Boolean' cannot be converted to '_Default.Courses') on the course list add:
Public Class Courses
Public courseName As String
Public qualName As String
Public providerName As String
End Class
...
While r.Read
Dim coursename As String = r("courseName").ToString
Dim qualname As String = r("qualName").ToString
Dim providername As String = r("providerName").ToString
courseList.Add(New Courses() With {
Key.courseName = coursename,
Key.qualName = qualname,
Key.providerName = providername
})
End While
...
And this is the original c# code:
while (r.Read())
{
string coursename = r["courseName"].ToString();
string qualname = r["qualName"].ToString();
string providername = r["providerName"].ToString();
courseList.Add(new Courses
{
courseName = coursename,
qualName = qualname,
providerName = providername
});
}

Change your code as :
While r.Read
Dim coursename As String = r("courseName").ToString
Dim qualname As String = r("qualName").ToString
Dim providername As String = r("providerName").ToString
courseList.Add(New Courses() With {
.courseName = coursename,
.qualName = qualname,
.providerName = providername
})
End While

Related

Value of type String() cannot be converted into ArrayList

I'm trying to automate test some codes and I can't seem to get this working on ListObject.
If I run the test it fails with an error:
Value of type String() cannot be converted into ArrayList.
Here's what I'm trying:
C# CODE:
public string[] GetUserIdsFromPassId(string organisationId, string #PassId)
{
DbParameterCollection parameters = new DbParameterCollection();
parameters.Add(new DbParameter("#OrganisationId", SqlDbType.NVarChar, organisationId));
parameters.Add(new DbParameter("#PassId", SqlDbType.NVarChar, #PassId));
string sql = "SELECT UserId FROM Orchestra WHERE OrganisationId=#OrganisationId AND PassId=#PassId";
ListObject list = new ListObject(_Accessor);
list.Read(sql, parameters);
List<string> userIds = new List<string>();
foreach (DataRow dataRow in list.Table.Rows)
userIds.Add(dataRow["UserId"].ToString());
return userIds.ToArray();
}
AUTOMATE TESTING CODE:
<TestClass()> Public Class Check_UserIdsFromPassId
<TestMethod()> Public Sub GetUserIdsFromPassId()
Dim organisationId As String = "1123"
Dim PassId As String = "8110004"
Dim UserId As string = String.Empty
Dim ExpUserId As String = "00044"
Dim DataServer As New DataServer()
Dim Accessor = DataServer.GetAccessor()
Dim _StandardHeader = New StandardHeader
Dim _AuditProvider = New Audit.AuditProvider(_StandardHeader)
Dim AD As New Ceridian.Administration.Authentication.AuthenticationData(Accessor, _AuditProvider)
UserId = AD.GetUserIdsFromPassId(organisationId, PassId)
Assert.AreEqual(ExpUserId, UserId)
Console.WriteLine(ExpUserId)
Console.WriteLine(UserId)
End Sub
End Class
If you are expecting the function under test to return a string array with a single UserId (ExpUserId) you could just test the length of the array and the first value.
For instance, remove this line:
Dim UserId As string = String.Empty
Change the line that exercises the function under test to:
Dim UserId = AD.GetUserIdsFromPassId(organisationId, PassId)
and then confirm the returned array has a single correct value:
Assert.AreEqual(1, UserId.Count)
Assert.AreEqual(ExpUserId, UserId(0))

(SQL, VB.NET) How Do I select multiple values from one row and assign them to variables?

I am writing a SELECT query to use in my project. So far, I have
Dim conn As New OleDbConnection
Dim StudentID, GradeID, SubjectID As Integer
Dim YourGrade(4), YourSubject(4) As String
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =H:\Year 13 Computer Science\Project\Usernames and Passwords.accdb"
conn.Open()
Dim sql = "Select * From Grades where StudentID =" & CurrentID
Dim cmd As New OleDbCommand(sql, conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
StudentID = dr("StudentID")
GradeID = dr("GradeID")
SubjectID = dr("SubjectID")
End While
My issue is that I need to be able to have a dynamic number of SubjectIDs and GradeIDs to be selected, in case a student is taking more or fewer subjects than the normal three.
My Query produces:
StudentID GradeID SubjectID
1 2 1
1 4 13
1 3 19
the CurrentID is "1" for the purposes of this.
Each GradeID and SubjectID corresponds to values in other tables which I can work on later.
I need to be able to have each of those three Grade IDs in a separate value, an array could be used but I don't know how to code it. I attempted it earlier as shown by the "YourGrade(4), YourSubject(4)".
I intend to use the data to fill out a Data Grid.
Create a domain object for "Student" and then load the records into a list of Student Objects.
I don't know VB.net, but the equivalent Domain object in C# would look like this:
public class Student
{
public int StudentId { get; set; }
public int GradeId { get; set; }
public int SubjectId { get; set; }
}
And then the code to loop through the dataReader and populate the list:
List<Student> results = new List<Student>();
while (dr.Read())
{
results.Add(new Student()
{
StudentId = Convert.ToInt32(dr["StudentID"]),
GradeId = Convert.ToInt32(dr["GradeId"]),
SubjectId = Convert.ToInt32(dr["SubjectId"])
});
}
-- Edit 2/2/2017 --
Turns out there are free converters on the web. These are the VB.net equivalents to the snippets above.
Class:
Public Class Student
Public Property StudentId() As Integer
Get
Return m_StudentId
End Get
Set
m_StudentId = Value
End Set
End Property
Private m_StudentId As Integer
Public Property GradeId() As Integer
Get
Return m_GradeId
End Get
Set
m_GradeId = Value
End Set
End Property
Private m_GradeId As Integer
Public Property SubjectId() As Integer
Get
Return m_SubjectId
End Get
Set
m_SubjectId = Value
End Set
End Property
Private m_SubjectId As Integer
End Class
Database Code:
Dim results As New List(Of Student)()
While dr.Read()
results.Add(New Student() With { _
Key .StudentId = Convert.ToInt32(dr("StudentID")), _
Key .GradeId = Convert.ToInt32(dr("GradeId")), _
Key .SubjectId = Convert.ToInt32(dr("SubjectId")) _
})
End While
I did some digging, found out that to fill out a datagrid in the way I was attempting to, the simplest way is to use an INNER JOIN SQL statement. In SQL the query is:
SELECT Students.FirstName, Students.LastName, Subjects.SubjectName, GradeVals.Grade
FROM GradeVals INNER JOIN (Students INNER JOIN (Subjects INNER JOIN Grades ON Subjects.SubjectID = Grades.SubjectID) ON Students.StudentID = Grades.StudentID) ON GradeVals.GradeID = Grades.GradeID;
That's using my Table names and such as.

Create own data examples in LinqPad

I have a class (vb.net) with some data that I want to query in LinqPad. I already worked with some examples as the one from "Linq in Action" so they work with some kind of classes with data as well to explain queries. But I just cannot find anything about how to import or write your own classes. Could anyone help me here?
My Class looks like:
Public Class Employee
Public Property ID As Integer
Public Property Salery As Integer
Public Property Name As String
Public Property Department As String
Public Property Gender As String
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .Department = "HR", .Gender = "Male", .Salery = 12000},
New Employee With {.ID = 2, .Name = "Sandra", .Department = "IT", .Gender = "Female", .Salery = 2000} _
}
End Function
End Class
You might be missing a couple things about using LINQPad:
Set the Language to "VB Program" and put classes where the comment says to.
Use the Dump method to output an expression. (For "VB Expression", Dump is called automatically.)
Here is an example. (Note, you might be using that SQL-looking syntax.)
Sub Main
Employee.GetAllEmployees() _
.Where(Function (employee) employee.Department = "HR") _
.Dump()
Dim hrEmployees = From employee In Employee.GetAllEmployees()
Where employee.Department = "HR"
hrEmployees.Dump()
End Sub
' Define other methods and classes here
Public Class Employee
Public Property ID As Integer
Public Property Salery As Integer
Public Property Name As String
Public Property Department As String
Public Property Gender As String
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .Department = "HR", .Gender = "Male", .Salery = 12000},
New Employee With {.ID = 2, .Name = "Sandra", .Department = "IT", .Gender = "Female", .Salery = 2000} _
}
End Function
End Class

VB: How can I create an array and split the contents of a text file to different locations on a program

My pseudocode is the following
-Select a textfile through a button and collect information.
-divide the data; Let data = line.Split(","c)
-Move the data to the appropriate area on the program
-The data would look like; Bugs Bunny,VB101,Fall 2013,bugs.jpg,85,100,80,92,70,95,88,92
-Im trying to put the Name, Class, Semester into a label, the bugs.jpg into a picturebox, and then put the rest of the info(testScores) into a DataGrid. Is it possible to grab these values and split them up to different areas of the program?
This is my code as of now; I know it needs lots of work but this is where I'm currently at.
Public Class Form1
Dim student As String
Dim subject As String
Dim semester As String
Dim image As Image
Private Sub btnSelect_Click(sender As System.Object, e As System.EventArgs) Handles btnSelect.Click
Dim textFile As String
OpenFileDialog1.ShowDialog() 'Open dialog box appears and program pauses until a text file is selected
textFile = OpenFileDialog1.FileName
'Dim student() As String = IO.File.ReadAllLines(textFile)
Dim query = From line In IO.File.ReadAllLines(textFile)
Let data = line.Split(","c)
Let student = data(0)
Let subject = data(1)
Let semester = data(2)
Let image = data(3)
Let p1 = data(4)
Let p2 = data(5)
Let p3 = data(6)
Let p4 = data(7)
Let p5 = data(8)
Let p6 = data(9)
Let exam1 = data(10)
Let exam2 = data(11)
dgvOutput.DataSource = query.ToList
dgvOutput.CurrentCell = Nothing
dgvOutput.Columns("P1").HeaderText = "P1"
dgvOutput.Columns("P2").HeaderText = "P2"
dgvOutput.Columns("P3").HeaderText = "P3"
dgvOutput.Columns("P4").HeaderText = "P4"
dgvOutput.Columns("P5").HeaderText = "P5"
dgvOutput.Columns("P6").HeaderText = "P6"
dgvOutput.Columns("exam1").HeaderText = "exam1"
dgvOutput.Columns("exam2").HeaderText = "exam2"
End Sub
End Class
The DGV will name the columns automatically with this implementation. Use a class for the data and then a collection for all the students found in the file.
Private Students As New List(Of Student)
'in a sub routine that collects the data
Using sr As New StreamReader({path})
While Not sr.EndOfStream
Dim student As New Student
Dim data = line.Split(","c)
student.name = data(0)
student.subject = data(1)
student.semester = data(2)
student.image = data(3)
student.p1 = data(4)
student.p2 = data(5)
student.p3 = data(6)
student.p4 = data(7)
student.p5 = data(8)
student.p6 = data(9)
student.exam1 = data(10)
student.exam2 = data(11)
Students.Add(student)
End While
End Using
dgvOutput.DataSource = Students
Custom class:
Public Class Student
Public Property name As String
Public Property subject As String
Public Property semester As String
Public Property image As String
Public Property p1 As String
Public Property p2 As String
Public Property p3 As String
Public Property p4 As String
Public Property p5 As String
Public Property p6 As String
Public Property exam1 As String
Public Property exam2 As String
End Class
Or, you should use a DataTable to bind data to the DataGrid
Dim table = New DataTable()
table.Columns.Add("P1")
table.Columns.Add("P2")
table.Columns.Add("P3")
table.Columns.Add("P4")
table.Columns.Add("P5")
table.Columns.Add("P6")
table.Columns.Add("exam1")
table.Columns.Add("exam2")
Dim row = table.NewRow()
row.Item("P1") = P1
row.Item("P2") = P2
row.Item("P3") = P3
row.Item("P4") = P4
row.Item("P5") = P5
row.Item("P5") = P6
table.Rows.Add(row)
dgvOutput.DataSource = table

Multiple Parameters in LINQ to SQL

I am trying to pass several search parameters to an LINQ expression to retrieve all entries that contain one of the search items.
Example:
Dim query = From p In db.BEW_PROFIL
For Each searchItem As String In searchItems
Dim item As String = searchItem
query = query.Where(Function(p) p.NAME = item)
Next
Problem here is I don´t get any results because the Where clause looks with that code something like this.
... Where p.NAME = item1 AND p.NAME = item2
What i need is an OR between the parameters, but I don´t get it how I can achieve this.
Any help would be greatly appreciated.
Got it...
void Main()
{
var searchItems = new string[] { "test", "past", "most", "last", "fast", "feast", "yeast", "cast" };
var query = from p in searchItems select new MyClass { Name = p };
Predicate<MyClass> whereClause = _ => false;
foreach (var item in searchItems)
{
var searchItem = item;
Predicate<MyClass> oldClause = whereClause;
whereClause = p => p.Name == searchItem || oldClause(p);
}
query = query.Where(p => whereClause(p));
query.Dump();
}
public class MyClass
{
public MyClass() { }
public string Name { get; set; }
}
The code was ran in LINQPad, and that returned every element.
Here is that code translated to Vb.Net
Private Sub Main()
Dim searchItems = New String() {"test", "past", "most", "last", "fast", "feast", "yeast", "cast"}
Dim query = From p In searchItems Select New [MyClass]() With { .Name = p }
Dim whereClause As Predicate(Of [MyClass]) = Function(element) False
For Each item As String In searchItems
Dim searchItem = item
Dim oldClause As Predicate(Of [MyClass]) = whereClause
whereClause = Function(p) p.Name = searchItem OrElse oldClause(p)
Next
query = query.Where(Function(p) whereClause(p))
query.Dump()
End Sub
Public Class [MyClass]
Public Sub New()
End Sub
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
End Class