So, I have a series of product pages and all I'd like to do is store the last 5 products viewed in a cookie so it can be displayed as a site-history. The problem I have isn't adding the five initial items to the cookie, its when they view 6, 7 or 10 items. Does anyone have any really decent suggestions on how to tackle this?
Currently I have this flawed logic (i have replaced the cookie name (xxx) for brevity);
Dim i As Integer = 0
Dim productcount As Integer = 0
If HttpContext.Current.Request.Cookies("xxx") Is Nothing Then
Dim gingernuts As New HttpCookie("xxx")
gingernuts.Values("productcount") = 0
gingernuts.Expires = DateTime.Now.AddDays(365)
HttpContext.Current.Response.Cookies.Add(gingernuts)
End If
productcount = HttpContext.Current.Request.Cookies("xxx")("productcount")
For i = 0 To productcount
If HttpContext.Current.Request.Cookies("xxx")("product" & i & "") = "" Then
HttpContext.Current.Response.Cookies("xxx")("product" & i & "") = Request.QueryString("id")
Else
HttpContext.Current.Response.Cookies("xxx")("product" & i & "") = HttpContext.Current.Request.Cookies("xxx")("product" & i & "")
End If
Next
If productcount = 5 Then
HttpContext.Current.Response.Cookies("xxx")("productcount") = 5
HttpContext.Current.Response.Cookies("xxx")("product0") = ""
Else
HttpContext.Current.Response.Cookies("xxx")("productcount") = productcount + 1
End If
Suggestions and critisism welcomed and appreciated.
Chris
Just use a simple cookie value which is a comma delimited list of the most recently viewed product IDs. (Note my VB.NET is that strong).
MostRecentIDs as String() '' // Instance level variables
Const ListSize = 5
'' // in a method somewhere
context As HttpContext = HttpContext.Current
cookie As HttpCookie = context.Request.Cookies("mri")
mri As Queue(Of String)
If cookie Is Nothing Then
mri = New Queue(Of String)(cookie.Value.Split(",".ToCharArray())
Else
mri = New Queue(Of String)
cookie = New HttpCookie("mri")
End If
If mri.Contains(Request.QueryString("id")) Then
If mri.Count >= ListSize Then mri.Dequeue()
mri.Enqueue(Request.QueryString("id"))
End If
MostRecentIDs = mri.ToArray();
cookie.Value = String.Join(",", MostRecentIDs)
cookie.Expires = DateTime.Now.AddDays(365)
context.Response.Add(cookie)
Now you have access to the most recent product IDs as a simple string array.
This code handles the case where the cookie has not yet been created.
The cookie itself is much smaller.
Managing the size of the list can easily be paramaterised.
Code above based on the tested C# code below that I dropped into an empty ASPX file:-
const int listSize = 8;
string[] _mru;
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["mru"];
Queue<string> mru;
if (cookie != null)
{
mru = new Queue<string>(cookie.Value.Split(','));
}
else
{
mru = new Queue<string>();
cookie = new HttpCookie("mru");
}
if (!mru.Contains(Request.QueryString["id"]))
{
if (mru.Count >= listSize) mru.Dequeue();
mru.Enqueue(Request.QueryString["id"]);
}
_mru = mru.ToArray();
cookie.Value = String.Join(",", _mru);
cookie.Expires = DateTime.Now.AddDays(365);
Response.Cookies.Add(cookie);
}
This is how i will do it, if I am understanding your question right :)
If product count is less than 5 just append the new product. Else replace product0 with product1 till 4 and then add new product at 4
If productcount < 5 Then 'Do the null value check before this
HttpContext.Current.Response.Cookies("xxx")("productcount") = productCount + 1
HttpContext.Current.Response.Cookies("xxx")("product" & productCount + 1) = ""
Else
For i = 0 To productcount - 1
'Replace product 0 with 1, 1 with 2...till 3 with 4
HttpContext.Current.Response.Cookies("xxx")("product" & i & "") = HttpContext.Current.Response.Cookies("xxx")("product" & i + 1& "")
Next
HttpContext.Current.Response.Cookies("xxx")("product" & 4 & "") = Request.QueryString("id")
End If
Anthony answered this question perfectly, but for future reference and for those using VB, this is the code:
Imports System.Collections.Generic
Const listSize As Integer = 5
Private _mru As String()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cookie As HttpCookie = Request.Cookies("mru")
Dim mru As Queue(Of String)
If cookie IsNot Nothing Then
mru = New Queue(Of String)(cookie.Value.Split(","c))
Else
mru = New Queue(Of String)()
cookie = New HttpCookie("mru")
End If
If mru.Count >= listSize Then
mru.Dequeue()
End If
mru.Enqueue(Request.QueryString("id"))
_mru = mru.ToArray()
cookie.Value = [String].Join(",", _mru)
cookie.Expires = DateTime.Now.AddDays(365)
Response.Cookies.Add(cookie)
End Sub
Many thanks to all the contributors here also.
Related
First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!
I am trying to reset the pagesize of each record in pdf, which is the total page
(1 of pagesize
2 of pagesize.......)
The 1st blockcode work for 1 single record but then when it come to multiple record it showed:
1 of 0 //1st record
2 of 0
1 of 0 //2nd record
.......
I think there is something to do with document.setPageSize() but it is boolean and belong to Rectangle.
Please help me solve this problem.
Thank.
Public Overrides Sub onEndPage(ByVal writer As PdfWriter, ByVal document As Document)
Dim page As Rectangle = document.getPageSize()
Dim cb As PdfContentByte = writer.getDirectContent()
Dim arialbasefont As BaseFont = arial.getBaseFont
Dim pg As Rectangle = document.getPageSize()
Dim pageNumberText As String = "Page " & writer.getPageNumber() & " of "
Dim timeStampText As String = Now.ToString
Dim pageNumberTextLength As Double = arialbasefont.getWidthPoint(pageNumberText, footerFontSize)
Dim timeStampTextLength As Double = arialbasefont.getWidthPoint(timeStampText, footerFontSize)
Dim pageNumberTextLeft As Double = 20
Dim templateLeft As Double = pageNumberTextLeft + pageNumberTextLength
Dim pageNumberTextBottom As Double = 5 + footerFontSize
cb.beginText()
cb.setFontAndSize(arialbasefont, footerFontSize)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, pageNumberText, pageNumberTextLeft, pageNumberTextBottom, 0)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, Now, pg.urx - (timeStampTextLength + 20), pageNumberTextBottom, 0)
cb.endText()
cb.addTemplate(tpl, templateLeft, pageNumberTextBottom)
End Sub
For Each ProjectID In array
Dim rptRequestReportObj As New rptRequestReport2
rptRequestReportObj.Report(document, ProjectID)
document.newPage()
document.setPageCount(1)
Next ProjectID
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.....
On Button Click
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
MsgBox("INSIDE")
If SocialAuthUser.IsLoggedIn Then
Dim accountId As Integer = BLL.getAccIDFromSocialAuthSession
Dim AlbumID As Integer = BLL.createAndReturnNewAlbumId(txtStoryTitle.Text.Trim, "")
Dim URL As String = BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim)
Dim dt As New DataTable
dt.Columns.Add("PictureID")
dt.Columns.Add("AccountID")
dt.Columns.Add("AlbumID")
dt.Columns.Add("URL")
dt.Columns.Add("Thumbnail")
dt.Columns.Add("Description")
dt.Columns.Add("AlbumCover")
dt.Columns.Add("Tags")
dt.Columns.Add("Votes")
dt.Columns.Add("Abused")
dt.Columns.Add("isActive")
Dim Row As DataRow
Dim uniqueFileName As String = ""
If Session("ID") Is Nothing Then
lblMessage.Text = "You don't seem to have uploaded any pictures."
Exit Sub
Else
**Dim FileCount As Integer = Request.Form(Request.Form.Count - 2)**
Dim FileName, TargetName As String
Try
Dim Path As String = Server.MapPath(BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim))
If Not IO.Directory.Exists(Path) Then
IO.Directory.CreateDirectory(Path)
End If
Dim StartIndex As Integer
Dim PicCount As Integer
For i As Integer = 0 To Request.Form.Count - 1
If Request.Form(i).ToLower.Contains("jpg") Or Request.Form(i).ToLower.Contains("gif") Or Request.Form(i).ToLower.Contains("png") Then
StartIndex = i + 1
Exit For
End If
Next
For i As Integer = StartIndex To Request.Form.Count - 4 Step 3
FileName = Request.Form(i)
'## If part here is not kaam ka..but still using it for worst case scenario
If IO.File.Exists(Path & FileName) Then
TargetName = Path & FileName
'MsgBox(TargetName & "--- 1")
Dim j As Integer = 1
While IO.File.Exists(TargetName)
TargetName = Path & IO.Path.GetFileNameWithoutExtension(FileName) & "(" & j & ")" & IO.Path.GetExtension(FileName)
j += 1
End While
Else
uniqueFileName = Guid.NewGuid.ToString & "__" & FileName
TargetName = Path & uniqueFileName
End If
IO.File.Move(Server.MapPath("~/TempUploads/" & Session("ID") & "/" & FileName), TargetName)
PicCount += 1
Row = dt.NewRow()
Row(1) = accountId
Row(2) = AlbumID
Row(3) = URL & uniqueFileName
Row(4) = ""
Row(5) = "No Desc"
Row(6) = "False"
Row(7) = ""
Row(8) = "0"
Row(9) = "0"
Row(10) = "True"
dt.Rows.Add(Row)
Next
If BLL.insertImagesIntoAlbum(dt) Then
lblMessage.Text = PicCount & IIf(PicCount = 1, " Picture", " Pictures") & " Saved!"
lblMessage.ForeColor = Drawing.Color.Black
Dim db As SqlDatabase = Connection.connection
Using cmd As DbCommand = db.GetSqlStringCommand("SELECT PictureID,URL FROM AlbumPictures WHERE AlbumID=#AlbumID AND AccountID=#AccountID")
db.AddInParameter(cmd, "AlbumID", Data.DbType.Int32, AlbumID)
db.AddInParameter(cmd, "AccountID", Data.DbType.Int32, accountId)
Using ds As DataSet = db.ExecuteDataSet(cmd)
If ds.Tables(0).Rows.Count > 0 Then
ListView1.DataSource = ds.Tables(0)
ListView1.DataBind()
Else
lblMessage.Text = "No Such Album Exists."
End If
End Using
End Using
'WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.ReturnUrl("~/Memories/SortImages.aspx?id=" & AlbumID))
Else
'TODO:we'll show some error msg
End If
Catch ex As Exception
MsgBox(ex.Message)
lblMessage.Text = "Oo Poop!!"
End Try
End If
Else
WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.LoginWithReturnUrl("~/Memories/CreateAlbum.aspx"))
Exit Sub
End If
End Sub
The above code works fine.I have added an Update Panel in the page to avoid post back, But when i add the button click as a trigger
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" />
</Triggers>
in the update panel to avoid post back, i get the following error.This happens when i add the button click as a Trigger to the update panel.
The Request.Form returns a NameValueCollection which is accessible by the name of the key or the int indexer. It always returns a String and not an Integer.
Dim FileCount As String = Request.Form(Request.Form.Count - 2)
This is all intuition from the exception message, but on the line
FileCount As Integer = Request.Form(Request.Form.Count - 2)
It looks like Request.Form(Request.Form.Count - 2) is a string, and you're trying trying to assign a it to an integer type.
I don't know what you're trying to do, but the string looks like it contains "true" do you want the following?
FileCount As Integer += Boolean.Parse(Request.Form(Request.Form.Count - 2)) ? 1 : 0;
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