Linq members with profiles - asp.net

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

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

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

convert existing code to asynchronous workings

I have existing code in VB in which I need to process all records that are in the list in one go, and await for their responses. When they respond, add them to the data table. The code works. I just need to convert it to run asynchronously.
Here is my code:
Imports System.Net
Imports System.IO
Public Class Form1
Dim _Datatable As New DataTable
Private Sub btnProcess_Click(sender As System.Object, e As System.EventArgs) Handles btnProcess.Click
prgProgress.Value = 0
prgProgress.Maximum = lstUrls.Items.Count
For Each _ProductEntry As String In lstUrls.Items
Try
Dim _Webclient As New WebClient
'_Webclient.Proxy = _ProxyClient
Dim _DataStream As Stream = _Webclient.OpenRead(New Uri(_ProductEntry))
Dim _DataRead As New StreamReader(_DataStream)
Dim _HtmlContent As String = _DataRead.ReadToEnd
Dim _HtmlDocument As mshtml.IHTMLDocument2 = New mshtml.HTMLDocument
_HtmlDocument.write(_HtmlContent)
Dim _ProductName As mshtml.IHTMLHeaderElement = _HtmlDocument.getElementById("product-header")
_DataStream.Close()
_DataRead.Close()
Call CheckTable("Name")
Call CheckTable("URL")
Call CheckTable("Image")
Call CheckTable("Price")
Dim _Price As String = String.Empty
Dim _SpanElements As mshtml.IHTMLElementCollection = _HtmlDocument.getElementsByTagName("span")
For Each _SpanElement As mshtml.IHTMLSpanElement In _SpanElements
If _SpanElement.classname = "regular-price" Then
_Price = Replace(Replace(_SpanElement.innertext, "£", ""), "Incl. VAT", "")
End If
Next
Dim _ImageLocation As String = String.Empty
For Each _Paragraph As mshtml.IHTMLElement In _HtmlDocument.getElementsByTagName("image")
If _Paragraph.id = "product-image-main" Then
Dim _Image As mshtml.IHTMLImgElement = CType(_Paragraph, mshtml.IHTMLImgElement)
_ImageLocation = _Image.src
Exit For
End If
Next
Dim tableElements As mshtml.IHTMLElementCollection
tableElements = _HtmlDocument.getElementsByTagName("Table")
Dim oTableTest As mshtml.IHTMLTable2 = tableElements.item(1)
'BUILD HEADERS
For Each _ColumnHeader As mshtml.IHTMLTableRow In oTableTest.rows
CheckTable(CType(_ColumnHeader.cells(0), mshtml.IHTMLElement).innerText)
Next
Dim _DataRow As DataRow = _DataTable.NewRow
_DataRow.Item("Name") = CType(_ProductName, mshtml.IHTMLElement).innerText
_DataRow.Item("URL") = _ProductEntry
_DataRow.Item("Price") = _Price
_DataRow.Item("Image") = _ImageLocation
For Each _RowData As mshtml.IHTMLTableRow In oTableTest.rows
Dim _Header As mshtml.IHTMLElement = _RowData.cells(0)
Dim _Value As mshtml.IHTMLElement = _RowData.cells(1)
_DataRow.Item(_Header.innerText) = _Value.innerText
Next
Dim _Elements As mshtml.IHTMLElementCollection = _HtmlDocument.all
For Each _Element As mshtml.IHTMLElement In _Elements
If _Element.className = "product-description product-documents" Then
For Each _ProductLink As mshtml.IHTMLElement In _Element.all
If _ProductLink.tagName = "A" Then
CheckTable(_ProductLink.innerText)
_DataRow(_ProductLink.innerText) = Replace(CType(_ProductLink, mshtml.IHTMLAnchorElement).href, "about:", "http://www.tapoutlet.co.uk")
End If
Next
End If
Next
_DataTable.Rows.Add(_DataRow)
_DataTable.AcceptChanges()
dgvScrapedData.DataSource = _Datatable
dgvScrapedData.Refresh()
Catch ex As Exception
Console.WriteLine("Error getting webpage-" & _ProductEntry)
Console.WriteLine(ex.Message.ToString)
End Try
Next
End Sub
Private Function CheckTable(ByVal ColumnName As String) As Boolean
If _DataTable.Columns.Contains(ColumnName) Then
Return True
Else
_DataTable.Columns.Add(ColumnName)
Return False
End If
End Function
End Class

linq to entity framework custom collection class that inherits list(Of T)

