Database NULL Value [duplicate] - ado.net

This question already has answers here:
Most efficient way to check for DBNull and then assign to a variable?
(15 answers)
Closed 9 years ago.
I have found in my codebase lots of places has been coded as
dr["FIRST_ITEM"].Trim()
Now the problem is that if FIRST_ITEM column is a allow null values there is chance to encounter Null pointer Exception. I know, I can change the code to
Convert.ToString(dr["FIRST_ITEM"]).Trim()
in order to fix the problem. But then I have to do this in 1000 lines of code. Can I have solution, by which I can fix the problem with least effort?

I just ended up writing a quick method like this:
private static string GetS(object obj)
{
if (obj == null || obj == DBNull.Value)
return "";
return obj.ToString();
}
Example:
MyObject.LastName = GetS(dr["LastName"]));
Someday I'll have time to go back and write an extention to the DataRow or to write a generic converter. But for now this works and I have one for dates and bool data types.

Related

How to tell Flutter that a variable can be null in the right way (Null Safety)?

I have a question about Flutter and Null Safety.
For example I have this lines of code:
Future<dynamic> isLoggedIn() async {
Account account = Account(client);
Response? result = await account.get();
if (result == null) {
print(true);
}
}
I've marked result as nullable variable with Response?. So result can be null. Why Visual Studio gives me the warning The operand can't be null, so the condition is always false., if I check if result == null?
Do I misunderstand the concept of Null Safety? :-)
As also suggested by julemand101, the behavior of your ide is due to the fact that, when a variable is set using a method that returns a non-nullable type, the dart analyzer knows with certainty that the variable is not null (despite the type with which you declared the variable would allow null).
I too was surprised a little by the warning, because if you declare the variable by specifying its type, instead of using var, I would expect the dart analyzer to understand that the intent of the developer is to guard against possible changes. Then, thinking about it, I realized that if the method changed the signature and returned a nullable type, the compiler would force the developer to perform a null check, so in fact there is no reason to execute such a check until it is really needed.
However, you can make the warning disappear by using the comment // ignore: unnecessary_null_comparison or through the file analysis_options.yaml:
analyzer:
errors:
unnecessary_null_comparison: ignore
Edit:
the request can return null from server side.
If your account.get() method could return null, the ide would not report that warning to you. So I guess it's the signature of your method which is incorrect.
However, as for the question in the title ("the right way to tell Flutter that a variable can be null"), by declaring the variable as nullable you are leaving yourself the option of re-evaluating the variable with null or with a nullable type (and in that case then the null check would make sense).
Visual Studio gives you that warning because (I'm guessing because I did not see your get method) your get method is returning value that is not able to be a null value
Future<Response> get() async {
...
}
If you want it to be able to return null it should be declared like this
Future<Response?> get() async {
...
}

how to express one object is null when I use drools rule engine

I want to know how can I express one object is null on the left hand side when I use drools rule engine?
And anybody can tell me how to use the drools keyword "not" and so on.Thank you!
You can call not in when clause to check for null objects:
rule "somerule"
no-loop
when not AnObject()
then
// rule body when AnObject is null
end;
Drools is built on top of Java, so there is an instance of the object (which may or may not have null properties) or there is not. If the object is a 'fact' in working memory, then it is not null and your LHS should instead be determining whether it exists:
exists MyObject()
not exists MyObject()
However if you are trying to find facts with null properties, you can do this:
obj: MyObject(myProperty == null)

Custom ORMLite Persister to Return Wrapper Objects

I am writing an application which uses ORMLite to connect to a back-end database. Since the application will be run over VPN I am trying to minimize database calls.
In order to minimize database calls I have created a set of classes to wrap the values for each field. Each wrapper class stores the original value returned from the database and also a current value. This allows things like reverting to the original value, or checking whether the value is dirty (ie. only update the database if one or more fields are dirty).
The implication of this regarding ORMLite is that ORMLite never returns a null value when it queries the database (even if the database returns null). If there is a null value in the database it returns a fully initialized "wrapper" with the currentValue and originalValue variables set to null.
It seems that the right place to do this is in a custom persister such as (where StatefulIntegerProperty is the wrapper for the Integer):
public class StatefulIntegerPersister extends BaseDataType {
... misc. other code
#Override
public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException {
Integer result = results.getInt(columnPos);
return new StatefulIntegerProperty((results.wasNull(columnPos)) ? null : result);
}
#Override
public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) throws SQLException {
return sqlArg;
}
#Override
public Object javaToSqlArg(FieldType fieldType, Object obj) throws SQLException {
return ((StatefulIntegerProperty)obj).getCurrentValue();
}
#Override
public boolean isStreamType() {
return true; // this is a hack to work around ORMLite setting the value to null in the FieldType.resultToJava function
}
}
I have three questions:
Is this the correct approach?
In the ORMLite FieldType.resultToJava function it seems to do a null check and will replace my wrapper with null if the database returned null. Right now I am getting past this by overriding the isStreamType method in the persister to return true. Is this the best approach, and will I find later an unintended negative side effect?
What is the difference between the resultToSqlArg and sqlArgToJava methods in a custom persister, and specifically, which one of these should I use to wrap the value returned from the DB, and then what should I be doing in the other?
Is this the correct approach?
I don't understand why anything that you are doing here minimizes database calls. Can you start a discussion on the users' mailing list?
Right now you are overriding the resultToSqlArg(...) method when I think you want the sqlArgToJava(...). See below.
Right now I am getting past this by overriding the isStreamType method in the persister to return true. Is this the best approach...
Hrm. If it works then fine but it seems dangerous to use this setting in this manner. If I changed the behavior of the isStreamType() method then this may break your code. At the very least you should have unit tests to confirm this behavior that will break if you upgrade ORMLite.
That said, there is good handling in the code specifically around null values if isStreamType() is true.
What is the difference between the resultToSqlArg and sqlArgToJava...
I've fleshed out the javadocs for these.
resultToSqlArg takes the object from the SQL results and turns it into a java-object suitable to be an argument to SQL commands. For example, if you have a date-long type, this will extract a Long value from the database results.
sqlArgToJava takes the sql-arg value and converts it into our Java field. For example, if you have a date-long type, this will take a Long value and convert it into a Date which matches the entity field.
I think you should override the sqlArgToJava and not the resultToSqlArg.

