Apparently odd ASP.NET Page Behaviour... might just be newbie error? - asp.net

I'm new to ASP.NET but have quite a few successful test pages going now which I am using to slowly build up a new website and data application... hence my many questions on here.
Anyway, in my efforts to understand JSON, I have a test page trying to get the data out, but for some reason the script works fine when it's all one page, but not as code behind.
My ASPX file is:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="json.aspx.vb" Inherits="jsonPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
Output:
<div id="readOut" runat="server"></div>
</form>
</body>
</html>
Code behind:
Imports Jayrock.Json.JsonTextWriter, Jayrock.Json, Jayrock.Json.Conversion, System.Net
Partial Class jsonPage
Inherits System.Web.UI.Page
Sub Page_Load(Sender As Object, E As EventArgs)
Dim cMessage As String = "{""ID"": 8291, ""Item"": ""Epiphone Les Paul Tribute Plus Outfit"", ""Main Image"": ""8291-113247"", ""Colour"": ""Vintage Sunburst"", ""Option"": ""none"", ""Price"": 549.0}"
Dim objResponse As JsonObject = CType(JsonConvert.Import(cMessage), JsonObject)
readOut.InnerText = "Item name is: " & objResponse("Item")
End Sub
End Class
As I say, this is just a test code to try to get to grips with JSON, the text "Item name is:" followed by the result of the JSON parsing, should be posted into the div id="readOut" in the main ASPX page, but it won't... the strange thing is that it works is I take out the Page_Load sub and run the code in the head of the ASPX file.
I've tried comparing this to other files I have that are working and can find no obvious reason why this is happening.

I think this may be your problem. I suspect you weren't even able to hit that code with a breakpoint?
Page_Load(Sender As Object, E As EventArgs)
Should have a handles clause.
Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Related

Variable on aspx page indicating that it is not declared

I am busy doing maintenance on an old VB.Net/ASP.Net solution.
Quite a number of the .aspx pages reference variables on the code behind. While working, these all show up as errors, but the code does compile (making it not critical, but extremely annoying, and difficult to find actual errors).
I have tried protected and private variables.
I made a test page, to indicate the proble.
TestForm.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="TestForm.aspx.vb" Inherits="EGS.TestForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=message %>
</div>
</form>
</body>
</html>
TestForm.aspx.vb
Public Class TestForm
Inherits System.Web.UI.Page
Protected message As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
message = "Hello!"
End Sub
End Class
Error List
Error | BC30451 | 'message' is not declared. It may be inaccessible due to its protection level.
Running it
Hello!
Is there a way to get Visual Studio (2015, if that makes a difference) to see these. They work just fine, like I said, it is just very annoying.
Use public modifier to declare the message variable
Public Class TestForm
Inherits System.Web.UI.Page
public message As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
message = "Hello!"
End Sub
End Class

Passing any value to FileUpload.FileName using a button click

Despite the firing of the method associated with a form and button click, my fileupload will not pass a value to a string, am I doing something obviously wrong (or just wrong in general)?
Do I need to attach a handler to the fileupload
Here is some sample source, note, it is the only code in the project, I have not made any definitions to the button or fileupload anywhere else:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button_Click()
Dim FileUpload1 As New FileUpload()
Dim X As String = FileUpload1.FileName
Response.Write(X)
End Sub
End Class
and the form:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="Test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button_Click" text="Submit"/>
<%-- <input type="file" />--%>
</form>
</body>
</html>
After trying FileUpload.HasFile, it appears as though not only can I not get the file name (described to me in the answer below), but the FileUpload.HasFile is nothing when a file is associated with it as well, is there any reason for this?
Protected Sub Button_Click()
Dim FileUpload1 As New FileUpload()
'Dim X As String = FileUpload1.FileName
'Response.Write(X)
If (FileUpload1.HasFile) Then
' Do Something
' SaveFile(FileUpload1.PostedFile)
Else
End If
End Sub
If you are looking for the path of the uploaded file in the client's machine, that is not allowed for security reasons.
However you should be able to get just the file name using the FileName property.
I check the file name in my applications when i want to test the to see the filetype that is uploaded.
I do not think the following line is required in your Protected Sub Button_Click() function:
Dim FileUpload1 As New FileUpload()
That must be creating a new instance causing it to show you an empty File Name.
If you just need the file name and not the entire path you could try the above.
Edit: Just saw the edit to your questions. The line I asked you to remove may be causing HasFile property to be empty as well.
You can not pass/assign name asp:FileUpload, as it is converted to input type file it is not allowed due to security reason. As it could breach the security of client machine that is browsing the website. The only possibility to assign it a value is through user selection that is browsing and assigning the file by user from client (browser)
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx
You can use FileUpload.SaveAs method to save the selected file.
FileUpload1.SaveAs(savePath);

iTextSharp .pdf tool

