save and reload page issues vb.net/asp - asp.net

I have 3 buttons, one cancels, one applies the changes and one saves/exits. The Cancel and the Save/Exit work fine, but the Apply and reload page fails. When the apply/reload is clicked it loads the unchanged version or the template depending on which way I have tried, instead of showing the updated page. I know this should be a fairly simple thing and have no problems in other languages when I try this, I have left a few of the options I have tried in the code as commented out parts. I went ahead and included the whole class, but the problem area is in the btnApply_Click
Public Class create_worksheet
Inherits System.Web.UI.Page
Public Property editID As Integer
Public Property TemplateID As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
editID = Request.QueryString("id")
TemplateID = Request.QueryString("template")
If Not Page.IsPostBack Then
If (Not editID = Nothing And Not editID = 0) Then
Dim d As New Data.LINQ.LINQWorkflowDAO
Dim wf = d.GetDefaultWorkflow(editID)
If wf.ID > 0 Then
litHeading.Text = "Edit Workflow"
lblWorkflowBreadCrumb.Text = wf.Name
txtWorksheetName.Value = wf.Name
txtProcessDoc.Value = wf.DetailedProcessDocumentLink
rptPrepTasks.DataSource = wf.Tasks.Where(Function(p) p.Type = "Prep-work")
rptPrepTasks.DataBind()
rptMigrationTasks.DataSource = wf.Tasks.Where(Function(p) p.Type = "Migration")
rptMigrationTasks.DataBind()
rptPostTasks.DataSource = wf.Tasks.Where(Function(p) p.Type = "Post-migration")
rptPostTasks.DataBind()
divProcessDoc.Visible = False
Else
If Not TemplateID = Nothing Then
lblWorkflowBreadCrumb.Text = "Create Workflow"
editID = Nothing
End If
End If
ElseIf Not TemplateID = Nothing Then
Dim d2 As New Data.LINQ.LINQWorkflowDAO
Dim wf2 = d2.GetDefaultWorkflow(TemplateID)
If wf2.ID > 0 Then
litHeading.Text = "Edit Workflow"
txtProcessDoc.Value = wf2.DetailedProcessDocumentLink
rptPrepTasks.DataSource = wf2.Tasks.Where(Function(p) p.Type = "Prep-work")
rptPrepTasks.DataBind()
rptMigrationTasks.DataSource = wf2.Tasks.Where(Function(p) p.Type = "Migration")
rptMigrationTasks.DataBind()
rptPostTasks.DataSource = wf2.Tasks.Where(Function(p) p.Type = "Post-migration")
rptPostTasks.DataBind()
divProcessDoc.Visible = False
End If
If Not TemplateID = Nothing Then
lblWorkflowBreadCrumb.Text = "Create Workflow"
editID = Nothing
End If
End If
If Not IsNothing(Request.QueryString("Action")) Then lblStatus.Text = "Workflow Saved"
End If
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If txtWorksheetName.Value.Length > 0 Then
Dim tasks As New List(Of Data.WorkflowTask)
Dim prepTitles = Request.Form.GetValues("txtPrepTitle")
Dim migrationTitles = Request.Form.GetValues("txtMigrationTitle")
Dim postTitles = Request.Form.GetValues("txtPostTitle")
If Not IsNothing(prepTitles) Then
'prep
For i As Integer = 0 To prepTitles.Length - 1
tasks.Add(New Data.WorkflowTask With {.Name = prepTitles(i), .Type = "Prep-work"})
Next
End If
If Not IsNothing(migrationTitles) Then
'migration
For i As Integer = 0 To migrationTitles.Length - 1
tasks.Add(New Data.WorkflowTask With {.Name = migrationTitles(i), .Type = "Migration"})
Next
End If
'post
If Not IsNothing(postTitles) Then
For i As Integer = 0 To postTitles.Length - 1
tasks.Add(New Data.WorkflowTask With {.Name = postTitles(i), .Type = "Post-migration"})
Next
End If
Dim d As New Data.LINQ.LINQWorkflowDAO
Dim newid As Integer = 0
'if this is a new process, create new, else, update existing
If editID = Nothing Then
d.CreateDefaultWorkflow(txtWorksheetName.Value, tasks, txtProcessDoc.Value)
Else
newid = d.UpdateDefaultWorkflow(editID, txtWorksheetName.Value, tasks)
End If
lblStatus.Text = "Workflow Saved"
Dim wf = d.GetDefaultWorkflow(txtWorksheetName.Value)
'Response.Redirect("create-worksheet.aspx?id=" & wf.ID.ToString() & "&action=Saved")
Response.Redirect("default-worksheets.aspx")
Else
lblStatus.Text = "Please Enter a Name for the Workflow"
End If
End Sub
Private Sub btnApply_Click(sender As Object, e As EventArgs) Handles btnApply.Click
If txtWorksheetName.Value.Length > 0 Then
Dim tasks As New List(Of Data.WorkflowTask)
Dim prepTitles = Request.Form.GetValues("txtPrepTitle")
Dim migrationTitles = Request.Form.GetValues("txtMigrationTitle")
Dim postTitles = Request.Form.GetValues("txtPostTitle")
If Not IsNothing(prepTitles) Then
'prep
For i As Integer = 0 To prepTitles.Length - 1
tasks.Add(New Data.WorkflowTask With {.Name = prepTitles(i), .Type = "Prep-work"})
Next
End If
If Not IsNothing(migrationTitles) Then
'migration
For i As Integer = 0 To migrationTitles.Length - 1
tasks.Add(New Data.WorkflowTask With {.Name = migrationTitles(i), .Type = "Migration"})
Next
End If
'post
If Not IsNothing(postTitles) Then
For i As Integer = 0 To postTitles.Length - 1
tasks.Add(New Data.WorkflowTask With {.Name = postTitles(i), .Type = "Post-migration"})
Next
End If
Dim d As New Data.LINQ.LINQWorkflowDAO
Dim newid As Integer = 0
'if this is a new process, create new, else, update existing
If editID = Nothing Then
d.CreateDefaultWorkflow(txtWorksheetName.Value, tasks, txtProcessDoc.Value)
Else
newid = d.UpdateDefaultWorkflow(editID, txtWorksheetName.Value, tasks)
End If
lblStatus.Text = "Workflow Saved"
Dim wf = d.GetDefaultWorkflow(txtWorksheetName.Value)
'testing/issue items below
Dim originThing = d.GetDefaultWorkflow(txtWorksheetName.Value)
'Server.Transfer(Request.Path)
'Response.Redirect("default-worksheets.aspx")
' Response.Redirect("create-worksheet.aspx?id=" & originThing.ID.ToString() & "&action=Saved")
'Response.Redirect("create-worksheet.aspx?id=" & wf.ID.ToString() & "&action=Saved")
'Response.Redirect(Request.RawUrl)
'Response.Redirect(Request.RawUrl, True)
'Server.TransferRequest(Request.Url.AbsolutePath, False)
'Server.TransferRequest(Request.Url.AbsolutePath, True)
Else
lblStatus.Text = "Please Enter a Name for the Workflow"
End If
End Sub
End Class
Thank you all in advance for any direction you can give, it is appreciated
SOLVED IT!!!
Response.Redirect("create-worksheet.aspx?id=" & newid)
what the issue was the code was assigning a new id, and i kept going back to the old one.....

