How can I avoid the null object reference error - apache-flex

I have function init, which runs on the creationComplete of the application. The init calls get_login_share_object function, in which objects are created, which are null.
Now my problem is that, I get a null object reference error on the Alert in "init()". How can I avoid that. Is it possible that I can have a check to see, if the objects are null the program should just skip reading the objects.
private function init():void
{
var stored_credentials:Object = get_login_share_object();
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
private function get_login_share_object():Object
{
//create or retrieve the current shared object
var so:SharedObject = SharedObject.getLocal("loginData","/");
var dataToLoad:ByteArray = so.data.ws_creds;
if(!dataToLoad)
return null;
//read in our key
var aes_key:String = ServerConfig.aes_key;
var key:ByteArray = new ByteArray();
key = Base64.decodeToByteArray(aes_key);
//read in our encryptedText
var encryptedBytes:ByteArray = new ByteArray();
dataToLoad.readBytes(encryptedBytes);
//decrypt using 256b AES encryption
var aes:ICipher = Crypto.getCipher("simple-aes128-ctr", key, Crypto.getPad("pkcs5"));
aes.decrypt(encryptedBytes);
encryptedBytes.position = 0;
var obj:Object = new Object();
obj.alias = encryptedBytes.readUTF();
obj.password = encryptedBytes.readUTF();
obj.check_remember = encryptedBytes.readUTF();
return obj;
}

You could check for the null like this:
var stored_credentials:Object = get_login_share_object();
if (stored_credentials)
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
else
trace('No Shared Object');

You should find out why those values are null and fix that first. Generally speaking, if you are expecting a value, it should not be null.
If it really is expected that some of those values are null then yes, you can check them first in two ways:
if(value != null) value.doSomething();
or
try{
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
catch(e:Error){
// do something else here if the statement under the try failed.
// most likely log the error message and see what it is
}

Your problem is here:
var dataToLoad:ByteArray = so.data.ws_creds;
if(!dataToLoad)
return null;
If there isn't any data to load, you're returning a null. So when you try and access the returned object's properties later, you'll get the null object reference error because you're referencing a null object. :)
There are a couple of easy solutions to this. You can check if the return value is null before you try to reference any properties like so:
if (stored_credentials != null) {
Alert.show(stored_credentials.check_remember +" "+ stored_credentials.alias +" "+ stored_credentials.password );
}
Or you can stop returning a null from your get_login_share_object function. What you return instead is totally up to you, just make sure it returns an object with all the properties you're referencing.

Related

Linq to XML single or default

I am querying an xml and i am storing the results using singleordefault
var query = from nm in xelement.Descendants("EmployeeFinance")
where (int)nm.Element("EmpPersonal_Id") == empID
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
Debug.WriteLine("2");
var resultquery = query.SingleOrDefault();
now this line: var resultquery = query.SingleOrDefault(); works fine if it found in the xml file. However, i have a case where my query will result in a null. If i have no value, it would make an entry in the xml file and my query obviously results in null. My question is how do i cater for this without causing my programe to crash. obviously, singleordefault() doesnt work.
***************** EDITED *************************
I read what everyone said so far and it make sense but i am still having a problem.
if (query.Count() == 0)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
if (query == null)
{
Debug.WriteLine("NULL");
}
else {
var resultquery = query.SingleOrDefault();
Debug.WriteLine("NOT NULL");
}
OR
var resultquery = query.SingleOrDefault();
if (resultquery == null)
{
Debug.WriteLine("NULL Result");
}
else
{
Debug.WriteLine("NOT NULL");
}
I am getting a System.NullReferenceException error when the first part of the if statement is true. One user said to do this: var resultquery = query.SingleOrDefault(); then use my if..else statement to do the comparison. However i am getting the error at the point of assign query.singleofdefault() to resultquery. So i am lost.. hope someone can help. thank you
what i am trying to understand is this. the documentation states if the result query is 0 it will give a default value, if it is not, it will be a single value. so why doesnt this give a default value? [taken from the comments]
null is the default value for reference types. Apparently AllowancePaid is a reference type (a custom class).
What is the value you want when the there is no value found.
You could either do:
if (resultquery == null) {
// Logic for No result
} else {
// Logic for result found
}
Or you could force a default value
eg.
var resultquery = query.SingleOrDefault() ?? new AllowancePaid();
UPDATE
From the comments posted it appears that the null reference exception is actually caused within the query itself rather than by the assignment to resultquery and use of later.
This updated query should solve the issue
var query = from nm in xelement.Descendants("EmployeeFinance")
where nm.Element("EmpPersonal_Id") != null
&& (int)nm.Element("EmpPersonal_Id") == empID
&& nm.Element("Allow-GradeTax") != null
&& nm.Element("Allow-GradeTax").Elements("Amount") != null
select new AllowancePaid
{
gradeTaxId = nm.Element("Allow-GradeTax").Elements("Amount").Attributes("BenListId").Select(a => (int)a).ToList(),
gradeTaxAmt = nm.Element("Allow-GradeTax").Elements("Amount").Select(a => (double)a).ToList()
};
var resultquery = query.SingleOrDefault();
if (resultquery == null) {
Debug.WriteLine("NULL Result");
} else {
// Logic here
}

How to pass non-optional NULL parameters to a Stored Proc using OrmLite

I'm using OrmLite against an existing SQL Server database that has published stored procedures for access. One of these SPs takes 3 int parameters, but expects that one or another will be null. However, none of the parameters are declared optional.
Here's the code I've tried:
using (IDbConnection scon = myFactory.OpenDbConnection())
{
rowCount = scon.SqlScalar<int>("EXEC myProc #FileID, #FileTypeID, #POID",
new
{
FileID = req.FileId,
FileTypeID = (int?)null,
POID = req.PoId,
});
}
But this produces a SqlException: Must declare the scalar variable "#FileTypeID". Examining the SQLParameterCollection under the covers shows that only two parameters are being generated by OrmLite.
Is it possible to call this SP with a null parameter?
It's not supported with SqlScalar. When you look at the code then you can see that SqlScalar methods from class ServiceStack.OrmLite.OrmLiteReadExtensions execute SetParameters method responsible for adding parameters to query with second parameter(excludeNulls) equal true I don't know why- mythz should answer for this ;).
If you want to fix it then you have change all SqlScalar methods to invoke SetParameters with true and SetParameters method should look like following(must support DBNull.Value not null)
private static void SetParameters(this IDbCommand dbCmd, object anonType, bool excludeNulls)
{
dbCmd.Parameters.Clear();
lastQueryType = null;
if (anonType == null) return;
var pis = anonType.GetType().GetSerializableProperties();
foreach (var pi in pis)
{
var mi = pi.GetGetMethod();
if (mi == null) continue;
var value = mi.Invoke(anonType, new object[0]);
if (excludeNulls && value == null) continue;
var p = dbCmd.CreateParameter();
p.ParameterName = pi.Name;
p.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType(pi.PropertyType);
p.Direction = ParameterDirection.Input;
p.Value = value ?? DBNull.Value; // I HAVE CHANGED THAT LINE ONLY
dbCmd.Parameters.Add(p);
}
}
When you change code then you can set null for parameters in the following way:
var result = db.SqlScalar<int>("EXEC DummyScalar #Times", new { Times = (int?)null });
In my opinion you can describe it as a defect on github and I can make pull request.

Picking out Just JSON Data Returned from ASP.NET MVC3 controller Update

I've got data returned from my JavaScript client that just includes the data that has changed. That is, I may have an array with each row containing 10 columns of JSON downloaded, but on the Update, only the data that is returned to me is the data that got updated. On my update, I only want to update those columns that are changed (not all of them).
In other words, I have code like below but because I'm passing in an instance of the "President" class, I have no way of knowing what actually came in on the original JSON.
How can I just update what comes into my MVC3 update method and not all columns. That is, 8 of the columns may not come in and will be null in the "data" parameter passed in. I don't want to wipe out all my data because of that.
[HttpPost]
public JsonResult Update(President data)
{
bool success = false;
string message = "no record found";
if (data != null && data.Id > 0)
{
using (var db = new USPresidentsDb())
{
var rec = db.Presidents.FirstOrDefault(a => a.Id == data.Id);
rec.FirstName = data.FirstName;
db.SaveChanges();
success = true;
message = "Update method called successfully";
}
}
return Json(new
{
data,
success,
message
});
}
rec.FirstName = data.FirstName ?? rec.FirstName;
I would use reflection in this case because the code will be too messy like
if (data.FirstName != null)
rec.FirstName = data.FirstName
.
.
.
and so on for all the fields
Using reflection, it would be easier to do this. See this method
public static void CopyOnlyModifiedData<T>(T source, ref T destination)
{
foreach (var propertyInfo in source.GetType().GetProperties())
{
object value = propertyInfo.GetValue(source, null);
if (value!= null && !value.GetType().IsValueType)
{
destination.GetType().GetProperty(propertyInfo.Name, value.GetType()).SetValue(destination, value, null);
}
}
}
USAGE
CopyOnlyModifiedData<President>(data, ref rec);
Please mind that, this won't work for value type properties.

Check if a key is available in Flex

I have a dictionary with objects as keys. How can I check if specific object is available in the dictionary?
hasOwnProperty won't work if the key is an object rather than a string.
checking that the value is null won't work if the key is in the dictionary, but with a null value.
The 'in' operator seems to work all the time.
var d:Dictionary = new Dictionary();
var a:Object = new Object();
d[a] = 'foo';
var b:Object = new Object();
d[b] = null;
var c:Object = new Object();
trace(a in d);
trace(b in d);
trace(c in d);
Returns
true
true
false
I believe this is a 'more correct' answer than the one posted above.
var b:Dictionary = new Dictionary();
if(b[key] != null) {
}
You can use array syntax and see if the value is null,
assertTrue(myDict["key"] == null)
If nulls are allowed values, use the hasOwnProperty method.
assertTrue(myDict.hasOwnProperty("key")==true)
Adobe, why don't you have a keyExists() function?
The most proper way is to compare the returned value with undefined:
if (dict["key"] !== undefined)
{
// do code when value does exist
}
as a key with a null associated value could exist in a dictionary.
Here is a good article that explains the topic.
You can use in to check for existing keys:
if ('key' in dict)
{
// do something
}
It works with object keys as well:
if (obj in dict)
{
// do something
}
Note that "obj" must be an existing object (defined or not) or it won't compile.

How do I dynamically instantiate a class, and set a property at runtime in Flex 3?

Using org.as3commons.reflect I can look-up the class name, and instantiate a class at runtime. I also have (non-working) code which invokes a method. However, I really want to set a property value. I'm not sure if properties are realized as methods internally in Flex.
I have a Metadata class which stores 3 pieces of information: name, value, and type (all are strings). I want to be able to loop through an Array of Metadata objects and set the corresponding properties on the instantiated class.
package com.acme.reporting.builders
{
import com.acme.reporting.model.Metadata;
import mx.core.UIComponent;
import org.as3commons.reflect.ClassUtils;
import org.as3commons.reflect.MethodInvoker;
public class UIComponentBuilder implements IUIComponentBuilder
{
public function build(metadata:Array):UIComponent
{
var typeClass:Class = ClassUtils.forName(getTypeName(metadata));
var result:* = ClassUtils.newInstance(typeClass);
for each (var m:Metadata in metadata)
{
if (m.name == "type")
continue;
// Attempting to invoke as method,
// would really like the property though
var methodInvoker:MethodInvoker = new MethodInvoker();
methodInvoker.target = result;
methodInvoker.method = m.name;
methodInvoker.arguments = [m.value];
var returnValue:* = methodInvoker.invoke(); // Fails!
}
return result;
}
private static function getTypeName(metadata:Array):String
{
if (metadata == null || metadata.length == 0)
throw new ArgumentError("metadata is null or empty");
var typeName:String;
// Type is usually the first entry
if (metadata.length > 1 && metadata[0] != null && metadata[0].name == "type")
{
typeName = metadata[0].value;
}
else
{
var typeMetadata:Array = metadata.filter(
function(element:*, index:int, arr:Array):Boolean
{
return element.name == "type";
}
);
if (typeMetadata == null || typeMetadata.length != 1)
throw new ArgumentError("type entry not found in metadata");
typeName = typeMetadata[0].value;
}
if (typeName == null || typeName.length == 0)
throw new Error("typeName is null or blank");
return typeName;
}
}
}
Here's some usage code:
var metadata:Array = new Array();
metadata[0] = new Metadata("type", "mx.controls.Text", null);
metadata[1] = new Metadata("text", "Hello World!", null);
metadata[2] = new Metadata("x", "77", null);
metadata[3] = new Metadata("y", "593", null);
this.addChild(new UIComponentBuilder().build(metadata));
I realize that I have to declare a dummy variable of the type I was to instantiate, or use the -inculde compiler directive. An unfortunate drawback of Flex.
Also, right now there's code to account for typecasting the value to it's specified type.
Dynamic execution in AS3 is much simpler than in other languages. This code:
var methodInvoker:MethodInvoker = new MethodInvoker();
methodInvoker.target = result;
methodInvoker.method = m.name;
methodInvoker.arguments = [m.value];
var returnValue:* = methodInvoker.invoke(); // Fails!
can be simplified to this:
var returnValue:* = result[method](m.value);
EDIT:
Since it's a property, it would be done like this:
result[method] = m.value;
and there is no return value (well, you can call the getter again but it should just return m.value unless the setter/getter do something funky.

Resources