Indexed Property Error: Must be Qualified and Arguments Explicitly Supplied - asp.net
While running the code I've included below I receive the error
"EntityCommandExecutionException was unhandled by user code.
I'm then told to look at the inner exception for details...and there I see under Data:
"In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user."
And under Inner Exception --> Message:
"A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The handle is invalid.)"
The code Visual Studio thinks is at fault is:
Dim qpeople = (From p In dbContext2.PEOPLE _
Where p.PEOPLE_ID = ID _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
The larger code context is:
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim semester As String = ddlwhSemester.SelectedValue
Dim year As String = txtwhYear.Text
Dim exists As String = "N"
Dim pcsemester As String = ddlSemester.SelectedItem.Text
Dim pcyear As String = ddlYear.SelectedItem.Text
Using dbContext As pbu_housingEntities = New pbu_housingEntities
' Get the list of residents in webHousing.
Dim qresidents = (From p In dbContext.Residents _
Where p.semester = semester _
Where p.year = year _
Select p.people_code_id)
Using dbContext2 As Campus6Entities = New Campus6Entities
' Get the list of students in PowerCampus.
Dim qstudents = (From p In dbContext2.RESIDENCies _
Join a In dbContext2.ACADEMICs _
On a.PEOPLE_CODE_ID Equals p.PEOPLE_CODE_ID _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Where a.ACADEMIC_TERM = pcsemester _
Where a.ACADEMIC_YEAR = pcyear _
Where a.PROGRAM = "UND" _
Where (a.CLASS_LEVEL = "FR" _
Or a.CLASS_LEVEL = "FRNR" _
Or a.CLASS_LEVEL = "FRST" _
Or a.CLASS_LEVEL = "SO" _
Or a.CLASS_LEVEL = "JR" _
Or a.CLASS_LEVEL = "SR" _
Or a.CLASS_LEVEL = "SR5" _
Or a.CLASS_LEVEL = "Tran") _
Select p.PEOPLE_ID).Distinct
For Each row In qstudents
exists = "N"
For Each res In qresidents
If row.ToString = res.ToString Then
exists = "Y"
End If
Next
If exists = "Y" Then
' Skip adding.
Else
' Add a row.
' Get the ID
Dim ID As String = row
' Get info from PowerCampus
Dim qpeople = (From p In dbContext2.PEOPLE _
Where p.PEOPLE_ID = ID _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim people_code_id As String = qpeople.PEOPLE_CODE_ID
Dim qacademic = (From p In dbContext2.ACADEMICs _
Where p.PEOPLE_CODE_ID = people_code_id _
Where p.ACADEMIC_TERM = pcsemester _
Where p.ACADEMIC_YEAR = pcyear _
Order By p.CREATE_DATE Descending _
Select p.CLASS_LEVEL).FirstOrDefault
Dim qaddress = (From p In dbContext2.ADDRESSes _
Where p.PEOPLE_ORG_CODE_ID = people_code_id _
Where p.ADDRESS_TYPE = "Perm" _
Order By p.CREATE_DATE Descending _
Select p).FirstOrDefault
Dim qdemographics = (From p In dbContext2.DEMOGRAPHICS _
Where p.PEOPLE_CODE_ID = people_code_id _
Order By p.CREATE_DATE Descending _
Select p.GENDER).FirstOrDefault
' Create the new occupant.
Dim newres As New Resident
newres.people_code_id = ID
newres.person_name = qpeople.FIRST_NAME + " " + qpeople.MIDDLE_NAME + " " + qpeople.LAST_NAME
newres.first_name = qpeople.FIRST_NAME
newres.last_name = qpeople.LAST_NAME
newres.class_level = qacademic
newres.gender = qdemographics
newres.semester = semester
newres.year = year
newres.email = qaddress.EMAIL_ADDRESS
newres.create_date = Date.Now
dbContext.Residents.AddObject(newres)
dbContext.SaveChanges()
End If
Next
End Using
End Using
End Sub
Check your db and make sure the primary key is there. I had a similar issue and found that the primary key was not defined. Just a thought, might not be the problem but worth a quick check.
I didn't notice this before but you are setting your ID like this:
Dim ID As String = row
Try converting the ID to a Int before the linq query.
Related
How to scrape all possible results from a search bar of a website
This is my first web scraping task. I have been tasked with scraping a website It is a site that contains the names of lawyers in Denmark. My difficulty is that I can only retrieve names based on the particular name query i put in the search bar. Is there an online web tool I can use to scrape all the names that the website contains? I have used tools like Import.io with no success so far. I am super confused on how all of this works.
Please scroll down to UPDATE 2 The website enforces you to enter at least one search parameter, so you may loop through all items for Arbejdsområde list, making request for each of them. Here is the example, showing how that could be done in Excel VBA (open VBE, create standard module, paste the code and run Test()): Option Explicit Sub Test() Dim sResponse As String Dim oItems As Object Dim vItem Dim aData Dim sContent As String Dim lPage As Long Dim i As Long Dim j As Long ' Retrieve search page HTML content XmlHttpRequest "GET", "http://www.advokatnoeglen.dk/", "", "", "", sResponse ' Extract work areas items ExtractOptions sResponse, "ctl00$ContentPlaceHolder$Search$AreaSelect", oItems oItems.Remove oItems.Keys()(0) sContent = "" ' Process each work area item For Each vItem In oItems.Items() Debug.Print "Item [" & vItem & "]" lPage = 0 ' Process each results page Do Debug.Print vbTab & "Page [" & lPage & "]" ' Retrieve result page HTML content XmlHttpRequest "GET", "http://www.advokatnoeglen.dk/sog.aspx?s=1&t=0&a=" & vItem & "&p=" & lPage, "", "", "", sResponse ' Extract result table ParseResponse _ "<table\b[^>]*?id=""ctl00_ContentPlaceHolder_Grid""[^>]*>([\s\S]*?)</table>", _ sResponse, _ aData, _ False ' Store parsed table sContent = sContent & aData(0) Debug.Print vbTab & "Parsed " & Len(sContent) lPage = lPage + 1 DoEvents Loop Until InStr(sResponse, "<a class=""next""") = 0 Next ' Extract data from the whole content ParseResponse _ "<tr.*?onclick=""location.href='([^']*)'"">\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "</tr>", _ sContent, _ aData, _ False ' Rebuild nested arrays to 2d array for output aData = Denestify(aData) ' Decode HTML For i = 1 To UBound(aData, 1) For j = 2 To 4 aData(i, j) = GetInnerText((aData(i, j))) Next Next ' Output With ThisWorkbook.Sheets(1) .Cells.Delete Output2DArray .Cells(1, 1), aData .Columns.AutoFit .Rows.AutoFit End With MsgBox "Completed" End Sub Sub XmlHttpRequest(sMethod, sUrl, aSetHeaders, sFormData, sRespHeaders, sRespText) Dim aHeader 'With CreateObject("MSXML2.ServerXMLHTTP") '.SetOption 2, 13056 ' SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS With CreateObject("MSXML2.XMLHTTP") .Open sMethod, sUrl, False ' , "u051772", "fy17janr" If IsArray(aSetHeaders) Then For Each aHeader In aSetHeaders .SetRequestHeader aHeader(0), aHeader(1) Next End If .Send (sFormData) sRespHeaders = .GetAllResponseHeaders sRespText = .ResponseText End With End Sub Sub ExtractOptions(sContent As String, ByVal sName As String, oOptions As Object) Dim aTmp0 Dim vItem ' Escape RegEx special characters For Each vItem In Array("\", "*", "+", "?", "^", "$", ".", "[", "]", "{", "}", "(", ")", "|", "/") sName = Replace(sName, vItem, "\" & vItem) Next ' Extract the whole <select> for parameter ParseResponse "<select[^>]* name=""?" & sName & """?[^>]*>[^<]*((?:<option[^>]*>[^<]*</option>[^<]*)+)[^<]*</[^>]*>", sContent, aTmp0, False ' Extract each parameter <option> ParseResponse "<option[^>]*value=(""[^""]*""|[^\s>]*)[^>]*>([^<]*)</option>", (aTmp0(0)), aTmp0, False ' Put each parameter and value into dictionary Set oOptions = CreateObject("Scripting.Dictionary") For Each vItem In aTmp0 oOptions(GetInnerText((vItem(1)))) = GetInnerText(Replace(vItem(0), """", "")) Next End Sub Sub ParseResponse(sPattern, sResponse, aData, Optional bAppend As Boolean = True, Optional bGlobal = True, Optional bMultiLine = True, Optional bIgnoreCase = True) Dim oMatch Dim aTmp0() Dim sSubMatch If Not (IsArray(aData) And bAppend) Then aData = Array() With CreateObject("VBScript.RegExp") .Global = bGlobal .MultiLine = bMultiLine .IgnoreCase = bIgnoreCase .Pattern = sPattern For Each oMatch In .Execute(sResponse) If oMatch.SubMatches.Count = 1 Then PushItem aData, oMatch.SubMatches(0) Else aTmp0 = Array() For Each sSubMatch In oMatch.SubMatches PushItem aTmp0, sSubMatch Next PushItem aData, aTmp0 End If Next End With End Sub Sub PushItem(aData, vItem, Optional bAppend As Boolean = True) If Not (IsArray(aData) And bAppend) Then aData = Array() ReDim Preserve aData(UBound(aData) + 1) aData(UBound(aData)) = vItem End Sub Function GetInnerText(sText As String) As String Static oHtmlfile As Object Static oDiv As Object If oHtmlfile Is Nothing Then Set oHtmlfile = CreateObject("htmlfile") oHtmlfile.Open Set oDiv = oHtmlfile.createElement("div") End If oDiv.innerHTML = sText GetInnerText = oDiv.innerText End Function Function Denestify(aRows) Dim aData() Dim aItems() Dim i As Long Dim j As Long If UBound(aRows) = -1 Then Exit Function ReDim aData(1 To UBound(aRows) + 1, 1 To 1) For j = 0 To UBound(aRows) If IsArray(aRows(j)) Then aItems = aRows(j) For i = 0 To UBound(aItems) If i + 1 > UBound(aData, 2) Then ReDim Preserve aData(1 To UBound(aRows) + 1, 1 To i + 1) aData(j + 1, i + 1) = aItems(i) Next Else aData(j + 1, 1) = aRows(j) End If Next Denestify = aData End Function Sub Output2DArray(oDstRng As Range, aCells As Variant) With oDstRng .Parent.Select With .Resize( _ UBound(aCells, 1) - LBound(aCells, 1) + 1, _ UBound(aCells, 2) - LBound(aCells, 2) + 1) .NumberFormat = "#" .Value = aCells End With End With End Sub It takes few minutes to retrieve all data for the first time (after that when launched again all requests are loaded from the cache that makes process significantly faster, to get a latest data from the server you need to clean up the cache in IE settings). The output for me is as follows: Generally RegEx's aren't recommended for HTML parsing, so there is disclaimer. Data being processed in this case is quite simple that is why it is parsed with RegEx. About RegEx: introduction (especially syntax), introduction JS, VB flavor. BTW there are another answers using the similar approach: 1, 2, 3 and 4. UPDATE The above suggested scraping is based on parsing search results filtered by Arbejdsområde parameter, and as it turned out, actually returned results are inaccurate. Those lawyers, which have multiply Arbejdsområder are present multiply times in results, and which have empty Arbejdsområder are not in results at all. Another parameter instead of Arbejdsområde, that can be used for such scraping is Retskreds. All lawyers records contain address, and only single address, so results are full and don't contain duplicates. Note, one lawyer can relate to several offices, so that will be several records in results. There is the code that allows to scrape detailed info for each entry within loop: Option Explicit Sub Test() Dim sResponse As String Dim oItems As Object Dim vKey Dim sItem As String Dim aTmp Dim aData Dim lPage As Long Dim i As Long Dim j As Long ' Retrieve search page HTML content XmlHttpRequest "GET", "http://www.advokatnoeglen.dk/", "", "", "", sResponse ' Extract Retskreds items ExtractOptions sResponse, "ctl00$ContentPlaceHolder$Search$CourtSelect", oItems oItems.Remove oItems.Keys()(0) i = 0 ' Process each Retskreds item For Each vKey In oItems sItem = oItems(vKey) Debug.Print "Area " & sItem & " " & vKey lPage = 0 ' Process each results page Do Debug.Print vbTab & "Page " & lPage ' Retrieve results page XmlHttpRequest "GET", "http://www.advokatnoeglen.dk/sog.aspx?s=1&t=0&c=" & sItem & "&p=" & lPage, "", "", "", sResponse ' Extract table ParseResponse _ "<table\b[^>]*?id=""ctl00_ContentPlaceHolder_Grid""[^>]*>([\s\S]*?)</table>", _ sResponse, _ aTmp, _ False ' Extract data from the table ParseResponse _ "<tr.*?onclick=""location.href='([^']*)'"">\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "</tr>", _ aTmp(0), _ aData, _ True ' Add Retskreds name For i = i To UBound(aData) aTmp = aData(i) PushItem aTmp, vKey aData(i) = aTmp Next Debug.Print vbTab & "Parsed " & UBound(aData) lPage = lPage + 1 DoEvents Loop Until InStr(sResponse, "<a class=""next""") = 0 Next ' Retrieve detailed info for each entry For i = 0 To UBound(aData) aTmp = aData(i) ' Retrieve details page aTmp(0) = "http://www.advokatnoeglen.dk" & aTmp(0) ' Extract details XmlHttpRequest "GET", aTmp(0), "", "", "", sResponse ParseResponse _ DecodeUriComponent( _ "Arbejdsomr%C3%A5der\: [\s\S]*?</h2>[\s\S]*?" & _ "Beskikkelses%C3%A5r\: ([^<]*)[\s\S]*?" & _ "F%C3%B8dsels%C3%A5r\: ([^<]*)[\s\S]*?" & _ "M%C3%B8deret for landsret\: ([^<]*)[\s\S]*?" & _ "M%C3%B8deret for h%C3%B8jesteret\: ([^<]*)[\s\S]*?" & _ "E-mail\: [\s\S]*?href='\/email\.aspx\?e\=(.*?)'[\s\S]*?" & _ "Mobiltlf\.\: ([\d\(\)\-+ ]*?)\s*<"), _ sResponse, _ aTmp, _ True, _ False aTmp(9) = StrReverse(aTmp(9)) aData(i) = aTmp Debug.Print vbTab & "Details " & i DoEvents Next ' Rebuild nested arrays to 2d array for output aData = Denestify(aData) ' Decode HTML For i = 1 To UBound(aData, 1) For j = 2 To 4 aData(i, j) = Trim(Replace(GetInnerText((aData(i, j))), vbCrLf, "")) Next Next ' Output With ThisWorkbook.Sheets(1) .Cells.Delete OutputArray .Cells(1, 1), _ Array("URL", _ "Navn", _ "Firma", _ DecodeUriComponent("Arbejdsomr%C3%A5der"), _ DecodeUriComponent("Retskreds"), _ DecodeUriComponent("Beskikkelses%C3%A5r"), _ DecodeUriComponent("F%C3%B8dsels%C3%A5r"), _ DecodeUriComponent("M%C3%B8deret for landsret"), _ DecodeUriComponent("M%C3%B8deret for h%C3%B8jesteret"), _ "E-mail", _ "Mobiltlf." _ ) Output2DArray .Cells(2, 1), aData .Columns.AutoFit .Rows.AutoFit End With MsgBox "Completed" End Sub Sub XmlHttpRequest(sMethod, sUrl, aSetHeaders, sFormData, sRespHeaders, sRespText) Dim aHeader 'With CreateObject("MSXML2.ServerXMLHTTP") '.SetOption 2, 13056 ' SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS With CreateObject("MSXML2.XMLHTTP") .Open sMethod, sUrl, False If IsArray(aSetHeaders) Then For Each aHeader In aSetHeaders .SetRequestHeader aHeader(0), aHeader(1) Next End If .Send (sFormData) sRespHeaders = .GetAllResponseHeaders sRespText = .ResponseText End With End Sub Sub ExtractOptions(sContent As String, ByVal sName As String, oOptions As Object) Dim aTmp0 Dim vItem ' Escape RegEx special characters For Each vItem In Array("\", "*", "+", "?", "^", "$", ".", "[", "]", "{", "}", "(", ")", "|", "/") sName = Replace(sName, vItem, "\" & vItem) Next ' Extract the whole <select> for parameter ParseResponse "<select[^>]* name=""?" & sName & """?[^>]*>[^<]*((?:<option[^>]*>[^<]*</option>[^<]*)+)[^<]*</[^>]*>", sContent, aTmp0, False ' Extract each parameter <option> ParseResponse "<option[^>]*value=(""[^""]*""|[^\s>]*)[^>]*>([^<]*)</option>", (aTmp0(0)), aTmp0, False ' Put each parameter and value into dictionary Set oOptions = CreateObject("Scripting.Dictionary") For Each vItem In aTmp0 oOptions(GetInnerText((vItem(1)))) = GetInnerText(Replace(vItem(0), """", "")) Next End Sub Sub ParseResponse(sPattern, sResponse, aData, Optional bAppend As Boolean = True, Optional bNestSubMatches = True, Optional bGlobal = True, Optional bMultiLine = True, Optional bIgnoreCase = True) Dim oMatch Dim aTmp0() Dim sSubMatch If Not (IsArray(aData) And bAppend) Then aData = Array() With CreateObject("VBScript.RegExp") .Global = bGlobal .MultiLine = bMultiLine .IgnoreCase = bIgnoreCase .Pattern = sPattern For Each oMatch In .Execute(sResponse) If oMatch.SubMatches.Count = 1 Then PushItem aData, oMatch.SubMatches(0) Else If bNestSubMatches Then aTmp0 = Array() For Each sSubMatch In oMatch.SubMatches PushItem aTmp0, sSubMatch Next PushItem aData, aTmp0 Else For Each sSubMatch In oMatch.SubMatches PushItem aData, sSubMatch Next End If End If Next End With End Sub Sub PushItem(aData, vItem, Optional bAppend As Boolean = True) If Not (IsArray(aData) And bAppend) Then aData = Array() ReDim Preserve aData(UBound(aData) + 1) aData(UBound(aData)) = vItem End Sub Function DecodeUriComponent(sEncoded As String) As String Static objHtmlfile As Object If objHtmlfile Is Nothing Then Set objHtmlfile = CreateObject("htmlfile") objHtmlfile.parentWindow.execScript "function decode(s) {return decodeURIComponent(s)}", "jscript" End If DecodeUriComponent = objHtmlfile.parentWindow.decode(sEncoded) End Function Function GetInnerText(sText As String) As String Static oHtmlfile As Object Static oDiv As Object If oHtmlfile Is Nothing Then Set oHtmlfile = CreateObject("htmlfile") oHtmlfile.Open Set oDiv = oHtmlfile.createElement("div") End If oDiv.innerHTML = sText GetInnerText = oDiv.innerText End Function Function Denestify(aRows) Dim aData() Dim aItems() Dim i As Long Dim j As Long If UBound(aRows) = -1 Then Exit Function ReDim aData(1 To UBound(aRows) + 1, 1 To 1) For j = 0 To UBound(aRows) If IsArray(aRows(j)) Then aItems = aRows(j) For i = 0 To UBound(aItems) If i + 1 > UBound(aData, 2) Then ReDim Preserve aData(1 To UBound(aRows) + 1, 1 To i + 1) aData(j + 1, i + 1) = aItems(i) Next Else aData(j + 1, 1) = aRows(j) End If Next Denestify = aData End Function Sub OutputArray(oDstRng As Range, aCells As Variant, Optional sFormat As String = "#") With oDstRng .Parent.Select With .Resize(1, UBound(aCells) - LBound(aCells) + 1) .NumberFormat = sFormat .Value = aCells End With End With End Sub Sub Output2DArray(oDstRng As Range, aCells As Variant, Optional sFormat As String = "#") With oDstRng .Parent.Select With .Resize( _ UBound(aCells, 1) - LBound(aCells, 1) + 1, _ UBound(aCells, 2) - LBound(aCells, 2) + 1) .NumberFormat = sFormat .Value = aCells End With End With End Sub There are 4896 entries total for 4689 lawyers: UPDATE 2 Seems to get complete list you may just make search with set (space) as Firma parameter: http://www.advokatnoeglen.dk/sog.aspx?s=1&t=0&firm=%20, there are 6511 entries at the moment. The Sub Test() code for parse that results should be changed then as shown below: Option Explicit Sub Test() Dim sResponse As String Dim aTmp Dim aData Dim lPage As Long Dim i As Long Dim j As Long lPage = 0 ' Process each results page Do Debug.Print vbTab & "Page " & lPage ' Retrieve results page XmlHttpRequest "GET", "http://www.advokatnoeglen.dk/sog.aspx?s=1&t=0&firm=%20&p=" & lPage, "", "", "", sResponse ' Extract table ParseResponse _ "<table\b[^>]*?id=""ContentPlaceHolder_Grid""[^>]*>([\s\S]*?)</table>", _ sResponse, _ aTmp, _ False ' Extract data from the table ParseResponse _ "<tr.*?onclick=""location.href='(.*?)'"">\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "<td[^>]*>\s*([\s\S]*?)\s*</td>\s*" & _ "</tr>", _ aTmp(0), _ aData, _ True Debug.Print vbTab & "Parsed " & (UBound(aData) + 1) lPage = lPage + 1 DoEvents Loop Until InStr(sResponse, "<a class=""next""") = 0 ' Retrieve detailed info for each entry For i = 0 To UBound(aData) aTmp = aData(i) ' Retrieve details page aTmp(0) = "http://www.advokatnoeglen.dk" & aTmp(0) ' Extract details Do XmlHttpRequest "GET", aTmp(0), "", "", "", sResponse If InStr(sResponse, "<title>Runtime Error</title>") = 0 Then Exit Do DoEvents Loop ParseResponse _ DecodeUriComponent( _ "Arbejdsomr%C3%A5der\: [\s\S]*?</h2>[\s\S]*?" & _ "Beskikkelses%C3%A5r\: ([^<]*)[\s\S]*?" & _ "(:?F%C3%B8dsels%C3%A5r\: ([^<]*)[\s\S]*?)?" & _ "M%C3%B8deret for landsret\: ([^<]*)[\s\S]*?" & _ "M%C3%B8deret for h%C3%B8jesteret\: ([^<]*)[\s\S]*?" & _ "(:?E-mail [\s\S]*?href='\/email\.aspx\?e\=(.*?)'[\s\S]*?)?" & _ "Mobiltlf\.\: ([\d\(\)\-+ ]*?)\s*<"), _ sResponse, _ aTmp, _ True, _ False aTmp(8) = StrReverse(aTmp(8)) aData(i) = aTmp Debug.Print vbTab & "Details " & i DoEvents Next ' Rebuild nested arrays to 2d array for output aData = Denestify(aData) ' Decode HTML For i = 1 To UBound(aData, 1) For j = 2 To 4 aData(i, j) = Trim(Replace(GetInnerText((aData(i, j))), vbCrLf, "")) Next Next ' Output With ThisWorkbook.Sheets(1) .Cells.Delete OutputArray .Cells(1, 1), _ Array("URL", _ "Navn", _ "Firma", _ DecodeUriComponent("Arbejdsomr%C3%A5der"), _ DecodeUriComponent("Beskikkelses%C3%A5r"), _ DecodeUriComponent("F%C3%B8dsels%C3%A5r"), _ DecodeUriComponent("M%C3%B8deret for landsret"), _ DecodeUriComponent("M%C3%B8deret for h%C3%B8jesteret"), _ "E-mail", _ "Mobiltlf." _ ) Output2DArray .Cells(2, 1), aData .Columns.AutoFit .Rows.AutoFit End With MsgBox "Completed" End Sub
LINQ function to return list but compiler says function doesn't return a value on all code path
Here is my code <WebMethod()> _ Public Function getlocationsbypro(searchtype As String, crime As String, proid As String, startdate As String, enddate As String, starttime As String, endtime As String) As List(Of crimelocation) If searchtype = "withdatetime" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime And (locations.DATE_COMTD >= Convert.ToDateTime(startdate) And locations.DATE_COMTD <= Convert.ToDateTime(enddate)) _ And (locations.gettimecom >= starttime And locations.gettimecom <= endtime) _ Select locations Return giveloc.ToList ElseIf searchtype = "withdate" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime And (locations.DATE_COMTD >= Convert.ToDateTime(startdate) And locations.DATE_COMTD <= Convert.ToDateTime(enddate)) _ Select locations Return giveloc.ToList ElseIf searchtype = "without" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime _ Select locations Return giveloc.ToList End If End Function but when I compile it says that the function doesn't return a value on all code path despite having a return statement on all of my if statement am I missing something and also I notice when there if no elseif statement just the usual if else end it doesn't give me an error stated above.
All code paths don't return a value. If searchtype = "withdatetime" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime And (locations.DATE_COMTD >= Convert.ToDateTime(startdate) And locations.DATE_COMTD <= Convert.ToDateTime(enddate)) _ And (locations.gettimecom >= starttime And locations.gettimecom <= endtime) _ Select locations Return giveloc.ToList ElseIf searchtype = "withdate" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime And (locations.DATE_COMTD >= Convert.ToDateTime(startdate) And locations.DATE_COMTD <= Convert.ToDateTime(enddate)) _ Select locations Return giveloc.ToList ElseIf searchtype = "without" Then Dim locs As New crimemsapslocationDataContext Dim giveloc = From locations In locs.crimelocations _ Where locations.INCIDENTTYPE = crime _ Select locations Return giveloc.ToList End If // if none of the if-else conditions are met your code goes straight to here and there is not return statement Return null; // this fixes it. You could also just put an else at the end of the if-else which would probably be better. I didn't notice the ElseIf's at fist cause I don't write that VB stuff.
You need to have another Return statement after End If. Otherwise, your code will not return anything if none of the If or ElseIf conditions are satisfied.
Object's Key Does Not Match the Corresponding Property in the ObjectContext
When I execute this subroutine it throws an error, "The value of a property that is part of an object's key does not match the corresponding property value stored in the ObjectContext. This can occur if properties that are part of the key return inncosistent or incorrect values or if DetectChanges is not called after changes are made to a property that is part of the key." Here is the code and below it I've explained briefly what the code does. Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click Dim semester As String = ddlwhSemester.SelectedValue Dim year As String = txtwhYear.Text Dim exists As String = "N" Dim pcsemester As String = ddlSemester.SelectedItem.Text Dim pcyear As String = ddlYear.SelectedItem.Text Using dbContext As pbu_housingEntities = New pbu_housingEntities ' Get the list of residents in webHousing. Dim qresidents = (From p In dbContext.Residents _ Where p.semester = semester _ Where p.year = year _ Select p.people_code_id) Using dbContext2 As Campus6Entities = New Campus6Entities ' Get the list of students in PowerCampus. Dim qstudents = (From p In dbContext2.RESIDENCies _ Where p.ACADEMIC_TERM = pcsemester _ Where p.ACADEMIC_YEAR = pcyear _ Select p) For Each row In qstudents exists = "N" For Each res In qresidents If row.ToString = res.ToString Then exists = "Y" End If Next If exists = "Y" Then ' Skip adding. Else ' Add a row. ' Get the ID Dim ID As String = row.PEOPLE_ID ' Get info from PowerCampus Dim qstudent = (From p In dbContext2.PEOPLE _ Where p.PEOPLE_ID = ID _ Order By p.CREATE_DATE Descending _ Select p).FirstOrDefault Dim qpeople = (From p In dbContext2.PEOPLE _ Where p.PEOPLE_ID = ID _ Order By p.CREATE_DATE Descending _ Select p).FirstOrDefault Dim people_code_id As String = qpeople.PEOPLE_CODE_ID Dim qacademic = (From p In dbContext2.ACADEMICs _ Where p.PEOPLE_CODE_ID = people_code_id _ Where p.ACADEMIC_TERM = pcsemester _ Where p.ACADEMIC_YEAR = pcyear _ Order By p.CREATE_DATE Descending _ Select p).FirstOrDefault Dim qaddress = (From p In dbContext2.ADDRESSes _ Where p.PEOPLE_ORG_CODE_ID = people_code_id _ Where p.ADDRESS_TYPE = "Perm" _ Order By p.CREATE_DATE Descending _ Select p).FirstOrDefault Dim qdemographics = (From p In dbContext2.DEMOGRAPHICS _ Where p.PEOPLE_CODE_ID = people_code_id _ Order By p.CREATE_DATE Descending _ Select p).FirstOrDefault ' Create the new occupant. Dim newres As New Resident newres.people_code_id = ID newres.person_name = qpeople.FIRST_NAME + " " + qpeople.MIDDLE_NAME + " " + qpeople.LAST_NAME newres.first_name = qpeople.FIRST_NAME newres.last_name = qpeople.LAST_NAME newres.class_level = qacademic.CLASS_LEVEL newres.gender = qdemographics.GENDER newres.semester = semester newres.year = year newres.email = qaddress.EMAIL_ADDRESS dbContext.Residents.AddObject(newres) dbContext.SaveChanges() End If Next End Using End Using End Sub The above code is used to pull records from a SIS (essentially a higher ed CRM) into my webHousing application (for on-campus residents). It gets a list of everyone who is a student for the select semester/year and then inputs them into the webHousing database if they don't already exist for that semester/year.
Looks like your qresidents is an enumeration of integers, while your qstudents is an enumeration of objects of type residents. So this line If row.ToString = res.ToString Then exists = "Y" End If Can't compare the the to types. Your second query should be something like: Dim qstudents = (From p In dbContext2.RESIDENCies _ Where p.ACADEMIC_TERM = pcsemester _ Where p.ACADEMIC_YEAR = pcyear _ Select p.people_code_id)
Conversion from string "" to type 'Double' is not valid
I have a variable that contains an integer which I then want to save as the value for a column (of type integer in the sql database and int32 in the entity model), but when I try this I receive the error: "Conversion from string "" to type 'Double' is not valid" I'm very confused by this since I'm not using a string or a double? The trouble-making line is: UpdateBed.First.occupant = GetID And here is the full code snippet: Private Sub btnReserve_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReserve.Click Using dbContext As pbu_housingEntities = New pbu_housingEntities ' Check that the room is still available. Dim hall As String = CStr(Session("hall")) Dim room As String = CStr(Session("room")) Dim checkOccupants = From p In dbContext.Rooms _ Let building_id = p.Building1.id _ Where p.building_name = hall _ Where p.room1 = room _ Select p.current_occupancy, p.max_occupancy, p.id, building_id If checkOccupants.First.current_occupancy >= checkOccupants.First.max_occupancy Then ' If it isn't available, let the student know. lblResult.Text = "Sorry, this room is now fully occupied. Please choose another room." Else ' If it is available, add the student to the room. Dim Occupant As New Resident Dim gender As String = CStr(Session("gender")) Dim person_name As String = CStr(Session("person_name")) Dim class_level As String = CStr(Session("class_level")) Dim semester As String = CStr(Session("term")) Dim people_code_id As String = CStr(Session("people_code_id")) Dim first_name As String = CStr(Session("first_name")) Dim last_name As String = CStr(Session("last_name")) Dim building_id As String = checkOccupants.First.building_id Dim room_id As String = checkOccupants.First.id Occupant.building = building_id Occupant.room = room_id Occupant.gender = gender Occupant.person_name = person_name Occupant.class_level = class_level Occupant.semester = semester Occupant.people_code_id = people_code_id Occupant.create_date = Date.Now Occupant.first_name = first_name Occupant.last_name = last_name dbContext.Residents.AddObject(Occupant) ' Increment the number of occupants in the room. Dim UpdateOccupancy = (From p In dbContext.Rooms _ Where p.building_name = hall _ Where p.room1 = room _ Select p).First UpdateOccupancy.current_occupancy = UpdateOccupancy.current_occupancy + 1 ' Add the student to a bed. Dim UpdateBed = From p In dbContext.Beds _ Where p.building = building_id _ Where p.room = room_id _ Where p.occupant = "" _ Select p ' Get the student's ID from the residency table. Dim GetID = (From p In dbContext.Residents _ Where p.people_code_id = people_code_id _ Order By p.id Descending _ Select p.id).FirstOrDefault UpdateBed.First.occupant = GetID dbContext.SaveChanges() lblResult.Text = "Success! You have successfully requested residency in this room!" End If End Using End Sub
This line in your LINQ query ... Where p.occupant = "" ... and this assignment ... UpdateBed.First.occupant = GetID don't seem to fit well together (if GetID is an Int32). Shouldn't it be perhaps Where p.occupant = 0 or something?
No results returning from GridView.SelectedRow.Cells(x).Text?
I have a GridView which is showing results and from which I am deleting a result using the auto-created delete link. My code behind to remove the row and associated info. is: Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting ' The deletion of the individual row is automatically handled by the GridView. Dim dbDelete As New pbu_housingEntities ' Remove individual from the bed. Dim remove_bed = From p In dbDelete.Beds _ Where p.occupant = GridView1.SelectedRow.Cells(3).Text _ Where p.room = GridView1.SelectedRow.Cells(6).Text _ Where p.building = GridView1.SelectedRow.Cells(5).Text _ Order By p.id Descending _ Select p remove_bed.First.occupant = "" dbDelete.SaveChanges() ' Increase number of open spaces in room. Dim update_occupancy = From p In dbDelete.Rooms _ Where p.room1 = GridView1.SelectedRow.Cells(6).Text Where p.building = GridView1.SelectedRow.Cells(5).Text _ Select p update_occupancy.First.current_occupancy = update_occupancy.First.current_occupancy - 1 dbDelete.SaveChanges() End Sub It seems that it is not able to grab the row that is being deleted, so it is always giving me a "Object reference not set to an instance of an object" error.
Use GridView1.Rows(e.RowIndex).Cells(.......