How to test QueryString - asp.net

I have a query string called propID and I wanna check if the passed value in it is a legal integer or not to avoid throwing an error that might reveal info about my database, how can I do it?
In other words, I want something like -but in vb.net- :
IF QueryString("propID").Content.Type = "int32" Then Proceed

You could use TryParse:
Dim myInt As Integer
If Int32.TryParse(QueryString("propID").Content, myInt) Then Proceed

Dim result as boolean
result = integer.tryparse(QueryString("propID"), myintegervariable)
boolean will return true if it parsed correctly (putting the value into your myintegervariable) and will return false if the parsing failed.
You can also write is as
if integer.tryparse(QueryString("propID"), myintegervariable) then
//continue going along with myintegervariable
else
//parsing didn't work
end if

You can just use Int32.TryParse.

You could try the 'is' keyword to check the type of on object.
If QueryString("propID").Content.Type Is Int32 Then Proceed
Otherwise Int32.TryParse would work as well.

C# version:
int _PropID;
if (int.TryParse(QueryString["propID"], out _PropID))
{
//Proceed with _PropID
}

Related

Cannot Solve "index was outside the bounds of the array"

I am working in C# with ASP.NET. I am familiar with this error but this time I can't solve it.
I have text in a drop-down list like this:
राम कुमार सिंह 8s2w8r
here राम कुमार सिंह is the name in HINDI while 8s2w8r is users' ID.
I need to separate these two values and need to pass them as session variables. The logic I am using is depicted in the code.
public string reverse(string s)
{
char []temp=s.ToCharArray();
Array.Reverse(temp);
return (temp.ToString());
}
string dropdowntextreversed=reverse(DropDownList1.Text);
char []delim=new char[]{' '};
string []parts=dropdowntextreversed.Split(delim,2);
string family_head_uid = reverse(parts[0]);
string family_head = reverse(parts[1]);
Session.Add("family_head", family_head);
Session.Add("family_head_uid", family_head_uid);
Response.Redirect("/WebForm1.aspx");
I always get an error as the index was outside the bounds of the array! I don't understand this because I am breaking the string into 2 parts so it should have parts[0] and parts[1]. Please suggest...
You are splitting the string into MAXIMUM 2 parts, but if there's only one you will get probably one part.
Read this documentation
Try to assert that parts.Length is == 2 or to access elemnts only there atre two elements
Try this link. As I think there is a problem in the temp.ToString() which will return System.Char[] rather than the value which are you looking for. Use string.join instead will work.
Use the following reverse method:
public string reverse(string s)
{
return String.Join(String.Empty, s.ToCharArray().Reverse());
}

DateTime.TryParse in a conditional is throwing an exception

On both examples I'm giving it a String like the following: 26-03-17
Dim mvarValor As String
Dim dateVarValor As DateTime
This code snippet is throwing an exception on the TryParse:
If Not mvarValor = Nothing AndAlso DateTime.TryParse(mvarValor, dateVarValor) Then
Return Format(dateVarValor, mvarFormat)
Else
Return strNull
End If
The next code snippet is not throwing an exception, but a False like it should:
DateTime.TryParse(mvarValor, dateVarValor)
If dateVarValor = Nothing Then
Return strNull
Else
Return Format(dateVarValor, mvarFormat)
End If
Why is the first code snippet giving me an exception?
Thanks in advance!
DateTime.TryParse throws three types of exceptions
http://msdn.microsoft.com/en-us/library/9h21f14e(v=vs.100).aspx
you must be getting one of those. Here is the proper usage of DateTime.TryParse
var culture = CultureInfo.CreateSpecificCulture("en-US");
string parsedDateTime = null;
if (DateTime.TryParse(parseMe, culture, DateTimeStyles.None, out dateResult))
{
parsedDateTime = dateResult;
}
this snippet will parse the datetime without throwing an exception.
I hope this helps :)
You need to pass in a Y2K compliant date. The parser can't tell the year from 2 digits. If you pass 2003-12-25 it will validate that the date does in fact exist, but 03-12-25 is ambiguous.

