Passing a parameter through server.execute? - asp-classic

It is possible to pass a parameter through server.execute?
Fx. I have in my site.asp an IF-scenario where I need functions.asp?a=something&id=123 executed. Is this possible?!
On site.asp:
dim id
id = 123
if b = "hi" then
server.execute("functions.asp?a=something&id=" & id)
else
response.write("No way dude")
end if
On functions.asp
a = request.querystring("a")
id = request.querystring("id")
if a = "something" and cint(id) > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if

You can't use querystring in Server.Execute, it's clearly mentioned in the official documentation.
What you can do is much better: you can directly access the variable id defined in site.asp inside functions.asp, and you can also declare and set another variable, a:
--site.asp:
dim id, a
id = 123
a = "something"
server.execute("functions.asp")
--functions.asp
if a = "something" and cint(id) > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if
As it creates whole new "scripting environment" the executed file won't have access to the calling code properties, methods or variables, only to the global Request parameters, Session etc.
With this in mind, I fear the most simple way around is using Session variable to pass the value between pages:
Session("id") = 123
Session("a") = "something"
And then:
if Session("a") = "something" and Session("id") > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if

This question may be old and resolved, but the best answer doesn't mention everything, and there is information clearly posted on Microsoft.com about it:
Server.Execute Method
The following collections and properties are available to the executed ASP page:
Application variables, even if they are set in the calling page.
Session properties, even if they are set in the calling page.
Server variables and properties, even if they are set in the calling page.
Request collections and properties, even if they are set in the calling page. This includes Form and QueryString data passed to the calling page.
Response collections and properties. The executed .asp file may modify HTTP headers. However, as with any .asp file, if the executed .asp file attempts to modify HTTP headers after it sends a response to the client, it generates an error.
So as you can see, there are 5 ways Microsoft suggests to pass variables through to a Server.Execute method. Before I saw this on Microsoft, the preferred method was Session, as the best answer suggests, since I saw this before the info on Microsoft.com. But after noticing that QueryStrings can be passed from the previous page, I would have to say this beats using Session for passing values. Session would be needed if your application required you adding variables to the executing page.
But passing variables, I would say QueryStrings, and it's easy to apply if your application allows the flexibility. I'm sure you know how to already use querystrings, but in the sense of using it for a Server.Execute method, you can simply do this:
Consider having ASP1.asp and ASP2.asp:
ASP1.asp includes:
Server.Execute("ASP2.asp")
ASP2.asp includes:
Response.Write Request("id")
When you call ASP1.asp?id=123
You will notice that ASP2.asp also see's the same Querystring passed to ASP1.asp, so it would write 123 on the response of ASP1.asp.
That's much less complicated than using a Session for the task.

In short: YES, you can use QueryString values in conjunction with Server.Execute within an ASP.NET page or application.
You can pass dynamic variables in a QueryString argument assembled in the executing ASPX page (page1.aspx), as follows:
Dim intExample1 As Int = 22
Dim strExample2 As String = "hello world"
Server.Execute("page2.aspx?number=" & intExample1 & "&string=" & Server.UrlEncode(strExample2))
In this example, page2.aspx can then reference and use the following values:
Request.QueryString("number")
Request.QueryString("string")

Why not to use #include instead of server.execute?
I looked for a difference and found that in this particular case, using #include is the best solution:
https://en.wikibooks.org/wiki/Active_Server_Pages/Server-Side_Includes#What_it_Does
You need some variables defined in parent page to be used in child, so your solution could be:
dim id, a
id = 123
a = "something"
if b = "hi" then
<!--#include file="functions.asp" -->
else
response.write("No way dude")
end if
On functions.asp
if a = "something" and cint(id) > 100 then
response.write("Yes way dude")
else
response.write("No way dude")
end if
Advantages:
Simply act as it was the same page.
Use of disposal variables instead of Session variables.
Don't show internal variables in main URL.

Related

Access request after upload (ASP classic)

