Is there anything wrong with this database class's execute query function? - asp.net

So I have this old code being used, that runs simple ExecuteNonQuery command for database calls. I'm using DbConnection, DbTransaction and other System.Data.Common commands.
I seem to get a lot of Null Reference errors whenever I use the function in certain parts of the project, though it seems fine in other parts. I think it has to do with opening connections manually or some problem with calling it, but I'm wondering if the function itself is badly designed originally (shouldn't there be a way to fix any problems in the way it is called?)
I feel when transactions are involved, these null reference errors come up more often, I think the error I get is null exception at "_command = _db.GetStoredProcCommand(storedProcedure);" inside the following function. But that stored procedure does exist, so it makes no sense.
public List<OutputParameter> execute(String storedProcedure, StoredProcedureParameter[] sqlParameters)
{
try
{
List<OutputParameter> outputParameters = new List<OutputParameter>();
_command = _db.GetStoredProcCommand(storedProcedure);
for (int x = 0; x < sqlParameters.GetLength(0); x++)
{
if (sqlParameters[x] != null)
{
StoredProcedureParameter sqlParameter = sqlParameters[x];
String param = sqlParameter.ParameterName;
DbType dbType = sqlParameter.DbType;
object value = sqlParameter.Value;
if (sqlParameter.IsOutputParam)
{
_db.AddOutParameter(_command, param, dbType, 32);
OutputParameter outputParameter = new OutputParameter(param);
outputParameters.Add(outputParameter);
}
else
_db.AddInParameter(_command, param, dbType, value);
}
}
if (_transaction == null)
_db.ExecuteNonQuery(_command);
else
_db.ExecuteNonQuery(_command, _transaction);
foreach (OutputParameter op in outputParameters)
{
op.ParameterValue = _db.GetParameterValue(_command, op.ParameterName);
}
return outputParameters;
}
catch (SqlException sqle)
{
throw new DataAccessException(sqle.ToString());
}
catch (Exception e)
{
throw new DataAccessException(e.ToString());
}
}

Your _command variable appears to be a field and as such a shared member.
As such your code is very susceptible to multithreading issues (if two functions call this class with different stored procedures, what happens?).
A Command should also be closed and disposed of properly, which is not happening in your code, not explicitly anyways.

If you are getting a null reference exception in the line _command = _db.GetStoredProcCommand(storedProcedure); then the only thing that can be null there is _db. The storedProcedure is just a parameter and _command could happily be null without a problem.
Since you aren't actually doing anything in the code to make sure that _db exists and is valid, open, etc. then this is most likely the problem.

Related

DictTable CallObject

I am using the following code to dynamically execute calls to a table method that may or may not be present.
However, it always returns Error executing code: myTableName table does not have method 'myUpdateMethod'.
Dicttable dictTable;
Common common;
ExecutePermission perm;
perm = new ExecutePermission();
dictTable= new DictTable(tableName2Id('myTableName'));
if (dictTable != null)
{
common = dictTable.makeRecord();
// Grants permission to execute the
// DictTable.callObject method. DictTable.callObject runs
// under code access security.
perm.assert();
dictTable.callObject('myUpdateMethod', common);
}
// Close the code access permission scope.
CodeAccessPermission::revertAssert();
These objects are in different models, but just for kicks I tried making a reference between the two models to see if it made a difference. It did not fix the issue.
Thanks
Changed the method being called from static to non-static.
Started working, then found the callStatic() equivalent.
Here is the code I ended up using for the non-static method, which has no params.
Dicttable dictTable;
Common common;
ExecutePermission perm;
perm = new ExecutePermission();
dictTable= new DictTable(tableName2Id('MyTableName'));
if (dictTable != null)
{
common = dictTable.makeRecord();
// Grants permissions
perm.assert();
if (dictTable.doesMethodExist('myMethodName'))
{
dictTable.callObject('myMethodName', common);
}
}
// Close the code access permission scope.
CodeAccessPermission::revertAssert();

How do you evaluate boolean and then execute statements in java 8 with Optional?

