Multiple Parameters in LINQ to SQL - vb.net

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

Related

using csvhelper writer with shouldquote in vb.net

I can see how shouldquote works with c# but does anyone have an example in vb.net?
I need to wrap every field with chr(34)
Private Sub Main()
Dim records = New List(Of Foo) From {
New Foo With {
.Id = 1,
.Name = "one"
}
}
Dim config = New CsvConfiguration(CultureInfo.InvariantCulture) With {
.ShouldQuote = Function(args) True
}
Using csv = New CsvWriter(Console.Out, config)
csv.WriteRecords(records)
End Using
End Sub
Public Class Foo
Public Property Id As Integer
Public Property Name As String
End Class

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))

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

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

Listbox in dynamic web user controls lost data after postback

I create dynamic web user control which has a list box and a textbox. However, data in the list box is lost after postback but the data in the textbox isn't.
I've read a lot of forums and pages about web user controls and I understands that web user controls recreate after such post-back.
Could you please show me the way to get data of list box before post back ?
Thank alot
'--------------------------------------
Note that: my web user control has a list and text boxes, user can add value to the list box by entering values in the text box ( I wrote functions in javascripts to add data from text box to list box) .
However, in the main page, when I click a button to save data of the list, all of my page and my web user control are reloaded, so data in the list box is also disappear :-(
Code VB for adding web user control:
Private Sub WebFormTestValidation_Init(sender As Object, e As EventArgs) Handles Me.Init
Dim ctrList As wucListPerson
ctrList = LoadControl("wucListPerson.ascx")
Me.Panel1.Controls.Add(ctrList)
ctrList.ID = "wucDynamic"
ctrList.wucName = "DYNAMIC TEST"
ctrList.wucInfo = "DYNAMIC TEST"
End Sub
'----------------------
Code VB of web user control
Public Class wucListPerson
Inherits System.Web.UI.UserControl
Public Property lstPersons As List(Of String)
Get
Dim lst As New List(Of String)
If lstFullName.Items.Count > 0 Then
For i = 0 To lstFullName.Items.Count - 1
lst.Add(CStr(lstFullName.Items(i).Value))
Next
End If
Return lst
End Get
Set(ByVal lstValues As List(Of String))
If lstValues.Count > 0 Then
For i = 0 To lstValues.Count - 1
Dim strArr As String() = Split(CStr(lstValues.Item(i)), "*")
Ordre.Text = CStr(strArr(0))
Nom.Text = strArr(1)
Prenom.Text = strArr(2)
hdfIdPersonne.Value = strArr(3)
Dim item As New System.Web.UI.WebControls.ListItem
item.Text = strArr(0) + "." + strArr(1) + " " + strArr(2)
item.Value = CStr(lstValues.Item(i))
lstFullName.Items.Add(item)
Next
End If
End Set
End Property
Public Property wucName As String
Get
Return lblName.Text
End Get
Set(ByVal value As String)
lblName.Text = value
End Set
End Property
Public Property wucInfo As String
Get
Return Info.Text
End Get
Set(ByVal value As String)
Info.Text = value
End Set
End Property
Public Sub addPersonne(ByVal ordre As Integer, ByVal nom As String, ByVal prenom As String, idpersonne As Integer)
'lstName.Items.Add(CStr(ordre) + "." + nom + " " + prenom, CStr(ordre) + "*" + nom + "*" + prenom + "*" + CStr(idpersonne))
Dim item As New System.Web.UI.WebControls.ListItem
item.Text = CStr(ordre) + "." + nom + " " + prenom
item.Value = CStr(ordre) + "*" + nom + "*" + prenom + "*" + CStr(idpersonne)
lstFullName.Items.Add(item)
End Sub
Public Function getList() As List(Of String)
Dim lst As New List(Of String)
If lstFullName.Items.Count > 0 Then
For i = 0 To lstFullName.Items.Count - 1
lst.Add(CStr(lstFullName.Items(i).Value))
Next
End If
Return lst
End Function
Public Sub SetList(ByVal lst As List(Of String))
If lst.Count > 0 Then
For i = 0 To lst.Count - 1
Dim strArr As String() = Split(CStr(lst.Item(i)), "*")
Ordre.Text = CStr(strArr(0))
Nom.Text = strArr(1)
Prenom.Text = strArr(2)
hdfIdPersonne.Value = strArr(3)
Dim item As New ListItem
item.Text = strArr(0) + "." + strArr(1) + " " + strArr(2)
item.Value = CStr(lst.Item(i))
lstFullName.Items.Add(item)
Next
End If
End Sub
Protected uniqueKey As String
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'If Not Page.IsPostBack Then
' lblName.Text = wucName
'End If
Me.uniqueKey = Guid.NewGuid.ToString("N")
Me.cmdRight.Attributes("onclick") = ("RemoveItem_" + (uniqueKey + "(); return false;"))
Me.cmdLeft.Attributes("onclick") = ("AddItem_" + (uniqueKey + "(); return false;"))
Me.cmdInfor.Attributes("onclick") = ("showHideInfor_" + (uniqueKey + "(); return false;"))
If Trim(lblName.Text) = "" Then cmdInfor.Visible = False
End Sub
End Class
'----------------------
Code Javascript to get/ remove data from text boxes to the list
//===================
function getMaxOrdre_<%=uniqueKey%>() {
var listName = document.getElementById("<%=lstFullName.ClientID()%>");
var lst = listName.options;
var count = lst.length;
if (lst.length == 0) {
return 0;
}
var max = 0;
for (var i = 0; i < count; i++) {
var item = lst[i].value;
var FName = getFullName_<%=uniqueKey%>(item);
if (parseInt(FName.Ordre) > max) {
max = FName.Ordre;
}
}
return max;
}
//===================
function getFullName_<%=uniqueKey%>(FullName) {
if (FullName.length != "0") {
var temp = new Array();
temp = FullName.split('*');
return { Ordre: temp[0], Nom: temp[1], PreNom: temp[2], IdPersonne: temp[3] };
}
return { Ordre: 0, Nom: '', PreNom: '', IdPersonne: '0' };
}
//===================
function AddItem_<%=uniqueKey %>() {
//lstName.BeginUpdate();
var txtOrdre = document.getElementById("<%=Ordre.ClientID()%>");
var txtNom = document.getElementById("<%=Nom.ClientID()%>");
var txtPrenom = document.getElementById("<%=Prenom.ClientID()%>");
var hdfIdPerson = document.getElementById("<%=hdfIdPersonne.ClientID%>");
var listName = document.getElementById("<%=lstFullName.ClientID()%>");
var index = listName.selectedIndex;
var lst = listName.options;
var ordre = txtOrdre.value;
var nom = txtNom.value;
var prenom = txtPrenom.value;
var idPerson = hdfIdPerson.value;
if ((nom.length > 0) || (prenom.length > 0)) {
var selectBoxOption = document.createElement("option");//create new option
selectBoxOption.value = ordre + '*' + nom + '*' + prenom + '*' + idPerson;//set option value
selectBoxOption.text = ordre + '.' + nom + ' ' + prenom;//set option display text
listName.add(selectBoxOption, null);//add created option to select box.
};
// lstName.EndUpdate();
//get deafault data
var ordreMax = getMaxOrdre_<%=uniqueKey%>();
txtOrdre.value = parseInt(ordreMax) + 1;
txtNom.value = '';
txtPrenom.value = '';
hdfIdPerson.value = '0';
}
//===================
function RemoveItem_<%=uniqueKey %>() {
//lstName.BeginUpdate();
var txtOrdre = document.getElementById("<%=Ordre.ClientID()%>");
var txtNom = document.getElementById("<%=Nom.ClientID()%>");
var txtPrenom = document.getElementById("<%=Prenom.ClientID()%>");
var hdfIdPerson = document.getElementById("<%=hdfIdPersonne.ClientID%>");
var listName = document.getElementById("<%=lstFullName.ClientID()%>");
var index = listName.selectedIndex;
var lst = listName.options;
if (index >= 0) {
var FName = getFullName_<%=uniqueKey %>(lst[index].value);
txtOrdre.value = FName.Ordre;
txtNom.value = FName.Nom;
txtPrenom.value = FName.PreNom;
hdfIdPerson.value = FName.IdPersonne;
listName.remove(index);
}
}
Your problem is that you are adding the new items in the DOM, but these changes will not necessarily be reflected in your ListBox after a page refresh or PostBack. I could suggest two solutions:
1) Add the elements in the ListBox through .net instead of using Javascript.
but if you need a client side solution so that your page won't refresh everytime you add an item:
2) Add a .net HiddenField control. These controls have the advantage of being accessible easily from both Client Side and Server Side. You can add each item in both, the ListItem and the HiddenField (maybe comma separated) and on the server side you will use this HiddenField instead of your ListBox.

