How to convert ListItemCollection to List(of object) - asp.net

I have defined a class like
Public Class MyClass
Public Type1 As Integer
Public Type2 As float
End Class
How can I convert a ListItemCollection to a list(of MyClass) ?

The MyClass is keyword and float type in VB.NET is expressed via Single alias (System.Single)
Public Class Item
Public Type1 As Integer
Public Type2 As Single
End Class
I've construct the collection with sample data.
Dim cl As New ListItemCollection
cl.Add(New ListItem("1", "1.2"))
cl.Add(New ListItem("2", "2.3"))
cl.Add(New ListItem("3", "3.4"))
Dim lst = From ele In cl Select New _
Item With
{
.Type1 = Integer.Parse(ele.Text),
.Type2 = Single.Parse(ele.Value)
}
For Each ele As Item In lst
Response.Write("<br/> " & ele.Type1 & " " & ele.Type2)
Next

Dim x As New List(of [MyClass])
For Each y as [MyClass] in ListItemCollectionInstance.Items
if (y.Selected)
x.Add(y)
Next y
Using Linq:
Dim selectedItems As List(Of [MyClass]) = ListItemCollectionInstance.Items.Cast(Of [MyClass])().Where(Function(itm) itm.Selected = True).ToList()

Related

Local sequence cannot be used in LINQ to SQL implementations

So here is what i am trying to do. I have tables from the DB and 1 list of member. I get the member from the asp.net membership controls and it a combined membership and profile object. I have a function that will return a list the following Mems object:
Public Property FirstName As String = ""
Public Property LastName As String = ""
Public Property Address1 As String = ""
Public Property Address2 As String = ""
Public Property City As String = ""
Public Property State As System.Int32 = "0"
Public Property Zip As String = ""
Public Property Title As String = ""
Public Property Phone As System.Decimal = "0"
Public Property Id As System.Int32 = "0"
Public Property UserType As System.Int32 = "0"
Public Property SSN As System.Int32 = "0"
Public Property Email As String = ""
Public Property UserName As String = ""
Public Property IsLockedOut As Boolean = False
Private Loaded As Boolean = False
then I have the 2 tables of Jobs and Accounts:
Jobs
JobId numeric(18,0)
AccountId numeric(18,0)
Name varchar(50)
Frequency int
Modifier varchar(90)
Active bit
sDate date
eDate date
Accounts
AccountId numeric(18,0)
CompanyId numeric(18,0)
ContactId varchar(256)
Type int
Name varchar(256)
Address1 varchar(50)
Address2 varchar(50)
City varchar(50)
State int
Zip varchar(5)
AuthCode varchar(10)
Comments text
The output I am trying to achieve is a list of Jobs for the accounts for a particular companyid with the info from the mems. I have it working elsewhere for the accounts, but when i throw the jobs in the mix, It give me the error of:
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
Here is where I have gotten with the function as of the moment:
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Function JobSearch(jSon As String) As String
Dim DamnSer As New JavaScriptSerializer
Dim Search As SearchString = DamnSer.Deserialize(Of SearchString)(jSon)
Dim myDB As New MyDbDataContext
Dim pro As New Mems(HttpContext.Current.User.Identity.Name)
Dim acc = From a In myDB.Accounts Where a.CompanyId = pro.Id Select a
Dim accList = acc.Where(Function(r) r.AccountId).[Select](Function(r) r.AccountId.ToString()).ToArray()
Dim q = From u In Util.GetMems Join a In acc On a.ContactId Equals u.UserName
Where u.FirstName.ToLower.Contains(Search.FirstName.ToLower) And
u.LastName.ToLower.Contains(Search.LastName.ToLower) And
a.Name.ToLower.Contains(Search.Name.ToLower) And
a.ContactId.ToLower.Contains(Search.Email.ToLower) And
u.Phone.ToString.Contains(Search.Phone.ToLower) And
a.AccountId.ToString.Contains(Search.AccountId.ToLower)
Select New With {.FirstName = u.FirstName,
.LastName = u.LastName,
.Name = a.Name,
.Email = u.Email,
.Phone = u.Phone,
.AccountId = a.AccountId,
.City = a.City,
.State = (From s In myDB.States Where s.StateId = a.State Select s.StateAbbr).Single
}
'This is the only line i added between what I have working and this new section and it is where the error happens
Dim qq = From j In myDB.Jobs Where accList.Contains(j.AccountId) Select New With {j.JobId, j.Name, (From z In q Where z.AccountId = j.AccountId).Single}
Return DamnSer.Serialize(qq)
End Function
I decided to go a different route with it
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Function JobSearch(jSon As String) As String
Dim DamnSer As New JavaScriptSerializer
Dim Search As SearchString = DamnSer.Deserialize(Of SearchString)(jSon)
Dim myDB As New MyDbDataContext
Dim pro As New Mems(HttpContext.Current.User.Identity.Name)
Dim acc = From a In myDB.Accounts Where a.CompanyId = pro.Id Select a
Dim q = From u In Util.GetMems Join a In acc On a.ContactId Equals u.UserName
Where u.FirstName.ToLower.Contains(Search.FirstName.ToLower) And
u.LastName.ToLower.Contains(Search.LastName.ToLower) And
a.Name.ToLower.Contains(Search.Name.ToLower) And
a.ContactId.ToLower.Contains(Search.Email.ToLower) And
u.Phone.ToString.Contains(Search.Phone.ToLower) And
a.AccountId.ToString.Contains(Search.AccountId.ToLower)
Select New With {.FirstName = u.FirstName,
.LastName = u.LastName,
.Name = a.Name,
.Email = u.Email,
.Phone = u.Phone,
.AccountId = a.AccountId,
.City = a.City,
.State = (From s In myDB.States Where s.StateId = a.State Select s.StateAbbr).Single,
.zip = a.Zip,
.Locations = (From l In myDB.Locations Where l.AccountId = a.AccountId Select New With {l.AccountId, l.Address1, l.Address2, l.City, l.Comments, l.LocationId, .State = (From s In myDB.States Where s.StateId = l.State Select s.StateAbbr).Single, l.Zip,
.JobCount = (From j In myDB.Jobs Where j.LocationId = l.LocationId Select j).Count}
)
}
Return DamnSer.Serialize(q)
End Function