OK, I'm not quite sure how to ask this, but basically I want to create a custom collection class that allows me to have properties on a generic list (Of T) such as:
Public ReadOnly Property TotalCalories() As Decimal
Get
Dim decTotal As Decimal = 0D
For Each thisFoodDiaryItem As FoodDiaryItem In Me
Dim thisNutValue As NutritionalData = (From nd In thisFoodDiaryItem.Food.NutritionalDatas Where nd.NutritionalDefinitionID = 208).FirstOrDefault
If thisFoodDiaryItem.Food.FoodWeights.Count > 0 Then
Dim decWeight As Decimal = thisFoodDiaryItem.Food.FoodWeights(0).WeightInGrams
If Not thisNutValue Is Nothing Then
Dim decCalories As Decimal = Math.Round((thisNutValue.Value * (decWeight / 100)) * thisFoodDiaryItem.Amount)
decTotal += decCalories
End If
End If
Next
Return decTotal
End Get
End Property
Public ReadOnly Property TotalSugars() As Decimal
Get
Dim decTotal As Decimal = 0D
For Each thisFoodDiaryItem As FoodDiaryItem In Me
Dim thisNutValue As NutritionalData = (From nd In thisFoodDiaryItem.Food.NutritionalDatas Where nd.NutritionalDefinitionID = 269).FirstOrDefault
If thisFoodDiaryItem.Food.FoodWeights.Count > 0 Then
Dim decWeight As Decimal = thisFoodDiaryItem.Food.FoodWeights(0).WeightInGrams
If Not thisNutValue Is Nothing Then
Dim decCalories As Decimal = Math.Round((thisNutValue.Value * (decWeight / 100)) * thisFoodDiaryItem.Amount)
decTotal += decCalories
End If
End If
Next
Return decTotal
End Get
End Property
I want this class to be used when calling entity framework queries:
Protected Sub BindFoodDiaryItems()
CurrentFoodDiaryItems = New FoodDiaryItemCollection
CurrentFoodDiaryItems = (From fdi In db.FoodDiaryItems Where fdi.PersonID = CurrentSiteUser.PersonID And fdi.EntryDate = CurrentDiaryDate).ToList
If AllMeals Is Nothing Then
AllMeals = (From m In db.Meals).ToList
End If
lvMealsA.DataSource = AllMeals
lvMealsA.DataBind()
lblTotalCalories.Text = CurrentFoodDiaryItems.TotalCalories.ToString
lblTotalSugars.Text = CurrentFoodDiaryItems.TotalSugars.ToString
lblTotalFats.Text = CurrentFoodDiaryItems.TotalFat.ToString
lblTotalProtein.Text = CurrentFoodDiaryItems.TotalProtein.ToString
lblTotalCarbs.Text = CurrentFoodDiaryItems.TotalCarbs.ToString
End Sub
I'm assuming it would go something like this:
Partial Public Class FoodDiaryItemCollection
Inherits List(Of FoodDiaryItem)
Sub New()
End Sub
End Class
Error I'm getting:
Unable to cast object of type 'System.Collections.Generic.List`1[NutritionBridgeModel.FoodDiaryItem]' to type 'NutritionBridgeModel.FoodDiaryItemCollection'.
TIA
The .Net Framework exposes a lot of awesome extension methods, like Sum, Average, etc...
http://msdn.microsoft.com/en-us/library/bb341635
Example:
class Program
{
static void Main(string[] args)
{
var sweetList = new List<int> { 4, 123, 5, 23, 42 };
Console.WriteLine("Average: {0}", sweetList.Average());
Console.WriteLine("Sum: {0}", sweetList.Sum());
var listOfCoolObjects = new List<CoolObject>();
listOfCoolObjects.Add(new CoolObject { Name = "1434", NeatValue = 42 });
listOfCoolObjects.Add(new CoolObject { Name = "asdf", NeatValue = 5 });
listOfCoolObjects.Add(new CoolObject { Name = "fgsdfg", NeatValue = 99 });
listOfCoolObjects.Add(new CoolObject { Name = "qwerty", NeatValue = 1345 });
listOfCoolObjects.Add(new CoolObject { Name = "casc", NeatValue = 111 });
Console.WriteLine("Average: {0}", listOfCoolObjects.Average(x => x.NeatValue));
Console.WriteLine("Sum: {0}", listOfCoolObjects.Sum(x => x.NeatValue));
}
}
class CoolObject
{
public string Name { get; set; }
public int NeatValue { get; set; }
}
In your code, you could do something like this:
var sum = (From fdi In db.FoodDiaryItems Where fdi.PersonID = CurrentSiteUser.PersonID And fdi.EntryDate = CurrentDiaryDate).Sum(fdi => fdi.SomeValueYouWantToSum)
I know you're coding in VB, but I don't know VB at all, so excuse any syntax errors in that last code chunk.

How to convert ListItemCollection to List(of object)

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

Resources