Return a collection of model as an output

I am simply trying to create an function to return a set of user. But, in order to be able to add the item later to a collection I used arrayList, but at last I am getting an error of Type ArrayList cannot be converted to 1-Dimensional array of Users
Here is my Code:
Function getDoctorsList() As Users()
Dim userCollection As New ArrayList
Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
Dim dr As SqlDataReader = dbHelper.ExecuteAndGetReader(sql)
While dr.Read
Dim user As New Users
user.Id = IIf(IsDBNull(dr("id")), 0, dr("id"))
user.UserName = IIf(IsDBNull(dr("username")), "", dr("username"))
user.UserNin = IIf(IsDBNull(dr("user_nin")), 0, dr("user_nin"))
user.UserType = IIf(IsDBNull(dr("usertype")), "", dr("usertype"))
user.Password = IIf(IsDBNull(dr("password")), "", dr("password"))
userCollection.Add(user)
End While
Return userCollection
End Function
How to solve such problems?
Either let your method return an ArrayList:
Function getDoctorsList() As ArrayList()
create an Array out of your ArrayList:
Return userCollection.ToArray()
or, the best solution, let your method return an IEnumerable(Of User)
Function getDoctorsList() As IEnumerable(Of User)
you should also use a List(of User) instead of a ArrayList instead, since it is type safe (and clearer) and it also implements IEnumerable(Of User).
Edit
Example using IEnumerable(of Users) and DataRowExtensions:
Function GetDoctorsList() As IEnumerable(of Users)
Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
Dim table = new DataTable()
table.Load(dbHelper.ExecuteAndGetReader(sql))
Return (from row in table.AsEnumerable()
select new User() With
{
.Id = row.FieldOf(Of Integer)("id"),
.UserName = row.Field(Of String)("username"),
.UserNin = row.Field(Of Integer)("user_nin"),
.UserType = row.Field(Of String)("usertype"),
.Password = row.Field(Of String)("password")
}).ToList()
End Function