Linq members with profiles

I am trying to make a linq query to pull all users in the membership with their profiles. Here is what I have gotten already:
Dim Mbrs = Membership.GetAllUsers
Dim Pros = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)
Dim q = From mem In Mbrs Join pro In Pros On mem.UserName Equals
pro.UserName Select mem.email, mem.username, mem.islockedout,
pro.FirstName, pro.lastname, pro.city, pro.state, pro.zip, pro.type
If i take the profile stuff off the select, it will at least pull a list of members. What am I doind wrong??
Make a Class like this
Imports Microsoft.VisualBasic
Public Class Mems
Public Property FirstName As String = ""
Public Property LastName As String = ""
Public Property Address1 As String = ""
Public Property Address2 As String = ""
Public Property City As String = ""
Public Property State As System.Int32 = "0"
Public Property Zip As String = ""
Public Property Title As String = ""
Public Property Phone As System.Decimal = "0"
Public Property Id As System.Int32 = "0"
Public Property UserType As System.Int32 = "0"
Public Property SSN As System.Int32 = "0"
Public Property Email As String = ""
Public Property UserName As String = ""
Public Property IsLockedOut As Boolean = False
Private Loaded As Boolean = False
Public Sub New(usr As String)
GetMem(usr)
End Sub
Public Sub New()
End Sub
Public Sub Save()
If Not Loaded Then Throw New Exception("No User Loaded")
Dim mm = Membership.GetUser(UserName)
mm.Email = Email
Membership.UpdateUser(mm)
Dim p As ProfileCommon = New ProfileCommon
Dim pp = p.GetProfile(UserName)
pp.Address1 = Address1
pp.Address2 = Address2
pp.City = City
pp.FirstName = FirstName
pp.Id = Id
pp.LastName = LastName
pp.Phone = Phone
pp.SSN = SSN
pp.State = State
pp.Title = Title
pp.UserType = UserType
pp.Zip = Zip
pp.Save()
End Sub
Public Sub GetMem(usr As String)
'Try
If usr.Length = 0 Then
FirstName = "SYSTEM"
Else
Dim mm = Membership.GetUser(usr)
Email = mm.Email
IsLockedOut = mm.IsLockedOut
Dim p As ProfileCommon = New ProfileCommon
Dim pp = p.GetProfile(usr)
Address1 = pp.Address1
Address2 = pp.Address2
City = pp.City
FirstName = pp.FirstName
Id = pp.Id
LastName = pp.LastName
Phone = pp.Phone
SSN = pp.SSN
State = pp.State
Title = pp.Title
UserType = pp.UserType
Zip = pp.Zip
UserName = usr
Loaded = True
'Catch ex As Exception
' End Try
End If
End Sub
Public Function ChangeUsername(uTo As String) As Integer
If Loaded Then
Return ChangeUsername(UserName, uTo)
Else
Throw New Exception("No User Loaded")
End If
End Function
Public Function ChangeUsername(uFrom As String, uTo As String) As Integer
If Membership.FindUsersByName(uFrom).Count = 0 Then
Throw New Exception("Original UserName Don't Exists")
ElseIf Membership.FindUsersByName(uTo).Count = 1 Then
Throw New Exception("Target UserName Don't Exists")
Else
Dim myDb As New MyDbDataContext
Dim q = (From u In myDb.aspnet_Users Where u.UserName = uFrom And u.ApplicationId.Equals("72e4b882-e471-4f4b-b161-af0abbcb8487") Select u).Single
q.UserName = uTo
q.LoweredUserName = uTo.ToLower
Try
myDb.SubmitChanges()
Return 1
Catch ex As Exception
Return 0
End Try
End If
End Function
End Class
then you can call it from a functions like this
Public Shared Function GetMems() As List(Of Mems)
GetMems = New List(Of Mems)
Dim mm = Membership.GetAllUsers
For Each mbr As MembershipUser In mm
GetMems.Add(New Mems(mbr.UserName))
Next
Return GetMems
End Function