Afternoon All,
I have been advised that i can use iTextSharp to help me convert my web pages into .PDF files. I am using the following link as a sample tutorial but cannot generate the .pdf?
Visit http://www.dotnetspark.com/kb/654-simple-way-to-create-pdf-document-using.aspx
I am using the VB sample. I have added the iTextSharp.dll to my project and added the namespaces as requested. I have simply created a blank page and added a button to the page and using the following code i cant seem to get this to generate the file?
Here is my code...
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Partial Class pdf
Inherits System.Web.UI.Page
Protected Sub btnGeneratePDF_Click(ByVal sender As Object, ByVal e As EventArgs)
'Create Document class obejct and set its size to letter and give space left, right, Top, Bottom Margin
Dim doc As New Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35)
Try
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("d:\myfolder\test.pdf", FileMode.Create))
'Open Document to write
doc.Open()
'Write some content
Dim paragraph As New Paragraph("This is my first line using Paragraph.")
Dim pharse As New Phrase("This is my second line using Pharse.")
Dim chunk As New Chunk(" This is my third line using Chunk.")
' Now add the above created text using different class object to our pdf document
doc.Add(paragraph)
doc.Add(pharse)
doc.Add(chunk)
Catch dex As DocumentException
'Handle document exception
Catch ioex As IOException
'Handle IO exception
Catch ex As Exception
'Handle Other Exception
Finally
'Close document
doc.Close()
End Try
End Sub
End Class
Here is the code for the button...
<%# Page Language="VB" AutoEventWireup="false" CodeFile="pdf.aspx.vb" Inherits="pdf" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGeneratePDF" runat="server" Text="Generate .PDF" />
</div>
</form>
</body>
</html>
Could someone please take a look at this for me and let me know where i am going wrong?
Regards
Betty
Not sure if this will fix it all, but you're at least missing the Click_Event from your buttton.
<asp:Button ID="btnGeneratePDF" runat="server" Text="Generate .PDF" OnClick="btnGeneratePDF_Click" />
(And I see that you asked this question yesterday: Button ClickEvent is not triggered with the same problem, try to remember next time ;-))

Show Image/HTML before Page_Load is completed

I have following code in aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" nherits="test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
<body>
<img src="images/loading_anim.gif" />Please wait...
</body>
</html>
In test.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
......Do some processing here .
Response.redirect("Next.aspx")
End Sub
Code Behind I do some processing in Page_load method and redirect to other page but it might take some time so I want to show user loading image.But it shows that after page_load is completed.How to handle this ?
I will suggest that you use a generic handler (ashx) and use un-buffered response. For example:
public class Handler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.BufferOutput = false;
context.Response.Write("<html><head></head><body><img src=\"images/loading_anim.gif\" />Please wait...</body></html>"
context.Response.Flush();
// do your processing
...
// redirect
}
...
}
Yet another way to first show image on the client side (using java-script) and then do redirection (or post) from client side.
I don't think it will work because always the server side code works first, then only HTML rendering starts. Better option will be using Ajax.
More details here : ASP.NET Integration with IIS 7

Dynamic Controls Example. Script controls may not be registered after PreRender

When creating dynamic ajax controls you may experience a pre-render issue on postbacks. You are supposed to re-create the controls on postback, however if there are very many of them performance gets very slow between each postback. i.e. clicking on a combobox, it may take several seconds. So what I did was group the controls in panels, store the panels in a collection, then re-call the panels on Postback. This actually works great if the controls inside the panel are standard html controls (textbox, dropdowlist, etc.). But...doesn't work well with ajax controls...yet.
I have included a sample below. Uncomment/Comment the code to test it. If anyone has a good idea how to make this work with ajax controls that would be great.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="PreRenderAjax.WebForm1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Public Class WebForm1
Inherits System.Web.UI.Page
Shared panellist As New List(Of Panel)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
'This is for reloading panels. Works with dropdownlist, but not ajax combobox
For Each pn As Panel In panellist
PlaceHolder1.Controls.Add(pn)
Next
'This for re-creating all the controls again. Not very efficient for ajax controls though.
'CreateInterface()
Else
CreateInterface()
End If
End Sub
Protected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()
End Sub
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
EnsureChildControls()
End Sub
Private Sub CreateInterface()
Dim pn As Panel
pn = CreatePanel("panel1")
CreateControls(pn, 5)
pn = CreatePanel("panel2")
CreateControls(pn, 5)
pn = CreatePanel("panel3")
CreateControls(pn, 5)
pn = CreatePanel("panel4")
CreateControls(pn, 5)
End Sub
Private Function CreatePanel(ByVal name As String) As Panel
Dim pn As New Panel
pn.ID = name
pn.Width = 250
pn.BorderStyle = BorderStyle.Solid
pn.BorderColor = Drawing.Color.Blue
pn.Style.Add("margin", "5px")
pn.Style.Add("padding", "5px")
PlaceHolder1.Controls.Add(pn)
panellist.Add(pn)
CreatePanel = pn
End Function
Private Sub CreateControls(ByVal pn As Panel, ByVal howmany As Integer)
Dim cbo As AjaxControlToolkit.ComboBox
'Dim cbo As DropDownList
For i As Integer = 0 To howmany - 1
cbo = New AjaxControlToolkit.ComboBox
'cbo = New DropDownList
cbo.ID = pn.ID & "_cbo" & i
cbo.Width = 200
cbo.Items.Add("Item 1")
cbo.Items.Add("Item 2")
cbo.Items.Add("Item 3")
cbo.Items.Add("Item 4")
cbo.Items.Add("Item 5")
cbo.Style.Add("margin", "3px")
cbo.AutoPostBack = True
pn.Controls.Add(cbo)
Next
End Sub
End Class
I just did a test to see if postback slowness was from the ajax controls themselves or recreation. Well come to find out its tha actual ajax controls themselves. I created a blank page, put 40 ajax combobox's on (adding a couple items to each), turn on postcack. When I started the page and clicked an item it took about 3 or 4 seconds to complete the postback.
Did the same thing with dropdownlist and it works great. too bad you cant use it like a combobox.

Resources