How can I refactor this snippet in Java 8 Optional? Can I use map with OrElseThrow for this? What is a cleaner way of writing this code?
public void updateMyDao(MyObj objToUpdate) {
if(myOptional.isPresent()) {
MyDao oq = myOptional.get();
if(!oq.getReferenceId().equals(objToUpdate.getId()))
throw new RuntimeException("Bad Move!");
oq.setAttribute(objToUpdate.getAttribute());
.....
.....
} else {
throw new RuntimeException("Entity was not found");
}
}
IMHO there are three reasonable scenarios for Optional:
Do something if there is a value
Provide a default value otherwise
The absence of a value is an error condition, in which case you want to fail fast
Your scenario falls into the last category so I would simply write:
MyDao oq = myOptional.orElseThrow(() -> new RuntimeException("Entity was not found");
if(!oq.getReferenceId().equals(objToUpdate.getId()))
throw new RuntimeException("Bad Move!");
oq.setAttribute(objToUpdate.getAttribute());
Of course, it's appealing to use methods like ifPresent, filter or map, but in your case, why would you want to continue when the application is in a faulty state. Now if you wouldn't throw an exception if the entity wasn't found, then the situation would be different.
Something like oq.checkMove(objToUpdate.getId()) could make sense. That would eliminate the if and make the code more expressive.
Don't know where did you create the Optional object. But your current code can be shortened using orElseThrow():
MyDao oq = myOptional.orElseThrow(() -> new RuntimeException("Entity was not found"));
if(!oq.getReferenceId().equals(objToUpdate.getId()))
throw new RuntimeException("Bad Move!");
oq.setAttribute(objToUpdate.getAttribute());

ILGenerator. Whats wrong with this Code

I am trying to build a dynamic Property Accessor. Want something which is like really fast as close to calling the actually Property. Dont want to go the Reflection route as its very slow. So i opted to using DynamicAssembly and inject IL using ILGenerator. Below is the ILGenerator related code which seems to work
Label nulllabel = getIL.DefineLabel();
Label returnlabel = getIL.DefineLabel();
//_type = targetGetMethod.ReturnType;
if (methods.Count > 0)
{
getIL.DeclareLocal(typeof(object));
getIL.DeclareLocal(typeof(bool));
getIL.Emit(OpCodes.Ldarg_1); //Load the first argument
//(target object)
//Cast to the source type
getIL.Emit(OpCodes.Castclass, this.mTargetType);
//Get the property value
foreach (var methodInfo in methods)
{
getIL.EmitCall(OpCodes.Call, methodInfo, null);
if (methodInfo.ReturnType.IsValueType)
{
getIL.Emit(OpCodes.Box, methodInfo.ReturnType);
//Box if necessary
}
}
getIL.Emit(OpCodes.Stloc_0); //Store it
getIL.Emit(OpCodes.Br_S,returnlabel);
getIL.MarkLabel(nulllabel);
getIL.Emit(OpCodes.Ldnull);
getIL.Emit(OpCodes.Stloc_0);
getIL.MarkLabel(returnlabel);
getIL.Emit(OpCodes.Ldloc_0);
}
else
{
getIL.ThrowException(typeof(MissingMethodException));
}
getIL.Emit(OpCodes.Ret);
So above get the first argument which is the object that contains the property. the methods collection contains the nested property if any. for each property i use EmitCall which puts the the value on the stack and then i try to box it. This works like a charm.
The only issue is if you have a property like Order.Instrument.Symbol.Name and assume that Instrument object is null. Then the code will throw an null object exception.
So this what i did, i introduced a null check
foreach (var methodInfo in methods)
{
getIL.EmitCall(OpCodes.Call, methodInfo, null);
getIL.Emit(OpCodes.Stloc_0);
getIL.Emit(OpCodes.Ldloc_0);
getIL.Emit(OpCodes.Ldnull);
getIL.Emit(OpCodes.Ceq);
getIL.Emit(OpCodes.Stloc_1);
getIL.Emit(OpCodes.Ldloc_1);
getIL.Emit(OpCodes.Brtrue_S, nulllabel);
getIL.Emit(OpCodes.Ldloc_0);
if (methodInfo.ReturnType.IsValueType)
{
getIL.Emit(OpCodes.Box, methodInfo.ReturnType);
//Box if necessary
}
}
Now this code breaks saying That the object/memory is corrupted etc. So what exactly is wrong with this code. Am i missing something here.
Thanks in Advance.
Previously, if you had consecutive properties P returning string and then Q returning int, you would get something like this:
...
call P // returns string
call Q // requires a string on the stack, returns an int
box
...
Now you have something like this:
...
call P // returns string
store // stores to object
... // load, compare to null, etc.
load // loads an *object*
call Q // requires a *string* on the stack
store // stores to object *without boxing*
...
So I see two clear problems:
You are calling methods in such a way that the target is only known to be an object, not a specific type which has that method.
You are not boxing value types before storing them to a local of type object.
These can be solved by reworking your logic slightly. There are also a few other minor details you could clean up:
Rather than ceq followed by brtrue, just use beq.
There's no point in doing Stloc_1 followed by Ldloc_1 rather than just using the value on the stack since that local isn't used anywhere else.
Incorporating these changes, here's what I'd do:
Type finalType = null;
foreach (var methodInfo in methods)
{
finalType = methodInfo.ReturnType;
getIL.EmitCall(OpCodes.Call, methodInfo, null);
if (!finalType.IsValueType)
{
getIL.Emit(OpCodes.Dup);
getIL.Emit(OpCodes.Ldnull);
getIL.Emit(OpCodes.Beq_S, nulllabel);
}
}
if (finalType.IsValueType)
{
getIL.Emit(OpCodes.Box, methodInfo.ReturnType);
//Box if necessary
}
getIL.Emit(OpCodes.Br_S, returnLabel);
getIL.MarkLabel(nulllabel);
getIL.Emit(OpCodes.Pop);
getIL.Emit(OpCodes.Ldnull);
getIL.MarkLabel(returnlabel);
Note that we can get rid of both locals since we now just duplicate the top value on the stack before comparing against null.

SQL statement's placeholders that is not replaced leads to "Cannot update '#columnName'; field not updateable"

I'm writing some code updating database with a SQL statement that has some placeholders . But it doesn't seem to update these placeholders.
I got the following error:
Cannot update '#columnName'; field not updateable
Here is the method:
public void updateDoctorTableField(string columnName, string newValue, string vendorNumber) {
sqlStatement = "update Doctor set #columnName = #newValue where `VENDOR #` = #vendorNumber;";
try {
_command = new OleDbCommand(sqlStatement, _connection);
_command.Parameters.Add("#columnName", OleDbType.WChar).Value = columnName;
_command.Parameters.Add("#newValue", OleDbType.WChar).Value = newValue;
_command.Parameters.Add("#vendorNumber", OleDbType.WChar).Value = vendorNumber;
_command.ExecuteNonQuery();
} catch (Exception ex) {
processExeption(ex);
} finally {
_connection.Close();
}
}
Not all parts of the query are parameterisable.
You can't parametrise the name of the column. This needs to be specified explicitly in your query text.
If this is sent via user input you need to take care against SQL Injection. In fact in any event it would be best to check it against a whitelist of known valid column names.
The reason the language does not allow for parameters for things like table names, column names and such is exactly the same reason why your C# program does not allow for substitution of variables in the code. Basically your question can be rephrased like this in a C# program:
class MyClass
{
int x;
float y;
string z;
void DoSomething(string variableName)
{
this.#variable = ...
}
}
MyCLass my = new MyClass();
my.DoSomething("x"); // expect this to manuipulate my.x
my.DoSomething("y"); // expect this to manuipulate my.y
my.DoSomething("z"); // expect this to manuipulate my.z
This obviously won't compile, because the compiler cannot generate the code. Same for T-SQL: the compiler cannot generate the code to locate the column "#columnName" in your case. And just as in C# you would use reflection to do this kind of tricks, in T-SQL you would use dynamic SQL to achieve the same.
You can (and should) use the QUOTENAME function when building your dynamic SQL to guard against SQL injection.

Is it possible to find the function and/or line number that caused an error in ActionScript 3.0 without using debug mode?

I'm currently trying to implement an automated bug reporter for a Flex application, and would like to return error messages to a server along with the function/line number that caused the error. Essentially, I'm trying to get the getStackTrace() information without going into debug mode, because most users of the app aren't likely to have the debug version of flash player.
My current method is using the UncaughtErrorEvent handler to catch errors that occur within the app, but the error message only returns the type of error that has occurred, and not the location (which means it's useless). I have tried implementing getStackTrace() myself using a function name-grabber such as
private function getFunctionName (callee:Function, parent:Object):String {
for each ( var m:XML in describeType(parent)..method) {
if ( this[m.#name] == callee) return m.#name;
}
return "private function!";
}
but that will only work because of arguments.callee, and so won't go through multiple levels of function calls (it would never get above my error event listener).
So! Anyone have any ideas on how to get informative error messages through the global
error event handler?
EDIT: There seems to be some misunderstanding. I'm explicitly avoiding getStackTrace() because it returns 'null' when not in debug mode. Any solution that uses this function is what I'm specifically trying to avoid.
Just noticed the part about "I don't want to use debug." Well, that's not an option, as the non-debug version of Flash does not have any concept of a stack trace at all. Sucks, don't it?
Not relevant but still cool.
The rest is just for with the debug player.
This is part of my personal debug class (strangely enough, it is added to every single project I work on). It returns a String which represents the index in the stack passed -- class and method name. Once you have those, line number is trivial.
/**
* Returns the function name of whatever called this function (and whatever called that)...
*/
public static function getCaller( index:int = 0 ):String
{
try
{
throw new Error('pass');
}
catch (e:Error)
{
var arr:Array = String(e.getStackTrace()).split("\t");
var value:String = arr[3 + index];
// This pattern matches a standard function.
var re:RegExp = /^at (.*?)\/(.*?)\(\)/ ;
var owner:Array = re.exec(value);
try
{
var cref:Array = owner[1].split('::');
return cref[ 1 ] + "." + owner[2];
}
catch( e:Error )
{
try
{
re = /^at (.*?)\(\)/; // constructor.
owner = re.exec(value);
var tmp:Array = owner[1].split('::');
var cName:String = tmp.join('.');
return cName;
}
catch( error:Error )
{
}
}
}
return "No caller could be found.";
}
As a side note: this is not set up properly to handle an event model -- sometimes events present themselves as either not having callers or as some very weird alternate syntax.
You don't have to throw an error to get the stack trace.
var myError:Error = new Error();
var theStack:String = myError.getStackTrace();
good reference on the Error class
[EDIT]
Nope after reading my own reference getStackTrace() is only available in debug versions of the flash player.
So it looks like you are stuck with what you are doing now.

Resources