How to convert a "custom class" to an arraylist?nc

I have a class called student. Student class has public fields like first name, and last name. I am creating an instance of this class in my default page and assigning values to the fields. I have a function which takes two arraylists and return false if items in the arraylists do not match. In my default page, I have an arraylist which has items like first name and last name. I am passing this student object and the arraylist to compare and I get unable to cast Student to arraylist. Is there a way to work around this? Below is my code.
Dim valid as boolean = StudentsCompare(Student, arrlst)
Function StudentsCompare(ByVal arraylist1 as Arraylist, ByVal arrayList2 as ArrayList)
Dim Error As Boolean = True
For i As Integer = 0 To (arraylist1.Count - 1)
If Not arraylist1.Item(i).ToString = arrayList2.Item(i).ToString Then
Return Error = False
End If
Next
Return Error
End Function
You could do it this way; student.FirstName is an example you may need to change it with one of your class's real property.
Private valid As Boolean = StudentsCompare(List(Of Student), arrlst)
Private Function StudentsCompare(students As List(Of Student), list As ArrayList) As Boolean
Dim index As Integer = 0
For Each student As var In students
If student.FirstName = list(index).ToString() Then
Return False
End If
index += 1
Next
Return True
End Function
And If you have both parameter with the same object "Student" you could do it this way and check the multiple conditions:
Private list1 As List(Of Student)
Private list2 As List(Of Student)
Private valid As Boolean = StudentsCompare(list1, list2)
Private Function StudentsCompare(students1 As List(Of Student), students2 As List(Of Student)) As Boolean
For Each st1 As var In students1
For Each st2 As var In students2
If st1.FirstName = st2.FirstName AndAlso st1.LastName = st2.LastName AndAlso st1.Grade = st2.Grade Then
Return True
End If
Next
Next
Return False
End Function

Implement IComparer(Of DateTime) on list(of X) property

