0

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

1 Answer 1

3

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");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.