Related

Webviewpage Model returns Nothing when deployed on web server

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.

Allow only some check boxes to be checked. Loaded on page_load

I am dynamically adding asp check boxes to my page based off of number of rows in my db table, by ID. Also the checkbox is being assigned an ID from the db table. I also two columns in my db table "numberOffered" and "numberAllowed". My idea is on page load only allow the user to check say 3 of the 10 check boxes shown. I have removed a lot of the code I thought would be unnecessary. Thank you very much in advance.
For Each Arow As Object In ATable.Rows
For Each Brow As Object In BTable.Rows
If Brow(1) = a_ID Then
If Brow(2) = b_ID Then
Dim cbShown As Integer = Arow(5)
Dim cbAllowed As Integer = Arow(6)
Dim checkBox As New CheckBox()
End If
End If
Next
Next
checkBox.ID = Crow(0)
divcontrol.Controls.Add(checkBox)
EDIT:
Full Page_load sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (Session("studentLoggedIn") Or Session("adminLoggedIn")) Then
Routines.LogOut()
End If
If Session("adminLoggedIn") = True Then
castVote.Enabled = False
castVote.CssClass = "btnDisabled"
Dim p As New HtmlGenericControl()
p.TagName = "p"
p.InnerText = "Vote button disabled. Only students may vote."
adminMsg.Controls.Add(p)
End If
Dim ballot_ID As Integer = CType(Session.Item("ballot_ID"), Integer)
Dim ballotName As String = CType(Session.Item("ballotName"), String)
Dim ballotsAdapter As New eVoteTableAdapters.ballotsTableAdapter()
Dim ballotsTable As New eVote.ballotsDataTable
ballotsTable = ballotsAdapter.GetDataBy3getBallotsByID(ballot_ID)
Dim sectionsAdapter As New eVoteTableAdapters.sectionsTableAdapter()
Dim sectionsTable As New eVote.sectionsDataTable
sectionsTable = sectionsAdapter.GetDataBygetsectionsByBallotID(ballot_ID)
Dim candidatesAdapter As New eVoteTableAdapters.candidatesTableAdapter()
Dim candidatesTable As New eVote.candidatesDataTable
candidatesTable = candidatesAdapter.GetDataBygetCandidatesByballotID(ballot_ID)
openBallotName.InnerText = ballotName
Dim section_ID
For Each row As Object In sectionsTable.Rows
If row(1) = ballot_ID Then
section_ID = row(0)
Dim sectionName As New HtmlGenericControl()
Dim sectionDescription As New HtmlGenericControl()
Dim divcontrol As New HtmlGenericControl()
Dim br As New HtmlGenericControl()
divcontrol.Attributes("ID") = section_ID
divcontrol.Attributes("runat") = "server"
divcontrol.Attributes("style") = "border: solid;"
divcontrol.TagName = "div"
br.TagName = "br"
sectionName.TagName = "h4"
sectionDescription.TagName = "p"
mainBallotDiv.Controls.Add(divcontrol)
mainBallotDiv.Controls.Add(br)
sectionName.InnerText = row(2)
sectionDescription.InnerText = row(3)
divcontrol.Controls.Add(sectionName)
divcontrol.Controls.Add(sectionDescription)
For Each Crow As Object In candidatesTable.Rows
If Crow(1) = ballot_ID Then
If Crow(2) = section_ID Then
Dim checkBox As New CheckBox()
Dim canImg As New Image()
Dim canName As New HtmlGenericControl()
Dim canBio As New HtmlGenericControl()
Dim rmImg As New Image()
Dim rmName As New HtmlGenericControl()
Dim rmBio As New HtmlGenericControl()
Dim canBytes As Byte() = Crow(6)
Dim canBase64String As String = Convert.ToBase64String(canBytes, 0, canBytes.Length)
Dim rmBytes As Byte() = Crow(11)
Dim rmBase64String As String = Convert.ToBase64String(rmBytes, 0, rmBytes.Length)
checkBox.ID = Crow(0)
canName.TagName = "h3"
canBio.TagName = "p"
rmName.TagName = "h3"
rmBio.TagName = "p"
canName.InnerText = Crow(4) & " " & Crow(5)
canBio.InnerText = Crow(7)
canImg.ImageUrl = Convert.ToString("data:image/png;base64,") & canBase64String
canImg.Height = 120
rmName.InnerText = Crow(9) & " " & Crow(10)
rmBio.InnerText = Crow(12)
rmImg.ImageUrl = Convert.ToString("data:image/png;base64,") & rmBase64String
rmImg.Height = 120
divcontrol.Controls.Add(checkBox)
divcontrol.Controls.Add(canImg)
divcontrol.Controls.Add(canName)
divcontrol.Controls.Add(canBio)
If row(4) = True Then
divcontrol.Controls.Add(rmImg)
divcontrol.Controls.Add(rmName)
divcontrol.Controls.Add(rmBio)
End If
End If
End If
Next
End If
Next
End Sub
You will want a variable (integer) for the amount of checkboxes allowed, then another variable for the amount of checkboxes currently checked, finally a List containing the name of each checkbox, (have all these variables as class fields)
then in your event handler something like
Sub Check_Clicked(sender As Object, e As EventArgs)
checked += 1
If checked >= NumberAllowedChecked Then
For Each a As CheckBox In MyCheckBoxList
If Not CheckBox.Checked Then CheckBox.Enabled = False
Next
End If
End Sub
I am not overly familiar with VB but I think this should set you on the right track on how to implement it for yourself
Edit: you will want to add in logic for if a user unchecks a check box that it will subtract one from 'checked;