I want to sort all items in the list of the property reviews of the class CompanyTotalReview by the property reviewdatetime in descending order.
Here's what I have:
Dim allReviews As RestService.CompanyTotalReview = rst.getReviews(type, objectId, _lang)
Dim dc As New ReviewComparer
allReviews.reviews.Sort(dc)
Public Class CompanyTotalReview
Public Property totalreviews() As Integer
Get
Return _totalreviews
End Get
Set(value As Integer)
_totalreviews = value
End Set
End Property
Private _totalreviews As Integer
Public Property averagereview() As String
Get
Return _averagereview
End Get
Set(value As String)
_averagereview = value
End Set
End Property
Private _averagereview As String
Public Property reviews() As List(Of Review)
Get
Return m_reviews
End Get
Set(value As List(Of Review))
m_reviews = value
End Set
End Property
Private m_reviews As List(Of Review)
End Class
Public Class Review
Public Property overallscore() As Integer
Get
Return _overallscore
End Get
Set(value As Integer)
_overallscore = value
End Set
End Property
Private _overallscore As Integer
Public Property reviewtext() As String
Get
Return _reviewtext
End Get
Set(value As String)
_reviewtext = value
End Set
End Property
Private _reviewtext As String
Public Property reviewdatetime() As DateTime
Get
Return _reviewdatetime
End Get
Set(value As DateTime)
_reviewdatetime = value
End Set
End Property
Private _reviewdatetime As DateTime
End Class
updated class based on comments
Public Class ReviewComparer
Implements IComparer(Of RestService.Review)
Public Function Compare(xr As RestService.Review, yr As RestService.Review) As Integer Implements System.Collections.Generic.IComparer(Of RestService.Review).Compare
Dim x As DateTime = xr.reviewdatetime
Dim y As DateTime = yr.reviewdatetime
If x = Nothing Then
If y = Nothing Then
Return 0
Else
Return -1
End If
Else
If y = Nothing Then
Return 1
Else
Dim retval As Integer = x.CompareTo(y)
If retval <> 0 Then
Return retval
Else
Return x.CompareTo(y)
End If
End If
End If
End Function
End Class
You are sorting Review objects, not datetime objects. Use a review comparer like this.
Public Class ReviewComparer
Implements IComparer(Of Review)
Public Function Compare(xr As Review, yr As Review) As Integer Implements System.Collections.Generic.IComparer(Of Review).Compare
Dim x As DateTime = xr.reviewdatetime
Dim y As DateTime = yr.reviewdatetime
If x = Nothing Then
If y = Nothing Then
Return 0
Else
Return -1
End If
Else
If y = Nothing Then
Return 1
Else
Dim retval As Integer = x.CompareTo(y)
If retval <> 0 Then
Return retval
Else
Return x.CompareTo(y)
End If
End If
End If
End Function
End Class

EXTRACT session element in sorted list

I have two sortedlists one stores product information and the other one stores services how can I use Session.Contents Collection to extract data in these two sortedlist thank you
code
service sortedlist
Dim CartItemService As New CartItem
CartItemService.objService = objTempCartService
Me.AddToCart(CartItemService)
Private Sub AddToCart(ByVal CartItem As CartItem)
Dim CartService As SortedList = GetCart()
Dim ServiceID As Integer = objTempCartService.ServiceId
Dim Servicekey As String = "s" & CType(ServiceID, String)
If CartService.ContainsKey(Servicekey) Then
CartItem = CType(CartService(Servicekey), CartItem)
Else
CartService.Add(Servicekey, CartItem)
End If
End Sub
Private Function GetCart() As SortedList
If Session("CartS") Is Nothing Then
Session.Add("CartS", New SortedList)
End If
Return CType(Session("CartS"), SortedList)
End Function
product sortedlist
Dim CartItem As New CartItem
CartItem.objProduct = objTempCart
Me.AddToCart(CartItem)
Private Sub AddToCart(ByVal CartItem As CartItem)
Dim Cart As SortedList = GetCart()
Dim sProductID As Integer = objTempCart.ProductId
Dim k As String = "P" & CType(sProductID, String)
If Cart.ContainsKey(k) Then
CartItem = CType(Cart(k), CartItem)
CartItem.objProduct.OrderQty = CartItem.objProduct.OrderQty + 1
CartItem.objProduct.Total = CartItem.objProduct.OrderQty * CartItem.objProduct.ProductPrice
Else
Cart.Add(k, CartItem)
CartItem.objProduct.OrderQty = 1
CartItem.objProduct.Total = CartItem.objProduct.OrderQty * CartItem.objProduct.ProductPrice
End If
End Sub
Private Function GetCart() As SortedList
If Session("Cart") Is Nothing Then
Session.Add("Cart", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function

Resources