System.InvalidCastException: 'Object cannot be cast from DBNull to other types.' asp.NET CORE [duplicate] - asp.net

I can check for a DBnull on a data row using any of the methods.
Either by using
if(dr[0][0]==DBNull.Value)
//do somethin
or by doing
if(dr[0][0].ToString().IsNullOrEmpty())
//do something
In Both Cases I will be getting same result.
But Which one is conecptually right approach. Which was will use less resources

The first way is somewhat correct.
However, more accepted way is:
if ( dr[0][0] is DBNull )
And the second way is definitely incorrect. If you use the second way, you will get true in two cases:
Your value is DBNull
Your value is an empty string

Conceptually the comparison to DBNull.Value is the correct one.
You can also use :
if (Convert.IsDBNull(dr[0]))
{
}
You could also use, which I'm not a fan of, purely because it's a type comparison rather than a value comparison:
if (dr[0] is DBNull)
{
}

Is always use :
dr[0].IsNull(0)
Assuming that the creators of this function know the best way/most efficient way of comparing..

The simplest way
if (dr[0][0] == DBNull.Value)
//do somethin
is perfectly valid and readable.
Even though == compares references, it works here because DBNUll.Value is the only instance of DBNull class - so all DBNull values are actually this exact reference.

Related

JavaFX binding and null values

