user2431800
user2431800

Reputation: 3

asp.net Passing name of method as parameter to another method

I tried to find answer how to use delegate for this example, but still I don't know how to use it for my code redundancy. I have this code which is repeated for each dbAction in my aplication:

public bool someDBMethod(params)
{
logDTO ldto = new logDTO("some text");
try
{
  if (DALmethod(params)) //DB operation is successfull
  {
    Log.insertLog(ldto); //inserrt log to DB
    return true;
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));
    throw new Exception (ex.Message);
  }
 catch (Exception ex)
 {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));
    throw new Exception (ex.Message);
 }

}

This code is the same for different DB opperations except lines

logDTO ldto = new logDTO("some text");

if (DALmethod(params)) //DB operation is successfull

where I create DAL specific log and call the DAL method for insert/update/delete to database. Parameters for these DAL method aren't the same, but I could use some wrapper.

I would like to call for any DAL method

result = someDBMethod(DALmethod m, params p, logDTO l)

Thanks for your help

Upvotes: 0

Views: 533

Answers (1)

dm88
dm88

Reputation: 382

you could pass a Func<> as argument to your method.

public bool someDBMethod(Func<bool> callDalMethod, string message)
{
logDTO ldto = new logDTO(message);
try
{
  if (callDallMethod()) //DB operation is successfull
  {
    Log.insertLog(ldto); //inserrt log to DB
    return true;
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR_SQL, ex.Message));
    throw new Exception (ex.Message);
  }
 catch (Exception ex)
 {
    Log.insertLog(changeLogStatus(ldto, errStatusEnum.ERR, ex.Message));
    throw new Exception (ex.Message);
 }

Call this method:

someDBMethod(() => myDbMethod(param1, param 2), "message text");

Upvotes: 3

Related Questions