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
Related
I am creating an ASP.Net website with VB.Net as code behind and this is the error that appears from the published version on a web server (this does not appear when run directly from the code or from the published version on the IIS server):
error message screenshot
This is a snippet from the controller:
Function Index(ByVal pSurveyName As String) As ActionResult
Try
If IsNothing(pSurveyName) Then
Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
End If
Dim l_question As Object = GetQuestion()
Return View(l_question)
Catch ex As Exception
Call ExceptionHandler(ex)
Return View()
End Try
End Function
Function GetQuestion() As Object
Dim l_questionnaire = Session("ActiveQuestionnaire")
Dim l_surveySession = Session("SurveySession")
Dim l_redirectQueue = Session("RedirectQueue")
Dim l_sessionAnswers = Session("SessionAnswers")
Dim l_CurrentQuestion As CurrentItem = New CurrentItem
Dim l_Choices As List(Of Choice) = New List(Of Choice)
Dim l_TempDBQuestions = db.Questions
Dim l_TempDBChildQuestions = db.ChildQuestions
Dim l_TempDBChoices = db.Choices
Dim l_tempFiltered_Q
Dim li_questionnaireID As Integer
Dim li_questionCtr As Integer
Dim li_total_NoOfQuestion As Integer = 0
Dim li_resultCount As Integer = 0
Dim li_childQID As Integer = 0
Dim ls_prevAnswer As String = ""
Dim ls_err As String = ""
Try
li_questionnaireID = l_questionnaire.ID
li_questionCtr = l_surveySession.QuestionCtr
If Session("Back") = False Then
li_questionCtr = GetQuestionCtr(NEXT_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers,, ls_prevAnswer)
Else
Dim l_current = Session("CurrentQuestion")
li_questionCtr = GetQuestionCtr(PREVIOUS_QUESTION, l_surveySession, l_redirectQueue, l_sessionAnswers, l_current, ls_prevAnswer)
End If
l_tempFiltered_Q = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
li_resultCount = l_TempDBQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr)).Count
If li_resultCount = 0 Then
l_tempFiltered_Q = l_TempDBChildQuestions.Where(Function(q) q.QuestionnaireID.Equals(li_questionnaireID) And q.QuestionOrder.Equals(li_questionCtr))
Session("FrmChildQuestions") = True
Else
Session("FrmChildQuestions") = False
End If
For Each item In l_tempFiltered_Q
'item could be from Questions or ChildQuestions
If li_resultCount = 0 Then
Session("IsNextQuestionChild") = item.IsNextQuestionChild
End If
With l_CurrentQuestion
.ID = item.ID
.QuestionnaireID = item.QuestionnaireID
.QuestionOrder = item.QuestionOrder
.Description = item.Description
.AnswerType = item.AnswerType
.AllowMultipleAnswers = item.AllowMultipleAnswers
.QuestionNo = item.QuestionNo
.Required = item.Required
.TempAnswer = ls_prevAnswer
End With
Next
If l_CurrentQuestion.AnswerType = constants.MULTIPLE_CHOICE Then
'Get Choices
Dim li_questionID As Integer = l_CurrentQuestion.ID
If li_resultCount = 0 Then
l_Choices = db.Choices.SqlQuery("select * from Choices where ChildQuestionID = " & li_questionID & "").ToList
Else
l_Choices = db.Choices.SqlQuery("select * from Choices where QuestionID = " & li_questionID & "").ToList
End If
Session("Choices") = l_Choices
End If
If Session("TotalQuestions") Is Nothing Then
li_total_NoOfQuestion = db.Database.SqlQuery(Of Integer) _
("select max(a.MaxOrder) from(select max(QuestionOrder) " &
"as MaxOrder from Questions union select QuestionOrder from " &
"ChildQuestions)a").FirstOrDefault
Session("TotalQuestions") = li_total_NoOfQuestion
End If
With l_surveySession
.QuestionCtr = li_questionCtr
End With
Session("SurveySession") = l_surveySession
Session("CurrentQuestion") = l_CurrentQuestion
Session("Back") = False
Return l_CurrentQuestion
Catch ex As Exception
Call ExceptionHandler(ex)
End Try
End Function
And this is from the view:
#ModelType Survey_App.Models.CurrentItem
#Code
ViewData("Title") = "Index"
Layout = "~/Views/Shared/_Layout.vbhtml"
Dim l_choices = Session("Choices")
Dim l_activeSurvey = Session("ActiveSurvey")
Dim ls_tempAnsType As String = Model.AnswerType.ToString 'this is the line indicated in the error msg
Dim ls_temp As String = ""
Dim ls_tempAnswer() As String = Nothing
Dim li_totalQuestions As Integer = 0
li_totalQuestions = Session("TotalQuestions")
Dim ls_POSTAction As String = vbNullString
The error appears some time (maybe 10-15 seconds) after going through the home page but not always immediately. I also tried some debugging and it looks like the session variables also return nothing after that some time.
Protected Sub Email_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim objExport As ClsItextSharp = New ClsItextSharp()
Dim strPath As String = ""
Dim objReport As Report = New Report()
objReport = (Telerik.Reporting.Report)RViewer.Report
strPath = CreatePDfwithPath1(objReport)
Dim docType As String = "EncounterNote"
Dim Imgop As ImageOperations = New ImageOperations()
Dim Path As String = Imgop.EncriptString(strpath)
Response.Redirect("../EMail/SendMail.aspx?send=M&Type=nothing&strpath=" + Path + "")
End Sub
end of statement expected in vb.net while storing value to the object? getting error on objReport = (Telerik.Reporting.Report)RViewer.Report.
What is this, C#?
objReport = (Telerik.Reporting.Report)RViewer.Report
I guess you want to cast it:
Dim objReport = CType(RViewer.Report, Telerik.Reporting.Report)
I have developed a site in vb.net (with some help from my brother in law) and it's almost ready to roll out except I am getting an unhandled exception error on the login
screen when the page is idle for a few minutes. I am reasonably new to vb.net and not a programmer :( Any help would be really appreciated. Sorry if anything in my post is not to the site standard as this is my first post. :)
I'm not sure why this is happening. The code that is executed on login_buttonClick is:
Protected Sub LoginWizard_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles LoginWizard.FinishButtonClick
Dim oUsername As String = txtUsername.Text
Dim oPassword As String = txtPassword.Text
Dim oPath As String = Server.MapPath("App_Data/IOFR.mdb")
Dim oValid As Boolean = False
Dim oReader As System.Data.OleDb.OleDbDataReader = Nothing
Dim oConnection As System.Data.OleDb.OleDbConnection = Nothing
Dim oName As String = ""
Dim oOrg As String = ""
Dim oUserId As Integer = 0
Dim oActiveAcc As String = ""
Dim oSessionExpire As Integer = 0
Try
oConnection = New System.Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Jet OLEDB:Database Password=EdmundColin13", oPath))
oConnection.Open()
Dim ipAddress As String = Request.ServerVariables("REMOTE_ADDR")
Dim cmd As New SqlCommand
Dim oParams As New List(Of System.Data.OleDb.OleDbParameter)
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmUsername", oUsername))
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmPassowrd", oPassword))
Dim oCommand As New System.Data.OleDb.OleDbCommand("SELECT ID, [Name], Organisation, ActiveAccount, [Password] FROM Users WHERE [Username] = #pmUsername AND [Password] = #pmPassword", oConnection)
oCommand.Parameters.AddRange(oParams.ToArray)
oReader = oCommand.ExecuteReader()
If oReader.Read() Then
oValid = True
oName = oReader.GetString(oReader.GetOrdinal("Name"))
oActiveAcc = oReader.GetString(oReader.GetOrdinal("ActiveAccount"))
oOrg = oReader.GetString(oReader.GetOrdinal("Organisation"))
oPassword = oReader.GetString(oReader.GetOrdinal("Password"))
oUserId = oReader.GetInt32(oReader.GetOrdinal("ID"))
oSessionExpire = oReader.GetInt32(oReader.GetOrdinal("SessionExpire"))
End If
Catch ex As Exception
Finally
If Not oReader Is Nothing Then
If Not oReader.IsClosed Then
oReader.Close()
End If
oReader = Nothing
End If
End Try
If oValid And Not String.Equals(txtPassword.Text, oPassword) Then
oValid = False
End If
If oValid Then
If oActiveAcc = "No" Then
Response.Redirect("~/DisabledAccount.aspx")
Return
End If
Session("username") = txtUsername.Text
Session("name") = oName
Session("org") = oOrg
'Generate session id and store it in session
Dim uniquesessionid As String = Guid.NewGuid().ToString()
Session("uid") = uniquesessionid
Dim oCommandSession As New System.Data.OleDb.OleDbCommand("UPDATE Users SET SessionId = #pmid, SessionExpire = '" & DateTime.Now.AddHours(2).ToString() & "' WHERE [ID] = #pmUserid", oConnection)
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmid", uniquesessionid))
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmUserid", oUserId))
oCommandSession.ExecuteNonQuery()
Response.Redirect("~/Home.aspx?login=true")
Else
txtUsername.BorderColor = Drawing.Color.Red
txtUsername.BackColor = Drawing.Color.Red
txtPassword.BorderColor = Drawing.Color.Red
FailedLogin.Visible = True
End If
If Not oConnection Is Nothing Then
If oConnection.State = Data.ConnectionState.Open Then
oConnection.Close()
End If
End If
End Sub
Thanks All. This seams to have resolved the issue.
EnableViewStateMAC="False"
I am connecting to a database and then using an SQLDataReader to parse through those results and then put those results into variables that I can use at a latter time. The problem is that all of my "results.items" are returning null values. The DataReader is however, showing the proper field count when I debug.
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "editPost" Then
'Remove DataGrid'''''''''
GridView1.Visible = False
'''''''''''''''''''''''''
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = GridView1.Rows(index)
Dim ID As String = GridView1.Rows(index).Cells(0).Text
''''''''''''''''''''''''''''''''''''''''CREATE Controls for Placeholder
Dim editEditor As New CuteEditor.Editor
Dim hiddenID As New HiddenField
hiddenID.ID = "hiddenID"
hiddenID.Value = ID
editEditor.ID = "editEditor"
Dim subjectTXT As New TextBox
subjectTXT.ID = "editorSubject"
Dim br As New Literal
Dim submitChanges As New Button
Dim sbjLabel As New Label
submitChanges.ID = "submitChanges"
submitChanges.Text = " Submit Changes "
submitChanges.Height = 40
submitChanges.Width = 300
sbjLabel.Text = "Subject: "
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
editEditor.AutoConfigure = CuteEditor.AutoConfigure.Simple
br.Text = "<br/><br/>"
plcEditor.Controls.Add(hiddenID)
plcEditor.Controls.Add(sbjLabel)
plcEditor.Controls.Add(subjectTXT)
subjectTXT.Width = "100"
subjectTXT.Height = "25"
subjectTXT.CssClass = "editInput"
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(editEditor)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(br)
plcEditor.Controls.Add(submitChanges)
submitChanges.OnClientClick = UpdatePost()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim connStr As String = ConfigurationManager.ConnectionStrings("oakfratnewsConnectionString").ConnectionString
Dim nCon As New SqlConnection(connStr)
Dim addCon As New SqlConnection(connStr)
Dim addCom As New SqlCommand("SELECT * FROM [News] WHERE ([ID] = #ID)", addCon)
addCom.Parameters.AddWithValue("#ID", ID)
addCon.Open()
addCom.ExecuteNonQuery()
Dim results As SqlDataReader
results = addCom.ExecuteReader
While results.Read()
Dim editText As String = results.Item("Content")
Dim Subject As String = results.Item("Subject")
editEditor.Text = editText
subjectTXT.Text = Subject
End While
End If
End Sub
Where do you get the ID value?
"addCom.Parameters.AddWithValue("#ID", ID) "
Remove "addCom.ExecuteNonQuery() "
Why using
Dim editText As String = results.Item("Content")
I define before the loop the variable and then read it in this way
Dim editText As String
While results.Read()
editText = results("Content") ' without .items
...
End While
Why is my bulk copy duplicating each row, so in my database table the row shows twice.
Label1.Visible = True
Dim tourid As New List(Of String)
tourid.Add(TextBox1.Text)
Dim tasktype As New List(Of String)
Dim tourname1 As New List(Of String)
Dim tasknamelist As New List(Of String)
Dim dboxdates As New List(Of String)
Dim dates As New List(Of String)
Dim firstdates As New List(Of String)
Dim agent As New List(Of String)
Dim desc As New List(Of String)
Dim checkitem As ListItem
Dim departuredate As Date
For Each checkitem In dboxes.Items
If checkitem.Selected Then
departuredate = checkitem.Text
dboxdates.Add(departuredate)
For Each row As GridViewRow In GridView1.Rows
' Selects the text from the TextBox
Dim checkboxstatus As CheckBox = CType(row.FindControl("tasknamebox"), CheckBox)
If checkboxstatus.Checked = True Then
tasknamelist.Add(checkboxstatus.Text)
Dim dates1 As TextBox = CType(row.FindControl("tdays"), TextBox)
Dim gracep As TextBox = CType(row.FindControl("tgrace"), TextBox)
Dim aftersubtraction As DateTime
Dim fromatafter As DateTime
aftersubtraction = departuredate.AddDays(-dates1.Text)
fromatafter = aftersubtraction.AddDays(-gracep.Text)
firstdates.Add(fromatafter.ToString("MM/dd/yyyy"))
While fromatafter.DayOfWeek = DayOfWeek.Saturday OrElse fromatafter.DayOfWeek = DayOfWeek.Sunday
fromatafter = fromatafter.AddDays(-2)
End While
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
Dim txtdesc2 As TextBox = CType(row.FindControl("txtdesc"), TextBox)
desc.Add(txtdesc2.Text)
Dim tasktype1 As Label = CType(row.FindControl("tasktype"), Label)
Dim agentdlist As DropDownList = CType(row.FindControl("agentdlist"), DropDownList)
tasktype.Add(tasktype1.Text)
agent.Add(agentdlist.text)
Dim tourname As String
tourname = tname.Text
Dim sChars As String = " "
tourname1.Add(tourname.TrimEnd(sChars))
End If
Next
End If
If tasknamelist.Count > dboxdates.Count Then
Do
dboxdates.Add(checkitem.Text)
Loop Until tasknamelist.Count = dboxdates.Count
End If
If tasknamelist.Count > tourid.Count Then
Do
tourid.Add(TextBox1.Text)
Loop Until tasknamelist.Count = tourid.Count
End If
Next
table.clear()
For i As Integer = 0 To ((dates.Count) - 1)
Dim row = table.NewRow()
row("Tour") = tourid(i)
row("TourName") = tourname1(i)
row("Task") = tasknamelist(i)
row("Departure") = dboxdates(i)
row("Due Date") = dates(i)
row("Task Type") = tasktype(i)
row("Agent Name") = agent(i)
row("Completed") = "NO"
row("Description") = desc(i)
row("Orig Due") = firstdates(i)
table.Rows.Add(row)
Next
toptable.Visible = False
bottom.Visible = True
GridView2.DataSource = table
GridView2.DataBind()
Using bcp As SqlBulkCopy = New SqlBulkCopy(SqlDataSource2.ConnectionString)
bcp.ColumnMappings.Add(0, 1)
bcp.ColumnMappings.Add(1, 2)
bcp.ColumnMappings.Add(2, 3)
bcp.ColumnMappings.Add(3, 4)
bcp.ColumnMappings.Add(4, 7)
bcp.ColumnMappings.Add(5, 5)
bcp.ColumnMappings.Add(6, 10)
bcp.ColumnMappings.Add(7, 13)
bcp.ColumnMappings.Add(8, 6)
bcp.DestinationTableName = "dbo.stagingtasks"
bcp.WriteToServer(table)
End Using
Your doing a table.Rows.Add(row) and a New SqlBulkCopy()
They seem to be the same?