Dealing with Nulls from a DataReader

I have done this in the past, but I cant remember the correct way to deal with DBNULLS.
This is vb.net
The error im getting is Conversion from type 'DBNull' to type 'Integer' is not valid.
Here is the code.
Dim reader As MySqlDataReader = command.ExecuteReader
Do While reader.Read
Dim item As New clsProvider(reader.Item("MasterAccountID"), reader.Item("CompanyName"), reader.Item("Address"), reader.Item("Postcode"), reader.Item("Telephone"), reader.Item("Fax"), reader.Item("Number_of_Companies"), reader.Item("Total_Number_of_employees"), reader.Item("MainContactName"), reader.Item("MainContactPhone"), reader.Item("MainContactEmail"), reader.Item("Fee"), Convert.ToString(reader.Item("Notes")))
list.Add(item)
Loop
reader.Close()
The issue i have is that some of the items may be empty in the DB. I'm sure in the past I have done something like
convert.ToString(reader.item("Something")
But for the life of me i cant remember.
If the column is nullable, then you should check for null:
If (reader.IsDBNull(ordinal))
See IsDBNull
Perhaps
reader.item("Something").ToString()
is what you've done before?
This isn't necessarily correct but it does deal with null strings quite effectively.
Perhaps:
IFF(reader.item("Something") != DBNull.Value, reader.item("Something"), "")
You have to first check if the column value is null (check the incoming value for DBNull). Once you know that you can decide what to do next - assign null or some other default value to your variable.
I am not sure if my VB.Net is still upto the mark but something like this should help:
Dim item As New clsProvider
item.AccountId = TryCast(reader.Item("MasterAccountID"), String)
item.SomeInt= If(TryCast(reader.Item("SomeInt"), System.Nullable(Of Integer)), 0)
Use TryCast to check if cast is possible.

Adding comma separators to numbers, asp.net

I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function

Why is this looping infinitely?

So I just got my site kicked off the server today and I think this function is the culprit. Can anyone tell me what the problem is? I can't seem to figure it out:
Public Function CleanText(ByVal str As String) As String
'removes HTML tags and other characters that title tags and descriptions don't like
If Not String.IsNullOrEmpty(str) Then
'mini db of extended tags to get rid of
Dim indexChars() As String = {"<a", "<img", "<input type=""hidden"" name=""tax""", "<input type=""hidden"" name=""handling""", "<span", "<p", "<ul", "<div", "<embed", "<object", "<param"}
For i As Integer = 0 To indexChars.GetUpperBound(0) 'loop through indexchars array
Dim indexOfInput As Integer = 0
Do 'get rid of links
indexOfInput = str.IndexOf(indexChars(i)) 'find instance of indexChar
If indexOfInput <> -1 Then
Dim indexNextLeftBracket As Integer = str.IndexOf("<", indexOfInput) + 1
Dim indexRightBracket As Integer = str.IndexOf(">", indexOfInput) + 1
'check to make sure a right bracket hasn't been left off a tag
If indexNextLeftBracket > indexRightBracket Then 'normal case
str = str.Remove(indexOfInput, indexRightBracket - indexOfInput)
Else
'add the right bracket right before the next left bracket, just remove everything
'in the bad tag
str = str.Insert(indexNextLeftBracket - 1, ">")
indexRightBracket = str.IndexOf(">", indexOfInput) + 1
str = str.Remove(indexOfInput, indexRightBracket - indexOfInput)
End If
End If
Loop Until indexOfInput = -1
Next
End If
Return str
End Function
Wouldn't something like this be simpler? (OK, I know it's not identical to posted code):
public string StripHTMLTags(string text)
{
return Regex.Replace(text, #"<(.|\n)*?>", string.Empty);
}
(Conversion to VB.NET should be trivial!)
Note: if you are running this often, there are two performance improvements you can make to the Regex.
One is to use a pre-compiled expression which requires re-writing slightly.
The second is to use a non-capturing form of the regular expression; .NET regular expressions implement the (?:) syntax, which allows for grouping to be done without incurring the performance penalty of captured text being remembered as a backreference. Using this syntax, the above regular expression could be changed to:
#"<(?:.|\n)*?>"
This line is also wrong:
Dim indexNextLeftBracket As Integer = str.IndexOf("<", indexOfInput) + 1
It's guaranteed to always set indexNextLeftBracket equal to indexOfInput, because at this point the character at the position referred to by indexOfInput is already always a '<'. Do this instead:
Dim indexNextLeftBracket As Integer = str.IndexOf("<", indexOfInput+1) + 1
And also add a clause to the if statement to make sure your string is long enough for that expression.
Finally, as others have said this code will be a beast to maintain, if you can get it working at all. Best to look for another solution, like a regex or even just replacing all '<' with <.
In addition to other good answers, you might read up a little on loop invariants a little bit. The pulling out and putting back stuff to the string you check to terminate your loop should set off all manner of alarm bells. :)
Just a guess, but is this like the culprit?
indexOfInput = str.IndexOf(indexChars(i)) 'find instance of indexChar
Per the Microsoft docs, Return Value -
The index position of value if that string is found, or -1 if it is not. If value is Empty, the return value is 0.
So perhaps indexOfInput is being set to 0?
What happens if your code tries to clean the string <a?
As I read it, it finds the indexChar at position 0, but then indexNextLeftBracket and indexRightBracket both equal 0, you fall into the else condition, and then you insert a ">" at position -1, which will presumably insert at the beginning, giving you the string ><a. The new indexRightBracket then becomes 0, so you delete from position 0 for 0 characters, leaving you with ><a. Then the code finds the <a in the code again, and you're off to the races with an infinite memory-consuming loop.
Even if I'm wrong, you need to get yourself some unit tests to reassure yourself that these edge cases work properly. That should also help you find the actual looping code if I'm off-base.
Generally speaking though, even if you fix this particular bug, it's never going to be very robust. Parsing HTML is hard, and HTML blacklists are always going to have holes. For instance, if I really want to get a <input type="hidden" name="tax" tag in, I'll just write it as <input name="tax" type="hidden" and your code will ignore it. Your better bet is to get an actual HTML parser involved, and to only allow the (very small) subset of tags that you actually want. Or even better, use some other form of markup, and strip all HTML tags (again using a real HTML parser of some description).
I'd have to run it through a real compiler but the mindpiler tells me that the str = str.Remove(indexOfInput, indexRightBracket - indexOfInput) line is re-generating an invalid tag such that when you loop through again it finds the same mistake "fixes" it, tries again, finds the mistake "fixes" it, etc.
FWIW heres a snippet of code that removes unwanted HTML tags from a string (It's in C# but the concept translates)
public static string RemoveTags( string html, params string[] allowList )
{
if( html == null ) return null;
Regex regex = new Regex( #"(?<Tag><(?<TagName>[a-z/]+)\S*?[^<]*?>)",
RegexOptions.Compiled |
RegexOptions.IgnoreCase |
RegexOptions.Multiline );
return regex.Replace(
html,
new MatchEvaluator(
new TagMatchEvaluator( allowList ).Replace ) );
}
MatchEvaluator class
private class TagMatchEvaluator
{
private readonly ArrayList _allowed = null;
public TagMatchEvaluator( string[] allowList )
{
_allowed = new ArrayList( allowList );
}
public string Replace( Match match )
{
if( _allowed.Contains( match.Groups[ "TagName" ].Value ) )
return match.Value;
return "";
}
}
That doesn't seem to work for a simplistic <a<a<a case, or even <a>Test</a>. Did you test this at all?
Personally, I hate string parsing like this - so I'm not going to even try figuring out where your error is. It'd require a debugger, and more headache than I'm willing to put in.

Resources