i am using this code for passing datetime.
Convert.ToDateTime(textBox1.Text)
but the compiler show an error that string was not recognized as a valid datetime. so how to avoid this error and is a datetime field in my database.
Convert.ToDateTime(textBox1.Text)
This code will throw an exception if the string value in textBox1.Text doesn't represent a valid DateTime (or at least can't be parsed into one with default functionality in C#). You can add some defensive programming to handle errors like this.
The DateTime type (as well as most, if not all, common value types in .NET) has a method on it called TryParse() specifically for the purpose to attempting to parse a value into that type without throwing an exception. The method returns true if the parse was successful, false otherwise. And it accepts an out parameter to hold the resulting parsed value (or the original value if parsing is unsuccessful).
So instead of this:
var dateTimeValue = Convert.ToDateTime(textBox1.Text);
You could use something like this:
var dateTimeValue = DateTime.MinValue;
if (DateTime.TryParse(textBox1.Text, out dateTimeValue))
// use the value for something
Related
I am creating a webhook route where I will receive a JSON, so I am converting it into an object as follows:
data = JSON.parse(request.body.read, object_class: OpenStruct)
And that generates the object I want. This object however has a property that is similar to an ENUM, which has some 'predictable' values
being: PURCHASE_APPROVED, PURCHASE_CANCELED.
They come as a string, so I tried to do the following to convert them
events = { PURCHASE_CANCELED: 0, PURCHASE_APPROVED: 1 }
So I want to take the value that came as a string and transform it into an enum, the way I managed to convert the data was:
data.event = events[data.event.to_sym]
But the data doesn't become an enum, I can't use some properties like the
data.event.PURCHASE_APPROVED?
Is there any simple way to do this within the controller? Or would I have to create a class and specify each property just to have 1 enum?
So after being away awhile some things changed. I used to be able to do this:
void ObjectTemplateProxy::GetProperty(Local<String> hName, const PropertyCallbackInfo<Value>& info)
{
auto hStr = hName->ToString();
But now I need an isolate, and the parameter type changed to Local<Name>. Then I tried this:
auto hStr = hName->ToString(info.GetIsolate());
But this still doesn't work because hStr is null. It is null because, as it turns out, the name is actually a Symbol type and NOT String. I don't see any way to convert a symbol to a string, which I need to do to send the name to the C# CLR via P/Invoke to pull the value from a dictionary using string keys.
So, it would seem that there is a Name() function on the Symbol type that returns a String. I was looking for a function on the Symbol type and didn't find one (must have missed it). The code that worked was hName.As<Symbol>()->Name().As<String>();.
As noted below in the comments, Symbol() is not required to have a name, so beware!
Grails has a bug with regards to databinding in that it throws a cast exception when you're dealing with bad numerical input. JIRA: http://jira.grails.org/browse/GRAILS-6766
To fix this I've written the following code to manually handle the numerical input on the POGO class Foo located in src/groovy
void setPrice(String priceStr)
{
this.priceString = priceStr
// Remove $ and ,
priceStr = priceStr.trim().replaceAll(java.util.regex.Matcher.quoteReplacement('$'),'').replaceAll(',','')
if (!priceStr.isDouble()) {
errors.reject(
'trade.price.invalidformat',
[priceString] as Object[],
'Price:[{0}] is an invalid price.')
errors.rejectValue(
'price',
'trade.price.invalidformat')
} else {
this.price = priceStr.toDouble();
}
}
The following throws a null reference exception on the errors.reject() line.
foo.price = "asdf" // throws null reference on errors.reject()
foo.validate()
However, I can say:
foo.validate()
foo.price = "asdf" // no Null exception
foo.hasErrors() // false
foo.validate()
foo.hasErrors() // true
Where does errors come from when validate() is called?
Is there a way to add the errors property without calling validate() first?
I can't exactly tell you why, but you need to call getErrors() explicitly instead of accessing it as errors like a property. For some reason, Groovy isn't calling the method for it. So change the reject lines in setPrice() to
getErrors().reject(
'trade.price.invalidformat',
[priceString] as Object[],
'Price:[{0}] is an invalid price.')
getErrors().rejectValue(
'price',
'trade.price.invalidformat')
That is the easiest way to make sure the Errors object exists in your method. You can check out the code that adds the validation related methods to your domain class.
The AST transformation handling #Validateable augments the class with, among other things
a field named errors
public methods getErrors, setErrors, clearErrors and hasErrors
The getErrors method lazily sets the errors field if it hasn't yet been set. So it looks like what's happening is that accesses to errors within the same class are treated as field accesses rather than Java Bean property accesses, and bypassing the lazy initialization.
So the fix appears to be to use getErrors() instead of just errors.
The errors are add to your validateable classes (domain classes and classes that have the annotation #Validateable) dinamically.
Allowing the developer to set a String instead of a number doesn't seem a good way to go. Also, your validation will work only for that particular class.
I think that a better approach is to register a custom property editor for numbers. Here's a example with dates, that enable the transform of String (comming from the form) to Date with a format like dd/MM/yyyy. The idea is the same, as you will enforce that your number is parseable (eg. Integer.parseInt() will throw exception).
In your domain class, use the numeric type instead of String, so by code developers will not be allowed to store not number values.
Have a column in a report which a string date field in the format of MM/dd/yyyy. Some of those columns may contain empty strings. Having a problem sorting a section. I am about 10 hours in to telerik reporting so I may be missing something obvious.
I initially tried to use a expression like this:
=IIf(Fields.ExpirationDate='', CDate('1/1/1990'), CDate(Fields.ExpirationDate))
Does that look correct? This threw an error:
An error has occured while processing Report '':
Failed to compare two elements in the array.
------------- InnerException ------------- An error has occured while executing function CDate().
Check InnerException for further
information.
------------- InnerException ------------- Exception has been thrown by the target of an invocation.
------------- InnerException ------------- String was not recognized as a valid DateTime.
Another developer suggested using a custom method so I created inside the report.cs file
public DateTime EmptyDateToNow( string expirationDate )
{
DateTime parsed;
if (!DateTime.TryParse(expirationDate, out parsed))
return DateTime.Now;
return parsed;
}
and then tried to call with =EmptyDateToNow(Fields.ExpirationDate)
and this throws the error:
An error has occured while processing
Report '': Failed to compare two
elements in the array.
------------- InnerException ------------- The expression contains undefined function call
EmptyDateToNow().
public static DateTime EmptyDateToNow( string expirationDate )
I think that Telerik Reporting wants your user functions to be static methods.
I am thinking that the problem with the first approach is that CDate(Fields.ExpirationDate) is being executed even if the expression is true thereby causing the exception to be thrown. You might try something like this to get the desired result without defining a user function:
=CDate(IIf(IsNull(Fields.ExpirationDate) Or Fields.ExpirationDate="", "1/1/1990", Fields.ExpirationDate))
I realize this is a bit old, I just wanted to post in case anyone else is having troubles and searching this.
Make the user function static (and if the call still fails, make the call fully qualified. e.g. =Myclass.EmptyDateToNow(Fields.ExpirationDate)).
Make the function receive an object as a parameter (not a string or any other data type).
Inside the function, check for null and then (it not null) convert to the proper data type and work with it.
I'm formatting a ResultSet to output to a CSV file. As such I really don't care about the Java types of the result set, beyond maybe knowing if it's text or numbers.
Does JDBC guarantee getString will always give a string representation of the values,atleast for single values (I don't need to concern myself about java.sql.Types.ARRAY,java.sql.Types.JAVA_OBJECT and a few others).
e.g. given resultSetMetaData.getColumnType(i) is a Types.FLOAT or a Types.BIGDECIMAL. will rs.GetString(i) always yield some String ?
i.e. Are there cases getString will throw an SQLException or return null when a getXXX would give me the value ?
Yup, check this : http://java.sun.com/docs/books/tutorial/jdbc/basics/retrieving.html
JDBC allows a lot of latitude as far as which getXXX methods you can use to retrieve the different SQL types. For example, the method getInt can be used to retrieve any of the numeric or character types. The data it retrieves will be converted to an int; that is, if the SQL type is VARCHAR , JDBC will attempt to parse an integer out of the VARCHAR. The method getInt is recommended for retrieving only SQL INTEGER types, however, and it cannot be used for the SQL types BINARY, VARBINARY, LONGVARBINARY, DATE , TIME, or TIMESTAMP.
But be careful, different JDBC driver may yield different result.
java.lang.String is a final class - it cannot, ever, have a subclass. So any method that returns String will either return an instance of the class java.lang.String, or a null, or throw an exception.
As for conversion, it is up to the JDBC driver if it will allow you to convert from non-String types. I suspect many will have an issue with it.
I would suggest that you do this instead:
Object item = resultSet.getObject(i);
String strValue = (item == null ? null : item.toString());
That should be more robust, since getObject() will always do the sensible thing.