ASP.NET create a page dynamically - asp.net

I am dynamically generating HTML which is stored in a string variable.
I would like to open a new window with a new page created from this HTML.
This seems too simple, but I just cannot find the solution.
I am using ASP.NET 3.5 and VS2008.
Thanks,
Paul.

Best idea would be to create an http handler, register it in your web.config file to handle the various request paths that you need to have dynamic content for, and then detect the content to display based on HttpContext.Current.Request.Path.
This way you don't have to save any files, and you write from your string variable to the output stream

You can try this in your new page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ContentType = "text/html
HttpContext.Current.Response.Write(YourString)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
End Sub

Create an .ashx page that takes a query string, e.g. pagebuilder.ashx?pageid=12345
The purpose of this page is simply to lookup in a session id based on the pageid query string. e.g.
var page = Session["PAGE_" + QueryString["pageid"]].ToString();
Response.Write(page);
On the page that generates the html in a variable, store the variable in Session at Page_Init
` ["PAGE_12345"] = generatedHtml;
Then on Page_Load, generate a javascript that opens to the url pagebuilder.ashx?pageid=12345.
That's it. You will be able to open your newly generated html in another window.

Related

dropdownlist selectedvalue doesnt change

I have this dropdownlist, this one load with the data that I get from a store procedure, as you can see the load is correct, but when I change the selected value in the debug the selected value doesnt change, it stays in the first loaded value, which in this case is 1. What can I do?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim adaptador As New SqlDataAdapter
Dim datos As New DataTable
Dim ord As SqlDataReader
Conexiones.AbrirConexion()
Conexiones.Cnn.Open()
Dim cmd As SqlCommand = New SqlCommand("sp_devolver_empresas", Conexiones.Cnn)
cmd.CommandType = CommandType.StoredProcedure
ord = cmd.ExecuteReader
datos.Load(ord)
cbEmpresas.DataSource = datos
cbEmpresas.DataTextField = "Nombre"
cbEmpresas.DataValueField = "Identificador"
cbEmpresas.DataBind()
Conexiones.Cnn.Close()
End Sub
For EVERY web page that you build and write to the end of time?
You MUST always put the load and setup code inside of a check for post back.
every button, every drop down list, and EVERY time you click on a button or do anything, the page load will ALWAYS fire and run. Thus if you change a value, you will lose that value since the page setup and loading of say control (in this case your dropdown list) will fire EACH time - thus overwriteing.
Out of the last 100's of web pages, the FIRST thing I write is the check for postback.
So, your code should look like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
Dim datos = New DataTable
Using onexiones.Cnn
Using cmd As SqlCommand = New SqlCommand("sp_devolver_empresas", onexiones.Cnn)
cmd.CommandType = CommandType.StoredProcedure
onexiones.Cnn.Open()
datos.Load(cmd.ExecuteReader())
End Using
End Using
cbEmpresas.DataTextField = "Nombre"
cbEmpresas.DataValueField = "Identificador"
cbEmpresas.DataSource = datos
cbEmpresas.DataBind()
End Sub
So, only on the "real" first page load do you want to load up your grids, dropdowns etc. Remember, even a simple button dropped on to the page, and you have a click event? (the page load event fires each time - and every time). So once again, you need the IsPostBack test - and I am quite pressed to find any of my web pages that does not have this all important code stub in the on-load event.
So, remember the above rule - always setup your setup code to run on first time - not every time a button or anything else occurs on the web page. So, page load (unlike desktop) fires each and every time you do ANY operations on that page.
Also, note how I setup the data text, and value field BEFORE we give the drop down list a data source. In fact, I would suggest you put the data text, and data value field in the markup and NOT code (since then multiple different code routines can use that setting - not hard coded in code).
eg do this:
<asp:DropDownList ID="cbEmpresas" runat="server"
DataTextField = "Nombre"
DataValueField = "Identificador" >
</asp:DropDownList>
So, now your code becomes :
cbEmpresas.DataSource = datos
cbEmpresas.DataBind()
I suppsoe some out of habt like to set the text + data settings for the dropdown list in code, but then again, in code you might want more then one palce that loads up the combo box - and thus you now have multiple places for those two settings. And better yet, you can even use the property sheet during design time to make the settings. (this is a "minor" issue, but I just perfer those settings in the markup as opposed to writing them in code for text/data settings).
At the end of the day? Just remember that golden rule: have that "test" for postback so you have a REAL first page load event code inside that if/then. In fact, you really can't even build a fnctional working web page if you break this rule. As noted, I count about 1-2 of my web pages out of 100's tht don't have that not postback code stub. It is quite much as important say compared to humans having to breathe air to function.
And why such a long post about this simple issue? Well on a near daily bases, both c# and vb.net questions are posted about how some combo box, grid view or just about anything else is "broken" and not working. And the answer 9 out of 10 times?
The developer forgot to use a Not IsPostBack code stub in their page load code.
If I was teaching asp.net, this would be the first lesson - ALWAYS use and consider the requirement for the Not IsPost back stub. You need that in 99% of your web pages. Or at the very least in ANY web page in which you have code to run on page load to setup grids, dropdowns, repeaters - don't matter what, you will NEED that code stub. So important, I often wonder if they should have create a even called first page load? It would have eliminated the daily posts and questions on SO that fail as a result of not heeding the above simple advice.
Edit: Now how to get selected value in code
Ok, now that we fixed up the code to setup the dropdown list, we now want to get in our code the value when the user makes a choice in the dropdown list.
You of course have code to fill the dropdown, BUT we also have to set autopostback = true for this dropdown.
So, say code to load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"SELECT ID, HotelName from tblHotels ORDER BY HotelName"
Using cmdSQL As SqlCommand = New SqlCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
cboHotels.DataSource = rstData
cboHotels.DataBind()
End Using
End Using
End Sub
And now the selected index changed event:
so, our debug output would then look like:
output:
combo selected value = 82
combo selected Text = Canadian Rocky Mountain Resorts
And as noted, make sure you set auto-post back true in the property sheet, or in the markup. The combo box for above in markup thus is this:
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="ID"
DataTextField="HotelName" AutoPostBack="True">
</asp:DropDownList>

ASP Email Validator

I have a textbox with multiple lines in it, each being an email address. I have a button that when clicked should read the emails from the textbox and validate that they are working emails (no spelling errors or anything). How would I go about doing something like this? For context the textbox is called emailBox
VB:
Protected Sub SaveButton(sender As Object, e As EventArgs)
End Sub
Thank you all so much in advanced!
Hi there I'm guessing by spelling errors you just mean valid email syntax.
You could use a regular expression. Like this:
Protected Sub SaveButton(sender As Object, e As EventArgs)
dim regexExpression As New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$")
'get an array of emails
dim emails = emailBox.text.Split(",")
'loop through emails checking each one
For Each email in emails
dim valid = regexExpression.IsMatch(email)
'do whatever with result
Next
End Sub
you will need to import this too, add it to the top of your file:
Imports System.Text.RegularExpressions
then the variable 'valid' will have a value of True or False that you can do what you like with.
I have edited my answer, assuming you can use a comma to separate your emails.
Edit 2: I can't guarantee the regex will work 100% correctly. Run your own tests, tweak it if need be or find/write another.

Creating a dynamic graphic in asp.net

I am busy creating a control in asp.net. The control consists of some text and an image. The image will be used to display a graph. The control gets the data for the graph by reading it from a database. It seems I have two options to display the graph in the image box. First, I can create a jpg from the data and save the file on the server. I can then load this file into the image box. I think this would cause a problem if various users try to access the site at the same time, so I don't think it is a good option. The other options is to create a file called output, that outputs the graph like this: objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
I can then display the image like this in my control: Image1.ImageUrl = "output.aspx"
The problem that I am facing is how do I get the data from my control to the output page? As far as I know it is too much data to pass as a parameter. If there is another better method of doing it, please let me know
Thanks
You can write the image content to the response of output.aspx. Something like this (taken from one of my existing GetImage pages:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strFilename As String
strFilename = Request.QueryString("filename")
Dim strPath As String = AppSettings("ProxyImageSavePath") & strFilename
Response.Clear()
Response.ContentType = "image/jpeg"
If Not IO.File.Exists(strPath) Then
'erm
Response.Write("file not found")
Else
Response.WriteFile(strPath)
End If
Response.End()
End Sub
Edit: I've just realised this may not be the solution you're looking for; Your webserver should be able to cache this though.
You need handlers. See in this article, Protecting Your Images, section "Creating the ImageHandler HTTP Handler", you'll find the code how to write the handler, so it outputs an image. You don't need all, it's only an example.
You also need to register the handler in the web.config.
To reference it Image1.ImageUrl = "handler.ashx?graphdata=xxxx". Use QueryString to get the data source to generate the graph.

Share Session between Page in Page to Page Request

My application is simple, I have 2 pages:
RSSProducer.aspx: A page that generates RSS (XML) feeds
RssConsumer.aspx: A page that retrieves the RSS feeds and displays it to the user in a repeater control. To do this I am using the System.Xml.XmlTextReader to fill a DataSet with tables based on the RSS-XML retrieved from the RSSProducePage. A table within the DataSet is bound to the repeater control.
For example, this is what I have in my RssConsumer.aspx page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("permittedToViewSomeDetail") = True
Dim url = "http://localhost/DevSite/RSSProducer.aspx"
Dim reader As New System.Xml.XmlTextReader(url)
Dim ds As New DataSet()
ds.ReadXml(reader)
myRssRepeater.DataSource = ds.Tables(2)
myRssRepeater.DataBind()
End Sub
My problem is that user-authorization details are stored in Session in the RssConsumer page that need to be accessed in the RSSProducer page (in this example it would be Session("permittedToViewSomeDetail") that I need to access in the RSSProducer page); however, the Session identifier is not common between the two. This means that I cannot access the authorization details in the RSSProducer page.
The reason for why is fairly clear to me:
User's browser makes a request to
the RssConsumer page
Server generates a Session ID (which is stored in a cookie) if
there is no existing Session
Identifer
The RSSConsumer requests the RSSProducer page...which generates a
new Session ID every time because no
session identifier is ever going to
be found.
I tried using cookieless session so that I could pass the SessionID via the URL to the RSSProducer page as an experiment but for some reason the XmlTextReader doesn't work well with this method (but the desired shared session does work).
I've hit a brick wall here.
Does anyone know how to share session between pages when one page makes a request to the other?
Thanks,
-Frinny
I ended up taking a different approach to solving this problem. I moved the code out of the RssProducer.aspx page into the RssConsumer.aspx page. I am now able to apply the correct authorization to the feature and it's actually more efficient this way because I don't need to produce/consume RSS-XML any more.
Thanks to everyone who took the time to help me with this.
-Frinny

DevExpress - Xtra Reports: VB.NET How to get current page number?

I've searched their site. I just want to find the page number in the vb script. I have a report header, and if it is on page #1 then I want a page break after.
This code should do the trick. It's the PrintOnPage event handler for a label in your Report Header.
Private Sub xrLabel1_PrintOnPage(ByVal sender As Object, ByVal e As DevExpress.XtraReports.UI.PrintOnPageEventArgs) Handles xrLabel1.PrintOnPage
If e.PageIndex > 0 Then
ReportHeader.PageBreak = DevExpress.XtraReports.UI.PageBreak.None
Else
ReportHeader.PageBreak = DevExpress.XtraReports.UI.PageBreak.AfterBand
End If
End Sub
Note that the PageIndex value is zero-indexed. Also, the page index is only available (as far as I know) in the PrintOnPageEventArgs, so this won't work in a Before/AfterPrint event.
See this knowledge base article for reference.

Resources