I was wondering how to bind values where the source of the bind could be null.
I have a property:
private ObjectProperty<Operation> operation = new SimpleObjectProperty<>(null);
I also have a text field:
#FXML
private Text txtCurrentOperation;
I would like to bind the textProperty of the field to the value of the operation object.
My first thought was to use FluentAPI with its when/then/otherwise construct, but it is eagerly evaluated so the solution:
Bindings.when(operation.isNotNull())
.then("null")
.otherwise(operation.get().getName()));
will throw a NPE, because the parameter of otherwise is evaluated no matter what the result of the when.
My next idea was to use lambda somehow:
txtCurrentOperation.textProperty().bind(() ->
new SimpleStringProperty(
operation.isNotNull().get() ? "Null" : operation.get().getName()
));
But the bind has no lambda enabled solution. (Later I realized that it couldn't have, becasue the real work goes backward: the change of the binded object (operation) will trigger the update of the binder (the field text property).)
Some articles I found suggested to use an "extremal" value for the property instead of null. But Operation is a complex and heavy weight component so it is not trivial to construct an artifical instance to represent null. Even more, this seems to me boilercode, something the binding mechanism is designed to help eliminating.
My next try was to logically swap the binding direction and add listener to the operation property and let it update the field programatically. It works and rather simple as long as the need of update only depends the operation object instances:
operation.addListener((e) -> {
txtCurrentOperation.setText(operation.isNull().get() ?
"Null" : operation.get().getName());
});
operation.set(oper);
It is relatively simple, but doesn't work: it throws "A bound value cannot be set." exception and I don't see why is the text property of the control regarded as bound.
I ran out of ideas. After much searching, I still cannot solve the simple problem to update a text field differently based on whether the source is null or not.
This seems so simple and everyday problem, that I am sure I missed the solution.
If a 3rd party library is an option, check out EasyBind. Try something like this:
EasyBind.select(operation)
.selectObject(Operation::nameProperty)
.orElse("null");
There's also a JavaFX JIRA issue for the type of functionality provided by EasyBind. If you don't want to use a 3rd party library, try Bindings.select:
Bindings.when(operation.isNotNull())
.then("null")
.otherwise(Bindings.select(operation, "name"));
Be aware the null checking in Bindings.select isn't super efficient. There's a JIRA issue for it.
Just in case if somebody using not Java itself but Kotlin.
It is a good idea to use wonderful tornadofx library.
There you can just use operation.select{it.name}. Although, this feature seems not to be documented yet, so it took some time to discover it.

Readable exception information when testing DateTime objects in PHPUnit

When testing DateTime objects in PHPUnit (3.7.22), I am making the assertion like this:
$this->assertEquals(date_create('2014-01-01'), $myobject->getDate());
Works nicely till you get an exception, and the exception in not clear enough (like for primitives where is clearly states for example that 1 does not equal the excepted 2).
PHPUnit_Framework_ExpectationFailedException : Failed asserting that two objects are equal.
I could pass the $message parameter to the assertEquals method, with a string containing the object value, but I feel it could go easier.
Any ideas?
You could do something like
$expected_date = new DateTime('2014-01-01');
$this->assertEquals($expected_date->format('Y-m-d'), $myobject->getDate()->format('Y-m-d');
This would make you error message say something like "failed asserting that '2014-02-03 matches expected 2014-01-01'
I had a poke around the phpUnit source, and don't see any hook to allow better display. What I usually do is what you already mention in your question:
$this->assertEquals(date_create('2014-01-01'), $myobject->getDate(), print_r($myobject,true) );
OR:
$this->assertEquals(date_create('2014-01-01'), $myobject->getDate(), print_r($myobject->getDate(),true) );
depending on which is more useful, case-by-case.
I do this anyway, because often I want to include other helpful data in the message, perhaps some previous calculations, to give it context. I.e. to know why a test is failing I often need to know more than just the two objects that should've been equal.

Object reference not set to an instance of an object while reading from 2 textboxes

for (int i = 0; i < parts.Count; i++)
{
if (!((part)parts[i]).deleteUsed)
((part)parts[i]).hints = ((TextBox)partsView.Rows[i].Cells[4].FindControl("textBox")).Text;
((part)parts[i]).PartsWaiting = ((TextBox)partsView.Rows[i].Cells[5].FindControl("textBox1")).Text;
}
System.NullReferenceException: Object reference not set to an instance of an object.
Im getting this error for some reason, don't seem to figure out where I'm going wrong.
Your problem is partly due to multiple chained deferences e.g.
a.getB().getC().getD()
and if one of those methods returns null, you can't easily identify what's going on.
Unless you're very sure of what you're doing, I would split the above into either:
separate lines and assign intermediate variables. A null will then become apparent wrt. the line that it's on
a set of functions that dereference and throw a NullPtrException upon resolving a null. Again, your offending line will become apparent immediately.
You'll note that the above isn't particular to your immediate problem. Rather it's a useful practise when you can't be sure that chaining methods won't return null at some stage.
Its likely that FindControl is not getting the TextBoxes. Set breakpoints and watch the FindControl(). Also make sure the IDs you are using ain FindControl are correct.

Why does this function compare to an arbitrary number as a null check?

I came across this interesting function in a piece of ASP Classic that I maintain. At first I laughed, shook my head, then cried (only a little). But then I started to wonder if there is any legitimate reason why 999999999999999 would apparently be considered NULL since VBScript has its quirks. As mentioned in comments, the values passed to this function are returned from the COM dll.
Can anyone confirm if there is some legitimate reason for this or is it ripe for submission to TheDailyWTF.
function NullNumberCheck(Value)
if IsNumeric(Value) then
if Value = 999999999999999 then
Value = ""
end if
end if
NullNumberCheck = Value
end function
That looks like a case of "magic null" in the source of the data - is there a column in the database that backs the values being passed to this function which is not nullable?
Why are people using magic values instead of null in their code?
The author is using this as a method of clearing or unsetting the variable. By setting the value of Value to an empty string, it clears any previous value. The author could have just as easily set it equal to 0, vbNull, or vbEmpty. It really depends on what you are doing with the value later in your script. If you go on to perform further checks on the variable, setting it to vbNull may not be advisable and setting it equal to vbEmpty may crash your script if you are using Option Explicit.
So to answer your question, no this is not a valid way to check for a "null" value, because it's not a comparison operation at all, it's performing a variable assignment.
To check for a null value you can use the IsNull function built into VBscript
http://www.w3schools.com/vbscript/func_isnull.asp

Actionscript - is it better to cast or create a new variable? Or does it matter at all?

I find that in my daily Flex/Flash work, I do this number a lot:
//Calling a function...
MyCustomObject(container.getChildAt(i)).mySpecialFunction();
The question is - is this the best way to do this? Should I do this:
//Calling a function
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;
tempItem.mySpecialFunction();
It might be incidental but I'm just wondering if there is an "accepted" way or a preferred way to do this. The second option seems more readable but I wonder if it takes more of a performance hit to create a new variable. Or does it all come down to style and preference?
It's important to remember that there is a difference between explicit casting and using the as keyword. Casting throws an error when it fails, whereas the as keyword does not (it just returns null).
// a casting error
try {
var number:int = 666;
var urlreq:URLRequest = URLRequest( number );
} catch(e:TypeError) {
// TypeError: Error #1034: Type Coercion failed: cannot
// convert 666 to flash.net.URLRequest.
trace(e);
}
Whereas the as keyword fails silently:
var number:int = 666;
var urlreq:URLRequest = number as URLRequest;
trace(urlreq); // prints null to the debug pane
Personally, I bear these behaviours in mind when deciding method to use. Generally, I'd recommend casting explicitly, as you'll know exactly how/when a cast failed. Often, though, you might want to fail silently and continue.
It generally doesn't matter. Creating a var just creates a pointer to the object, so it's not using more memory or anything like that.
The second example is definitely more readable and debuggable and should thus be preferred.
The risk you run from creating temp vars is that you might delay or prevent garbage collection for that object. This generally isn't a problem when it's just a local var in a function; just keep scope in mind when you're creating vars and passing them around.
For in-depth on the subject, read Grant Skinner's series on resource management in AVM2:
http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html
for the second example you might want to test for the nullity to avoid a NullPointerException when invoking "mySpecialFunction", e.g.
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;
if ( tempItem )
{
tempItem.mySpecialFunction();
}
I usually prefer the second approach but you have to remember that you can only use the as operator for casting "Date" and "Array" types.

Resources