How to check if form is an input file field? Asp Classic - asp-classic

I have some code that checks input values before I insert it into the db. And it works as it should, it checks all form inputs, but I would like it to exclude all the file upload inputs, so it doesn´t check the values of file inputs when I upload an image. But I don´t know how to make it work, so any input really appreciated. Thanks.
This is what I have now.
Dim BlackList, ErrorPage
BlackList = Array("#","$","%","^","&","|",_
"<",">","'","""","(",")",_
"--", "/*", "*/", "##",_
"cursor","exec","execute",_
"nchar", "varchar", "nvarchar", "iframe", "char", "alter", "begin", "cast", "create", "insert","delete", "drop", "table"_
)
Function CheckStringForSQL(str,varType)
On Error Resume Next
Dim lstr
' If the string is empty, return false that means pass
If ( IsEmpty(str) ) Then
CheckStringForSQL = false
Exit Function
ElseIf ( StrComp(str, "") = 0 ) Then
CheckStringForSQL = false
Exit Function
End If
lstr = LCase(str)
' Check if the string contains any patterns in our black list
For Each s in BlackList
If(IsExceptionList(s,varType)=False) then
If ( InStr (lstr, s) <> 0 ) Then
CheckStringForSQL = true
Exit Function
End If
End If
Next
CheckStringForSQL = false
End Function
CookieExceptionList = Array("""","(",")","!")
Function IsExceptionList(str,varType)
If(varType="cookie") then
For Each item in CookieExceptionList
If(item=str) then
IsExceptionList=True
Exit Function
End If
Next
End If
IsExceptionList=False
End Function
--SO HERE I NEED TO CHECK IF IT IS A FILE INPUT, AND IF SO, NOT RUN THE BELOW--
For Each s in Request.form
If ( CheckStringForSQL(Request.form(s),"form") ) Then
feltext="Fel"
End If
Next

Related

How i can add a catch block inside the for each block ( in progress 4gl) when the error is occurs i want to move to the next records

I have tried
DO ON ERROR UNDO , THROW:
FOR EACH ttFileData NO-LOCK:
CREATE ttCustomerDetails.
ASSIGN
ttCustomerDetails.ttcustmId = INTEGER (ENTRY(2 , ttFileData.ttLine))
ttCustomerDetails.ttfirstName = ENTRY(3 , ttFileData.ttLine)
ttCustomerDetails.ttgender = ENTRY(6 , ttFileData.ttLine)
ttCustomerDetails.ttsalary = DECIMAL (ENTRY( 13 , ttFileData.ttLine))
ttCustomerDetails.ttcountry = ENTRY(5 , ttFileData.ttLine)
ttCustomerDetails.ttage = INTEGER ( ENTRY (7 , ttFileData.ttLine))
ttCustomerDetails.ttTenure = INTEGER (ENTRY (8 , ttFileData.ttLine))
ttCustomerDetails.ttDOB = obj1custmomerDetail:calculateDOB(INPUT ttCustomerDetails.ttcustmId , INPUT TABLE ttCustomerDetails)
ttCustomerDetails.ttemail = obj1custmomerDetail:createEMAIL(INPUT ttCustomerDetails.ttcustmId , INPUT TABLE ttCustomerDetails).
CATCH e AS Progress.Lang.Error:
MESSAGE "error:" e:GetMessage(1) VIEW-AS ALERT-BOX.
FIND NEXT ttFileData.
END CATCH.
END.
END.
The error I'm getting is
FIND cannot be processed for a FOR EACH mode record.
You don't need the
FIND NEXT ttFileData.
inside the CATCH block. The CATCH block handles the error and the FOR EACH loop will just move to the next iteration - which moves to the next record.

lua recursive function gets true and then false within a false

not sure what is happening. i have a recursive function getting data from a table. and it's finds an key to be true and then false twice within it being false..
i am wanting to check the isActive boolean and if it's false return false. if it's true then continue the script.
DUMMY_DATA
local DummyData = {
data = {
['id'] = 34523456,
['question'] = 'whats milk?',
['isActive'] = true,
['questionCountdownTimerInSeconds'] = (60),
}
}
RECURSIVE
function FindQuestionInfo(Object)
local Data = {
['id'] = '',
['question'] = '',
['isActive'] = true or false,
['questionCountdownTimerInSeconds'] = (0),
}
for index, child in pairs(Object) do
local ChildIsTable = type(child) == 'table'
if not ChildIsTable then
local isActive = index == 'isActive'
local isId = index == 'id'
local isQuestion = index == 'question'
local isQuestionCountDDownTImerInSeconds = index == 'questionCountdownTimerInSeconds'
if isQuestion then
Data['question'] = child
end
if isId then
Data['id'] = child
end
end
if ChildIsTable then
local FoundItem = FindQuestionInfo(child)
if FoundItem then
return FoundItem
end
end
end
return Data
end
PRINT
Your code doesn't make too much sense. I'm not even sure what you want to achieve with it.
I'll just mention a few issues:
['isActive'] = true or false
As Nifim already pointed out in his comment true or false equals true. Sou you could simply do
['isActive'] = true
You don't need parenthesis around numbers as in ['questionCountdownTimerInSeconds'] = (0)
You don't mention how you use this code. I assume you call FindQuestionInfo(DummyData)
So let's run your code. First you define Data
local Data = {
['id'] = '',
['question'] = '',
['isActive'] = true or false,
['questionCountdownTimerInSeconds'] = (0),
}
Then you traverse over the table Object with a generic for loop and the pairs iterator. Assuming Object is DummyData this will give us a key value pair of DummyData each cycle.
First you check if child (our value) is a table. I don't see how it can be a table with the provided code. If it is not a table you create various booleans.
local isActive = index == 'isActive'
local isId = index == 'id'
local isQuestion = index == 'question'
local isQuestionCountDDownTImerInSeconds = index == 'questionCountdownTimerInSeconds'
And then you assign values conditionally.
if isQuestion then
Data['question'] = child
end
if isId then
Data['id'] = child
end
So only if index equals one of the keys you assign the same table field from Object to Data.
This whole loop doesn't make sense. If you want to assign values from one table to another you simply assign them. You don't traverse over the entire table until you find the right key to assign.
Aside from your isTable condition which seems to be always false you can replace that for loop by
Data.isQuestion = Object.isQuestion and Object.isQuestion or Data.isQuestion
Data.isId = Object.isId and Object.isId or Data.isId
Because you simply assign those values if they exist in Object.
Then there is this section which I cannot make sense of as I don't see how child will ever be a table:
if ChildIsTable then
local FoundItem = FindQuestionInfo(child)
if FoundItem then
return FoundItem
end
end
Also FindQuestionInfo(child) always returns Data so the condition
if FoundItem then
return FoundItem
end
is not necessary.
So unless your Object will have a table inside that you didn't show in your example I don't see any reason to have this code at all. Especially not the recursive part.
You only copy parts of Object into a new table Data.
I cannot make sense of your problem description either.
I'm assuming you're asking about a xy-problem here. So I suggest you ask a new question about the actual problem you're trying to solve rather than about how to fix this code.

Place and retrieve multidimensional array in Session

As the title says, I need to store my Array in a Session and later on retrieve it.
Here is my Array:
Dim arrStatus(,) As Object =
New Object(,) {
{DHID, btnEditDepHead, ddlHeads, lblDH, DepHeadStatus, DepHeadDateChanged}, _
{MMID, btnEditMM, ddlMM, lblMM, MMStatus, MMDateChanged}, _
{AA1ID, btnEditAA1, ddlAA1, lblAA1, AA1Status, AddApp1DateChanged}, _
{AA2ID, btnEditAA2, ddlAA2, lblAA2, AA2Status, AddApp2DateChanged}, _
{AA3ID, btnEditAA3, ddlAA3, lblAA3, AA3Status, AddApp3DateChanged}, _
{EXECID, btnEditExec, ddlExec, lblEXEC, ExecStatus, ExecDateChanged}, _
{EVPID, btnEditEVP, ddlEVP, lblEVP, EVPStatus, EVPDateChanged}, _
{DMID, btnEditDM, ddlDM, lblDM, DMStatus, DMDateChanged}
}
Session("arrStatus") = arrStatus
Code in retrieval
Dim arrStatus As Object
arrStatus = Session("arrStatus")
For i As Integer = 0 To arrStatus.GetUpperBound(0)
arrStatus(i, 3).visible = True
arrStatus(i, 4).visible = True
arrStatus(i, 5).visible = True
Next
But when i run this code, my objects does not do what it should do. It does not visible = true
I need this code for multiple buttons and I need to place it inside session to avoid code repetition. Ive done a research already but I only saw simple arrays.

Printing the results from a select query with Genie

I have created the database in SQL lite and improved the little program to handle it (list, add, remove records). At this point I am trying to list the contents from the database using the prepared statement step() function. However, I can't iterate over the rows and columns on the database.
I suspect that the reason for that is that I am not handling the statement appropriately in this line:
stmt:Sqlite.Statement = null
If that is the case, how to pass the statement from the main (init) function to the children function?
This is the entire code so far:
// Trying to do a cookbook program
// raw_imput for Genie included, compile with valac --pkg sqlite3 cookbook.gs
[indent=4]
uses Sqlite
def raw_input (query:string = ""):string
stdout.printf ("%s", query)
return stdin.read_line ()
init
db : Sqlite.Database? = null
if (Sqlite.Database.open ("cookbook.db3", out db) != Sqlite.OK)
stderr.printf ("Error: %d: %s \n", db.errcode (), db.errmsg ())
Process.exit (-1)
loop:bool = true
while loop = true
print "==================================================="
print " RECIPE DATABASE "
print " 1 - Show All Recipes"
print " 2 - Search for a recipe"
print " 3 - Show a Recipe"
print " 4 - Delete a recipe"
print " 5 - Add a recipe"
print " 6 - Print a recipe"
print " 0 - Exit"
print "==================================================="
response:string = raw_input("Enter a selection -> ")
if response == "1" // Show All Recipes
PrintAllRecipes()
else if response is "2" // Search for a recipe
pass
else if response is "3" //Show a Recipe
pass
else if response is "4"//Delete a recipe
pass
else if response is "5" //Add a recipe
pass
else if response is "6" //Print a recipe
pass
else if response is "0" //Exit
print "Goodbye"
Process.exit (-1)
else
print "Unrecognized command. Try again."
def PrintAllRecipes ()
print "%-5s%-30s%-20s%-30s", "Item", "Name", "Serves", "Source"
print "--------------------------------------------------------------------------------------"
stmt:Sqlite.Statement = null
param_position:int = stmt.bind_parameter_index ("$UID")
//assert (param_position > 0)
stmt.bind_int (param_position, 1)
cols:int = stmt.column_count ()
while stmt.step () == Sqlite.ROW
for i:int = 0 to cols
i++
col_name:string = stmt.column_name (i)
val:string = stmt.column_text (i)
type_id:int = stmt.column_type (i)
stdout.printf ("column: %s\n", col_name)
stdout.printf ("value: %s\n", val)
stdout.printf ("type: %d\n", type_id)
/* while stmt.step () == Sqlite.ROW
col_item:string = stmt.column_name (1)
col_name:string = stmt.column_name (2)
col_serves:string = stmt.column_name (3)
col_source:string = stmt.column_name (4)
print "%-5s%-30s%-20s%-30s", col_item, col_name, col_serves, col_source */
Extra questions are:
Does the definitions of functions should come before or after init? I have noticed that they wouldn't be called if I left all of them after init. But by leaving raw_input in the beginning the error disappeared.
I was trying to define PrintAllRecipes() within a class, for didactic reasons. But I ended up making it "invisible" to the main routine.
Many thanks,
Yes, you need to assign a prepared statement, not null, to stmt. For example:
// Trying to do a cookbook program
// raw_input for Genie included, compile with
// valac --pkg sqlite3 --pkg gee-0.8 cookbook.gs
[indent=4]
uses Sqlite
init
db:Database
if (Database.open ("cookbook.db3", out db) != OK)
stderr.printf ("Error: %d: %s \n", db.errcode (), db.errmsg ())
Process.exit (-1)
while true
response:string = UserInterface.get_input_from_menu()
if response is "1" // Show All Recipes
PrintAllRecipes( db )
else if response is "2" // Search for a recipe
pass
else if response is "3" //Show a Recipe
pass
else if response is "4"//Delete a recipe
pass
else if response is "5" //Add a recipe
pass
else if response is "6" //Print a recipe
pass
else if response is "0" //Exit
print "Goodbye"
break
else
print "Unrecognized command. Try again."
namespace UserInterface
def get_input_from_menu():string
show_menu()
return raw_input("Enter a selection -> ")
def raw_input (query:string = ""):string
stdout.printf ("%s", query)
return stdin.read_line ()
def show_menu()
print """===================================================
RECIPE DATABASE
1 - Show All Recipes
2 - Search for a recipe
3 - Show a Recipe
4 - Delete a recipe
5 - Add a recipe
6 - Print a recipe
0 - Exit
==================================================="""
namespace PreparedStatements
def select_all( db:Database ):Statement
statement:Statement
db.prepare_v2( """
select name, servings as serves, source from Recipes
""", -1, out statement )
return statement
def PrintAllRecipes ( db:Database )
print "%-5s%-30s%-20s%-30s", "Item", "Name", "Serves", "Source"
print "--------------------------------------------------------------------------------------"
stmt:Statement = PreparedStatements.select_all( db )
cols:int = stmt.column_count ()
var row = new dict of string, string
item:int = 1
while stmt.step() == ROW
for i:int = 0 to (cols - 1)
row[ stmt.column_name( i ) ] = stmt.column_text( i )
stdout.printf( "%-5s", item.to_string( "%03i" ))
stdout.printf( "%-30s", row[ "name" ])
stdout.printf( "%-20s", row[ "serves" ])
stdout.printf( "%-30s\n", row[ "source" ])
item++
A few pointers
Generally you want to avoid assigning null. null is no value. For example a boolean can either be true or false and nothing else, but a variable that can have no value makes things more complicated.
a:bool? = null
if a == null
print "I'm a boolean variable, but I am neither true nor false???"
If you are looking to declare a variable in Genie before assigning a value, for example when calling a function with an out parameter, don't assign anything. I have changed db:Database to show this
Process.exit( -1 ) should probably be used sparingly and really only for error conditions that you want to signal to a calling command line script. I don't think a user selected exit from the program is such an error condition, so I have changed Process.exit( -1 ) to break for that
The definition of functions doesn't matter whether it is before or after init, I prefer to put them after so the first function that is called, i.e. init, is at the top and easy to read
A class is a data type and yes, it can have functions, but usually you need some data defined in the class and the function is written to act on that data. A function in a class is often called a 'method' and in the past with object oriented programming classes were defined to group methods together. These methods had no data to act on and are defined as 'static' methods. The modern practise is to mainly use static methods for creating more complex object constructors, look up 'factory' methods and creational design patterns. Instead to group functions, and other syntax, we use namespaces. I have used a couple of namespaces in the example. Usually a namespace is given its own file or files. If you are thinking of splitting your Genie project into more source files then take a look at https://wiki.gnome.org/Projects/Genie#A_Simple_Build_Script
A primary key should be internal to the database and would not be presented to a user, only a database administrator would be interested in such things. So I have changed 'item' in the output to be a count of the number of entries displayed
Genie and Vala bind the SQLite C interface. If you need more details on a particular function take a look at C-language Interface Specification for SQLite

Get HTTP response body as string (BubbleWrap for RubyMotion)

Using RubyMotion (for the first time!), I want to use Twitter's search API to retrieve some recent tweets for some users so have put together the class below.
The value of tweets is always an empty array. I suspect that BW::HTTP.get(url) spawns its own thread which is causing the issue.
Really, I just want twitter_search_results to return response.body.to_str but I am not sure how to do this.
How do I use RubyMotion (or BubbleWrap) to put an array of Tweet objects into my UIViewController?
class TweetsController
def initialize
#twitter_accounts = %w(dhh google)
#tweets = []
end
def tweets
twitter_search_results
puts #tweets.count
#tweets
end
def create_tweets(response)
BW::JSON.parse(response)["results"].each do |result|
#tweets << Tweet.new(result)
end
end
def twitter_search_results
query = #twitter_accounts.map{ |account| "from:#{account}" }.join(" OR ")
url = "http://search.twitter.com/search.json?q=#{query}"
BW::HTTP.get(url) do |response|
create_tweets(response.body.to_str)
end
end
end
class TwitterViewController < UIViewController
def viewDidLoad
super
self.view.backgroundColor = UIColor.blueColor
#table = UITableView.alloc.initWithFrame(self.view.bounds)
self.view.addSubview #table
#table.dataSource = self
#tweets_controller = TweetsController.new
end
def initWithNibName(name, bundle: bundle)
super
self.tabBarItem = UITabBarItem.alloc.initWithTitle(
"Twitter",
image: UIImage.imageNamed('twitter.png'),
tag: 1)
self
end
def tableView(tableView, numberOfRowsInSection: section)
#tweets_controller.tweets.length
end
def tableView(tableView, cellForRowAtIndexPath: indexPath)
#reuse_id = "Tweet"
cell = UITableViewCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:#reuse_id)
cell.textLabel.text = #tweets_controller.tweets[indexPath.row].text
return cell
end
end
class Tweet
attr_reader :created_at, :from_user, :text
def initialize(tweet_result)
#created_at = tweet_result["created_at"]
#from_user = tweet_result["from_user"]
#text = tweet_result["text"]
end
end
Full controller code below. I've also put the project on GitHub
class TweetsController
def initialize
#twitter_accounts = %w(dhh google)
#tweets = []
create_tweets
end
def tweets
#tweets
end
def create_tweets
json_data = twitter_search_results.dataUsingEncoding(NSUTF8StringEncoding)
e = Pointer.new(:object)
dict = NSJSONSerialization.JSONObjectWithData(json_data, options:0, error: e)
dict["results"].each do |result|
p result.class
p result
#tweets << Tweet.new(result)
end
end
def twitter_search_results
query = #twitter_accounts.map{ |account| "from:#{account}" }.join(" OR ")
url_string = "http://search.twitter.com/search.json?q=#{query}"
url_string_escaped = url_string.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
url = NSURL.URLWithString(url_string_escaped)
request = NSURLRequest.requestWithURL(url)
response = nil
error = nil
data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: error)
raise "BOOM!" unless (data.length > 0 && error.nil?)
json = NSString.alloc.initWithData(data, encoding: NSUTF8StringEncoding)
end
end
the issue here is asynchronicity. you're almost there, I think, but the create_tweets method is not called before puts #tweets. In this case, I would recommend using a notification, because I think they are good ;-)
TweetsReady = 'TweetsReady' # constants are nice
NSNotificationCenter.defaultCenter.postNotificationName(TweetsReady, object:#tweets)
In your controller, register for this notification in `viewWillAppear` and unregister in `viewWillDisappear`
NSNotificationCenter.defaultCenter.addObserver(self, selector: 'tweets_ready:', name: TweetsReady, object:nil) # object:nil means 'register for all events, not just ones associated with 'object'
# ...
NSNotificationCenter.defaultCenter.removeObserver(self, name:TweetsReady, object:nil)
and you tweets_ready method should implement your UI changes.
def tweets_ready(notification)
#table.reloadData
end

Resources