unhandles exception error when login page idle

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"

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

Session disappears unexpectedly

The site is a buy/sell site and the page the code comes from is the "add product" page.
The problem is that the session("change") becomes nothing by some reason, I can't find any errors. The payment.aspx have a button that sends me back to the page with a session("change").
The reason I see the problem is that when I try to edit something the category gets restetted to the first in the list. and when I debug I see that the session is nothing, though it should be something
Heres the code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
If Not stats > 0 Then
If Session("change") IsNot Nothing Then
Dim dc As New DataClassesDataContext
Dim getP = From prod In dc.Products _
Where prod.ProductID = CInt(Session("change")) _
Select prod
If getP.Any Then
If rdbSell.Checked = True Then
getP.FirstOrDefault.BuySell = True
Else
getP.FirstOrDefault.BuySell = False
End If
If ddlSubSubcat.SelectedValue IsNot String.Empty Then
getP.FirstOrDefault.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
getP.FirstOrDefault.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
getP.FirstOrDefault.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
getP.FirstOrDefault.CountyID = CInt(ddlCounty.SelectedValue)
getP.FirstOrDefault.E_mail = txtEmail.Text
getP.FirstOrDefault.Date = DateTime.Now
getP.FirstOrDefault.Active = 0
getP.FirstOrDefault.Alias = txtAlias.Text.Replace("'", "''")
getP.FirstOrDefault.ShowEmail = 0
Dim PreID As Integer = getP.FirstOrDefault.ProductID
If chkShowEmail.Checked = True Then
getP.FirstOrDefault.ShowEmail = 1
Else
getP.FirstOrDefault.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
getP.FirstOrDefault.ShowPhone = 1
Else
getP.FirstOrDefault.ShowPhone = 0
End If
getP.FirstOrDefault.Headline = txtHeadline.Text
getP.FirstOrDefault.Password = txtPassword.Text
getP.FirstOrDefault.Phone = txtPhone.Text
getP.FirstOrDefault.Price = txtPrice.Text
If chkUnknown.Checked = True Then
getP.FirstOrDefault.YearModel = String.Empty
Else
getP.FirstOrDefault.YearModel = ddlYear.SelectedValue
End If
For Each item In libPictures.Items
Dim i As String = item.ToString
Dim imagecheck = From img In dc.Pictures _
Where img.Name = i And img.ProductID = CInt(Session("change")) _
Select img
If imagecheck.Any Then
Else
Dim img As New Picture
img.Name = item.ToString
img.ProductID = CInt(Session("change"))
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
End If
Next
dc.SubmitChanges()
Session.Remove("change")
Response.Redirect("~/precheck.aspx?id=" + PreID.ToString)
End If
Else
Dim dc As New DataClassesDataContext
Dim prod As New Product
If rdbSell.Checked = True Then
prod.BuySell = True
Else
prod.BuySell = False
End If
If ddlSubSubcat.DataValueField IsNot String.Empty Then
prod.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
prod.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
prod.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
prod.CountyID = CInt(ddlCounty.SelectedValue)
prod.E_mail = txtEmail.Text
prod.Date = DateTime.Now
prod.Active = 0
prod.Alias = txtAlias.Text.Replace("'", "''")
prod.ShowEmail = 0
If chkShowEmail.Checked = True Then
prod.ShowEmail = 1
Else
prod.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
prod.ShowPhone = 1
Else
prod.ShowPhone = 0
End If
prod.Headline = txtHeadline.Text
prod.Password = txtPassword.Text
prod.Phone = txtPhone.Text
prod.Price = txtPrice.Text
If chkUnknown.Checked = True Then
prod.YearModel = String.Empty
Else
prod.YearModel = ddlYear.SelectedValue
End If
dc.Products.InsertOnSubmit(prod)
dc.SubmitChanges()
Dim PreID As Integer = prod.ProductID
For Each item In libPictures.Items
Dim img As New Picture
img.Name = item.ToString
img.ProductID = prod.ProductID
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
Next
Session.Remove("change")
Response.Redirect("./precheck.aspx?id=" + PreID.ToString, False)
End If
End If
stats = 0
'Catch ex As Exception
'End Try
End Sub
It depends upon how the application is managing session state. If your session state is managed InProc then if the application pool is recycled then all your session information will be lost. If that is happening then it could be a good option to store session state in SQL Server which will persist between app pool recycling.
More info:
ASP.NET Session State Overview
ASP.NET State Management Recommendations

Resources