So, as I figured out, when I have a form with enctype="multipart/form-data" and I upload a file, I can no longer access the object request. The following error is shown:
Cannot use the generic Request collection after calling BinaryRead.
After checking some resources, I stumpled upon a statement, which says: "This is by design". Well, okay, not here to judge about design-decisions.
To give you a quick overview, let me walk you through the code:
if request("todo") = "add" then
Set Form = New ASPForm
category = request("category")
title = request("title")
if len(Form("upload_file").FileName) > 0 then
filename = Form("upload_file").FileName
DestinationPath = Server.mapPath("personal/allrounder/dokumente/")
Form.Files.Save DestinationPath
end if
end if
Nothing too special here so far. Later however, when I try to access my request object, the error mentioned above occures:
<% if request("todo") = "new" then %>
...
My question now, how to get rid of it or fix this. I don't want to open the upload in a popup if there is another way around. This is the only solution I could think off.
Perfectly would be an object, which checks Form and request. Alternatively maybe a check at the top of the file, which object I have to use?
Thanks for any suggestions.
There used to be a very popular ASP class/component that solved ASP file uploads. The site for that component has been taken down, but the code is mirrored here:
https://github.com/romuloalves/free-asp-upload
You can include this ASP page on your own page, and on your page instantiate the class to get access to the files in your form, but also to the form variables. Here is a piece of example code (Upload.Form accesses the form fields):
Dim uploadsDir : uploadsDir = server.mapPath(".") ' whatever you want
Dim Upload, ks, fileKey, mailto
Set Upload = New FreeASPUpload
call Upload.Save(uploadsDir)
ks = Upload.UploadedFiles.keys
for each fileKey in ks
Response.write(fileKey & " : " & Upload.UploadedFiles(fileKey).FileName & "<br/>")
next
mailto = Upload.form("mailTo")
Set Upload = Nothing
If you want to stick to your own implementation, you can probably figure out how to get to the form variables in a multipart/form-data encoded data stream by having a look at the code they use to do so.

Execute VB Script on page_load

I am having VB Script in ASPX page.I need to use that Script in codeBehind in Page _load with in a For loop,for each iteration.
My Code is :-
(.ASPX Page with VB Script. )
<script type="text/vbscript" language="vbscript" >
sub wordit()
'Opens Word application and does some process
end sub
</script>
VB Code Behind Part:-
For i As Integer = 1 To colSelRowIndex
CheckboxTemplateId = colSelRowKeys(i).ToString 'I get the ID from here
ViewState("TemplateID") = CheckboxTemplateId 'I need to send the value to the sub routines
hen()'sub
den()'sub
cs.RegisterStartupScript(cstype, csname1 & i, "wordit();", True)
Next
I need to open a word doc for an ID and another document for another ID from the loop.
Try this:
For i As Integer = 1 To 10
cs.RegisterStartupScript(cstype, csname1 & i, "wordit();", True)
Next
That second argument in that function call is looking for a unique key. This is a feature, to prevent accidentally programmatically adding the same script more than once. If you want to do it on purpose, you need a unique key each time.
But that you want to do this at all indicates a possible fundamental misunderstanding about what's going on. While your server code (including Page_Load) is running, your client page in the web browser doesn't exist. The purpose of the server code is always to generate an html response to web request. The server code can never directly manipulate a page DOM.
Obviously this is true for a first request to a page in session: the server must first generate the initial page to send the client. But even on subsequent postbacks, the browser will destroy the prior instance of a page. The server must rebuild the entire page from scratch. Every. Time. While this happens, the page you're looking at in your browser window is only a sort of after-image. The browser has already destroyed any prior DOM, and is waiting for the server to supply a whole new set of HTML.
I also wonder at your use of vbscript, rather than javascript. Using vbscript pretty much guarantees you're page will only work with Internet Explorer.

How to check if a POST submitted field exists in VBScript?

After a form is submitted, how does one check server-side if a particular field exists? For example:
If [Exists] Request("FieldName") Then
...
End If
If Request("FieldName").Count > 0 Then
...
End If
Or, for short:
If Request("FieldName").Count Then
...
End If
Background:
The Request collection is magic, in so far as it does not throw an error when you try to access a key that was not part of the request - but the .Count will be 0 for non-existing keys.
In a URL-encoded query string it's legal to send keys that don't have a value, like foo&bar&baz
It's also legal to send the same key multiple times, i.e. multiple values per key, like foo=value1&foo=value2.
Therefore, the reliable way to determine if a key has been sent by the client is to count how many times the client has sent it.
A special case of this test is checking whether there was a non-empty value for that key (If Request("FieldName") > ""). This may or may not be what you want in the end; just be aware that the underlying behavior of query strings is broader than that.
Check if it's not empty. There are a few different ways, but the one I've seen more frequently used is along the lines of:
If Request("FieldName") <> "" Then
'etc.
End If
I usually explicitly check the Form and QueryString collections with some variation of one of the code below if I may be getting the variable from one or the other depending on context:
Select Case True
Case Request.Form("FieldName") <> ""
'Run if the Form isn't empty
Case Request.QueryString("FieldName") <> ""
'Run if the QueryString isn't empty
Case Else
'Set a predefined default if they're both empty
End Select
Or a nested If ... Then:
If Request.Form("FieldName") <> "" Then
'Run if the Form isn't empty
ElseIf Request.QueryString("FieldName") <> "" Then
'Run if the QueryString isn't empty
Else
'Set a predefined default if they're both empty
End If
If I know exactly which collection it's coming from, I'll check that collection specifically. The reason is that I want to make sure it is pulling what I expect from where I expect it to come from. I don't want someone overriding a Form value by sending something in the QueryString when I'm not expecting it.
From MSDN:
If the specified variable is not in one of the preceding five
collections, the Request object returns EMPTY.
All variables can be accessed directly by calling Request(variable)
without the collection name. In this case, the Web server searches the
collections in the following order:
QueryString
Form
Cookies
ClientCertificate
ServerVariables
If a variable with the same name exists in more than one collection,
the Request object returns the first instance that the object
encounters.
It is strongly recommended that when referring to members of a
collection the full name be used. For example, rather than
Request.("AUTH_USER") use Request.ServerVariables("AUTH_USER"). This
allows the server to locate the item more quickly.
To check if the parameter was present (without caring about its value) it is also possible to write:
fieldValue = Request("FieldName")
if Not IsEmpty(fieldValue) ...
One advantage over Count method above is, that you can test the variable, without referring to the field name again.
Advantage over testing for "" is that if you pass &FieldName without assigning value, test for "" will yield true, but IsEmpty returns false.
Edit: Turns out this is not reliable in IIS.
For the url with ?param alone, or ?param=&param2, IsEmpty(param) returns false, but
For the url with ?param&param2, IsEmpty(param) weirdly returns true ...
I usually check the value of the SUBMIT button. If it was clicked, it's value is posted along with the form data. So, even if all your form data is blank, the submit button's value will not be. And if the submit button's value is blank, then it wasn't clicked.
if request("btn_Submit") <> "" Then
response.write "form was submitted"
end if
This is more difficult if you are using a javascript form.submit() call, in which case I usually opt for the hidden field.

