DateTime.TryParse in a conditional is throwing an exception - asp.net

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.

Related

ASP.NET/VB date works on localhost but not remoteserver

I'm having alot of trouble trying to get the date from a DateTime picker to save to my database. It works fine when run from Localhost, but when running it on the public server it doesn't.
Originally i used the cDate function, plus also tried Convert.ToDateTime. But on the server it now gives me an error "String was not recognized as a valid DateTime."
I researched and found that its best to used the DateTime.TryParse function. After finding an example i changed it for my project and now im getting the error "Must declare the scalar variable "#articledate"."
When i debug the project, the value added into the "result1" DateTime is correct. But it still throws the error at ExecuteNonQuery?
If it makes a difference, the main server is hosted with GoDaddy, Localhost is my PC.
Any help or advice would be greatly appreciated.
cnSQL1 = New SqlConnection(MSSQL.cRemoteConnectionString)
cnSQL1.Open()
sSQL = "SELECT NewsID FROM News WHERE Season = #season AND Heading = #heading AND ArticleDate = #articledate AND Author = #author AND Club = #club AND State = #state AND AddedDate = #addeddate AND AddedBy = #addedby AND Release = #release"
Dim com1 As New SqlCommand(sSQL)
com1.Connection = cnSQL1
com1.Parameters.AddWithValue("#season", General.sSeason)
com1.Parameters.AddWithValue("#heading", General.UppercaseFirstLetter(txtHeading.Text))
Dim result1 As DateTime
com.Parameters.AddWithValue("#articledate", DateTime.TryParseExact(txtArticleDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result1))
'com1.Parameters.AddWithValue("#articledate", Convert.ToDateTime(txtArticleDate.Text))
com1.Parameters.AddWithValue("#author", txtAuthor.Text)
com1.Parameters.AddWithValue("#club", ddlClub.SelectedItem.Value)
com1.Parameters.AddWithValue("#state", dsState.Tables(0).Rows(0).Item(0))
com1.Parameters.AddWithValue("#addeddate", Date.Today)
com1.Parameters.AddWithValue("#addedby", Session("UserID"))
com1.Parameters.AddWithValue("#updatedate", Date.Today)
com1.Parameters.AddWithValue("#updateby", Session("UserID"))
com1.Parameters.AddWithValue("#release", s)
com1.ExecuteNonQuery()
The error "Must declare the scalar variable "#articledate" is caused by a typo. When you add the parameter you should use the SqlCommand variable named com1 not the variable com.
But after this you have a more critical error. All the TryParse methods return booleans. The converted date is written in the last parameter passed to TryParse.
In this way you are passing a boolean to AddWithValue and this method takes whatever you put in the value parameter. It has no way to know that you want a date, so it happily complies with your request.
You should do (Notice that the SqlCommand to use is com1 not com)
Dim result1 As DateTime
if DateTime.TryParseExact(txtArticleDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result1) Then
com1.Parameters.AddWithValue("#articledate", resul1)
Else
.....
In general it is better to avoid AddWithValue exactly because it takes whatever you pass to it. The preferred way is with
if DateTime.TryParseExact(txtArticleDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result1) Then
com1.Parameters.Add("#articledate", SqlDbType.Datetime).Value = result1
com1.Parameters.AddWithValue("#season", General.sSeason)
com1.Parameters.AddWithValue("#heading", General.UppercaseFirstLetter(txtHeading.Text))
com1.Parameters.AddWithValue("#author", txtAuthor.Text)
com1.Parameters.AddWithValue("#club", ddlClub.SelectedItem.Value)
com1.Parameters.AddWithValue("#state", dsState.Tables(0).Rows(0).Item(0))
com1.Parameters.AddWithValue("#addeddate", Date.Today)
com1.Parameters.AddWithValue("#addedby", Session("UserID"))
' This is not used by the query, commented out
' com1.Parameters.AddWithValue("#updatedate", Date.Today)
' This is not used by the query, commented out
' com1.Parameters.AddWithValue("#updateby", Session("UserID"))
com1.Parameters.AddWithValue("#release", s)
com1.ExecuteNonQuery()
Else
MessageBox.Show("Date is not valid")
End If
I have also removed two parameters that are not used in the query above (though they should not cause the error message above)

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.

Problems with If Statement (ASP.NET)

Dim custEmail As String
Dim inputEmail As String
custEmail = dt.Rows(0).Item("email")
inputEmail = email_add.Text
if (custEmail.toString() == inputEmail.toString() ){
label1.Text = custEmail
}
End If
This code is giving an error: Compiler Error Message: BC30201: Expression expected.
I just basically want to check if two values are equal but its saying something about expression expected although i've given the expression to evaluate.
The above is a mix of vb.net and c# syntax. You can use either in .net with success but not both at the same time. Get rid of the { and } to stick with vb.
Looks like you are mixing C# and VB.Net. Assuming you are using VB.Net
Replace the '{' with Begin IF and remove the '}'.

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

How to test QueryString

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
}

Resources