Why am I being told my mySQLi object is a 'non-object'? [duplicate]

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 10 years ago.
I'm trying to build a website using object-oriented functionality, and running into some issues. The one that is currently vexing me is an error message that I can't solve:
Fatal error: Call to a member function real_escape_string() on a non-object in /home/rilbur5/public_html/tutor/login.php on line 41
function get_user_MYSQL(){
return new mysqli($GLOBALS['db_host'],$GLOBALS['user_login'],$GLOBALS['user_password'],$GLOBALS['db_name']);
}//will turn this into a singleton object later
class User_Login{
private $db_link;
public function __construct()
{
$db_link=get_user_MYSQL();
}
public function bar($foo)
{
$foo=$db_link->real_escape_string($foo);
}
}
I've inserted an echo statement into the constructor, and it IS being called. I've tested the get_user function, and it works elsewhere -- in fact, I used an echo statement that showed that the data was, in fact, being properly escaped when I used real_escape_string on an object produced by the get_user functions. So why is the combination not producing a mySQLi function that will do the necessary work?
I think you need to use $this->db_link, since you're trying to access the MySQLi object within the class.

NUnit - Assert to check all properties are equal? [duplicate]

This question already has answers here:
Compare equality between two objects in NUnit
(20 answers)
Closed 7 years ago.
Is there an assertion built into Nunit that checks all properties between 2 objects are the same, without me having to override Equals?
I'm currently using reflection to Assert each individual property for a pair of objects.
I don't believe there is.
Assert.AreEqual compares non-numeric types by Equals.
Assert.AreSame checks if they refer to the same object
You can write framework agnostic asserts using a library called Should. It also has a very nice fluent syntax which can be used if you like fluent interfaces. I had a blog post related to the same.
http://nileshgule.blogspot.com/2010/11/use-should-assertion-library-to-write.html
You can two objects and there properties with ShouldBeEquivalentTo
dto.ShouldBeEquivalentTo(customer);
https://github.com/kbilsted/StatePrinter has been written specifically to dump object graphs to string representation with the aim of writing easy unit tests.
It comes witg Assert methods that output a properly escaped string easy copy-paste into the test to correct it.
It allows unittest to be automatically re-written
It integrates with all unit testing frameworks
Unlike JSON serialization, circular references are supported
You can easily filter, so only parts of types are dumped
Given
class A
{
public DateTime X;
public DateTime Y { get; set; }
public string Name;
}
You can in a type safe manner, and using auto-completion of visual studio include or exclude fields.
var printer = new Stateprinter();
printer.Configuration.Projectionharvester().Exclude<A>(x => x.X, x => x.Y);
var sut = new A { X = DateTime.Now, Name = "Charly" };
var expected = #"new A(){ Name = ""Charly""}";
printer.Assert.PrintIsSame(expected, sut);