What does an empty input's value when using POST in asp? - asp-classic

I am using asp (JScript as my language) and working with getting data from a form that is sent using POST.
Specifically, I have a text input and I want to check if it was left empty. When leaving it empty, and including Response.Write(Request.form('opt2Dur')) in the called page, nothing prints (doesn't print null or undefined).
My thought was that it was just an empty string so I included this: Response.Write(Request.form('opt2Dur') === ''), however this printed false.
It will print true if I use Response.Write(Request.form('opt2Dur') == '') (== not ===). What is the true value that I can check against using ===? Or, in this case will it be sufficient to check with just ==?
Thanks for any help.

In scripting languages with "flexible" types and default values it's very easy to get confused with actual data types.
The actual type of each Request item (both QueryString and Form, it doesn't matter) is some sort of Array as it also supports more than one form element with the same name submitted to the ASP handler. It's mentioned in the documentation as well:
The Form collection is indexed by the names of the parameters in the request body. The value of Request.Form(element) is an array of all the values of element that occur in the request body.
Since the === also take into account type, it will return false in your case as array is not a string.
I wasn't able to find the exact actual type and reproduce it with local variable (it's not any plain array) so if you are keen on using the strict comparison operator, check the Count:
Response.Write(Request.Form('opt2Dur').Count === 0);

Related

Fo-dicom: How to add "empty, if unknown" integer string type 2 attribute

There is a tag which is of type 2 ("required, empty if unknown"), with value representation Integer String which I would like to leave empty. I have tried creating the attribute like so:
var attribute = new DicomIntegerString(DicomTag.SeriesNumber, string.Empty);
The storing of the file works. When I read the file again, the result of the following call returns null:
var result = dicomDataset.GetString(DicomTag.SeriesNumber); // <-- this is null
How can I set the element to be correctly "zero-length", or "empty, if unknown"?
Thanks.
As already mentioned in the comments, the code to set an empty string in the dataset is correct:
dataset.AddOrUpdate(new DicomIntegerString(DicomTag.SeriesNumber, string.Empty));
Note that you could also write a null value:
dataset.AddOrUpdate(new DicomIntegerString(DicomTag.SeriesNumber, (string)null));
Writing out the dataset will create an empty tag for SeriesNumber in exactly the same way in both cases, as both cases are equivalent in DICOM.
The code to read the tag back is also correct, and the fact that it returns null is due to this equivalence, which creates an ambiguity in the interpretation of an empty string tag in DICOM. As the number of values in a DICOM string tag is defined only by the string itself (and the number of backslashes it contains), there is no difference between a tag with no values (which usually is represented by a null value), and a tag with an empty string (which would be represented by a "" value). For consistence with other tags it makes sense to return null for a tag with VM 0 - for non-string VRs there is no ambiguity here, as the length of a value is defined. For string values it could also make sense to return an empty string instead - both approaches have pros and cons, so in the end it is a design decision of the library creators.
In fo-dicom, it is probably best to handle both cases (e.g. using something like string.IsNullOrEmpty). If you read the value from a file dataset, you always get null, but if you are writing an empty string to a tag in a dataset (first version shown above) and read it back, you will get the same empty string back.
As an aside: in pydicom (the common Python DICOM library) there was a discussion about this same design decision, and in the end a configuration entry was added that defines the behavior (e.g. return None or an empty string for such values).

In gatling, how do I validate the value of a string extracted via the css check?

I'm writing a Gatling simulation, and I want to verify both that a certain element exists, and that the content of one of its attributes starts with a certain substring. E.g.:
val scn: ScenarioBuilder = scenario("BasicSimulation")
.exec(http("request_1")
.get("/path/to/resource")
.check(
status.is(200),
css("form#name", "action").ofType[String].startsWith(BASE_URL).saveAs("next_url")))
Now, when I add the startsWith above, the compiler reports an error that says startsWith is not a member of io.gatling.http.check.body.HttpBodyCssCheckBuilder[String]. If I leave the startsWith out, then everything works just fine. I know that the expected form element is there, but I cant confirm that its #action attribute starts with the correct base.
How can I confirm that the attribute start with a certain substring?
Refer this https://gatling.io/docs/2.3/general/scenario/
I have copied the below from there but it is a session function and will work like below :-
doIf(session => session("myKey").as[String].startsWith("admin")) { // executed if the session value stored in "myKey" starts with "admin" exec(http("if true").get("..."))}
I just had the same problem. I guess one option is to use a validator, but I'm not sure how if you can declare one on the fly to validate against your BASE_URL (the documentation doesn't really give any examples). You can use transform and is.
Could look like this:
css("form#name", "action").transform(_.startsWith(BASE_URL)).is(true)
If you also want to include the saveAs call in one go you could probably also do something like this:
css("form#name", "action").transform(_.substring(0, BASE_URL.length)).is(BASE_URL).saveAs
But that's harder to read. Also I'm not sure what happens when substring throws an exception (like IndexOutOfBounds).

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.

return domain objects from grails constraint validation

Is it possible to write your own validator in grails that will return a valid object?
Something like:
static constraints = {
name(validator: {val, obj ->
if (Drink.findByName(val)) return [Drink.findByName(val)]
})
}
In other words - if the Drink already exists in the DB, just return the existing one when someone does a
new Drink("Coke")
and coke is already in the database
You cannot do this with a custom validator. It's not really what it was meant for. From the Grails Reference:
The closure can return:
null or true to indicate that the value is valid
false to indicate an invalid value and use the default message code
a string to indicate the error code to append to the "classname.propertName." string used to resolve the error message. If a field specific message cannot be resolved, the error code itself will be resolved allowing for global error messages.
a list containing a string as above, and then any number of arguments following it, which can be used as formatted message arguments indexed at 3 onwards. See grails-app/i18n/message.properties to see how the default error message codes use the arguments.
An alternative might be to just create a service method that 1) looks for the domain and returns it if it exists, 2) otherwise, saves the domain and returns it.
There's probably a more elegant alternative. Regardless, Grails' constraints mechanism isn't (and shouldn't be) capable of this.
Not sure if you can do this from inside the validator, but:
Drink d = Drink.findOrSaveWhere(name: 'Smooth Drink', alcoholLevel: '4.5')