Pass parameter from 1 page to another using post method

I have a page "Demo.aspx". I need to set some parameters using post method and redirect the page to "DemoTest.aspx".
Is there any way to set parameters in post method in asp.net? I don't want to set "Querystring" due to security propose.
Also I need server side code for this. I am not able to use "Javascript" or "Jquery" for the same.
Here is some more description for the same.
Right now I am using Response.Redirect("www.ABC.Com/DemoTest.aspx?P1=2"). So the page is simply redirect to the given URL.
Now I don't want to pass that "P1" in "Querystring". Instead of query string I want to use Post method.
Please note that redirection page is not in my own application. So I cant maintain session or "Viewstate".
Thanks in advance.
Use a session variable and response.redirect to the next page.
Session["MyVariable"] = "someThing";
Response.Redirect("DemoTest.aspx");
The value stored in Session variables will be accessible across application.
you can store in session like this :
Session["id"] = "anyID";
To get values On another page you need to write
string id = Convert.ToString(Session["Id"]);
However
By default, in .NET pages post() do the things automatically.
You will need to do sumthing like this:
Server.Transfer("DemoTest.aspx", True)

Check if an Object exists in VBScript

I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago.
I have an array of imagefile paths, like so:
dim banners, arrKeys, i
set banners=CreateObject("Scripting.Dictionary")
banners.Add "banner1.jpg", "http://www.somelink.com"
banners.Add "banner2.jpg", "http://www.somelink.com"
banners.Add "banner3.jpg", "http://www.somelink.com"
This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages).
If Not banners Is Nothing then
' then loop through the Dictionary and make a list of image links
End if
The problem is that if banners is not instantiated on the page (it's not on all pages), I get a Can't find object error
What's the proper way to check if an object exists in VB Script?
#Atømix: Replace
If Not banners Is Nothing then
and use
If IsObject(banners) Then
Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.
#Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-)
IsObject could work, but IsEmpty might be a better option - it is specifically intended to check if a variable exists or has been initialised.
To summarize:
IsEmpty(var) will test if a variable exists (without Object Explicit), or is initialised
IsNull(var) will test if a variable has been assigned to Null
var Is Nothing will test if a variable has been Set to Nothing, but will throw an error if you try it on something that isn't an object
IsObject(var) will test if a variable is an object (and will apparently still return False if var is Empty).
If a variable is declared, but not initialized, its value will be Empty, which you can check for with the IsEmpty() function:
Dim banners
If IsEmpty(banners) Then
Response.Write "Yes"
Else
Response.Write "No"
End If
' Should result in "Yes" being written
banners will only be equal to Nothing if you explicitly assign it that value with Set banners = Nothing.
You will have problems, though, with this technique if you have Option Explicit turned on (which is the recommendation, but isn't always the case). In that case, if banners hasn't been Dimed and you try to test IsEmpty(banners), you will get a runtime error. If you don't have Option Explicit on, you shouldn't have any problems.
edit: I just saw this related question and answer which might help, too.
Somewhat related is IsMissing() to test if an optional parameter was passed, in this case an object, like this:
Sub FooBar(Optional oDoc As Object)
'if parameter is missing then simulate it
If IsMissing(oDoc) Then Dim oDoc as Object: oDoc = something
...
You need to have at least dim banners on every page.
Don't you have a head.asp or something included on every page?
Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered.
The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here:
Is there any way to check to see if a VBScript function is defined?

Resources