Cleanest way to hide password input fields?

We have some error reporting code that, when an unhandled exception occurs, we send everything over in an email to our groups. This is great except if an unhandled exception occurs on a page with a password field then it's sent over as plain text.
Is there a way to iterate through Request.Form and figure out which item(s) are passwords? This is done at a low level so we can't look for specific controls.
Naturally, we could check to see what type the input box is but I'm not sure if that's the cleanest way. Advice?
Use a whitelist of field names that you want to email.
There could be hundreds of field names that get POSTed to your server. And password isn't the only field that is sensitive. Depending on your application, there could be other things that should be treated with a little respect.
So, make a list of field names that will assist in you in debugging. These are typically unique identifiers / database keys and such. If you have any parameter names in this list, you can include it in the email.
I've suggested a different solution earlier, but I thought you were going to handle this on the client side. Following your comments I now understand that you need to take care of this on the server side. There may be a way for you to do it, which is not really elegant, but it should work:
Add to all pages a script that collects all password field names into a new client-generated field, like so:
function collectPasswordFields() {
var inputs = document.getElementsByTagName('input'), list = [];
for (var i = 0; i < inputs.length; ++i)
if (inputs[i].type == 'password') list.push(inputs[i].name);
var field = document.createElement('input');
field.name = '__password_fields';
field.value = list.join(',');
document.getElementsByTagName('form')[0].appendChild(field);
}
Then intercept the additional field in the server-side error handler, and remove the named fields from the email.
Can something like this work for you?
The cleanest way is to check the type attribute of the input element.
The HTML5 specification has this to say about input type=password:
The input element with a type attribute whose value is "password" represents a one-line plain-text edit control for entering a password.
Data type: Text with no line breaks (sensitive information)
Control type: Text field that obscures data entry
This is a mandatory requirement from all User Agent implmentations, and it has been so since HTML 2. So this is indeed the cleanest way to do what you want.
If you want to do it on the client side (you talked about sending the data to the server) then it is relatively easy:
function hidePasswords() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i)
if (inputs[i].type == 'password') input[i].value = '*****';
}
As Jerome already pointed out in the comments, just keep track of the names of your password input fields and filter them before sending the error/exception report. This is the best solution as the type of the input field is not submitted.
A few solutions, though I'm not sure how bright any of them is:
1) Maintain in the page a List of input control IDs that are passwords, pass this list to the exception handler with the expectation to ignore these fields.
2) Keep a resource file in the website that lists a page name, a field id and have the exception handler check against this resource file (may not work if the exception is related to the ResourceManager)
3) Keep a database table as with idea 2. Same problems exist.

Resources