mercredi 24 juillet 2019

Purging files and SQL database logs using Factory Method in C#

I am building an application (in C#) using Factory Method to be able to purge files and databases logs that are older than a certain day. I am using Factory method to contain all my purge processes in one central location/application. This is currently what I have so far.

public interface IPurger
{
  void Purge() ;
}

public enum PurgeType
{
  File,
  Database,
}

public class FilePurger : IPurger
{
  public void Purge()
  {
      var files = new DirectoryInfo(@"folderpath").GetFiles();
      foreach (var file in files)
      {
          if (DateTime.Now - file.CreationTime > TimeSpan.FromDays(7))
          {
              File.Delete(file.FullName);
          }
      }
  }
}

public class DbPurger : IPurger
{
  public void Purge()
  {
            using (SqlConnection mySqlConnection = new SqlConnection("server=MYSERVER;database=MYDATABASE;uid=UID;pwd=PASSWORD"))
            {

                using (SqlCommand mySqlCmd = new SqlCommand("dbo.OrderHeaders_Delete", mySqlConnection))
                {

                    mySqlCmd.CommandType = CommandType.StoredProcedure;    
                    mySqlCmd.Parameters.Add("@OlderThanDays", SqlDbType.Int).Value = "7";

                    mySqlConnection.Open();
                    mySqlCmd.ExecuteNonQuery();

                }
            }  
  }
}

public class PurgerFactory
{
  public IPurger CreatePurger(PurgeType type)
  {
    switch(type)
    {
      case PurgeType.File:
        return new FilePurger() ;
      case PurgeType.Database:
        return new DatabsePurger() ;
      default:
        throw new NotImplementedException() ;
    }
  }
}

Currently, the dependencies/parameters for each of the processes are hard coded. The idea is to create a database table in SQL that contains all the dependencies/parameters info such as file path, connection string, older than days, etc. Using a Poco object, the table will connect to the Factory, which will then, using the information from the table, decide which process it needs to execute and will do so accordingly. I'd like to do it this way so that if there's a new log directory/database I'd like to have it purge, I can just add it to the dependencies/parameters table, and the application will pick it up and perform the purge.

I'm beginner developer and I've never worked with Factory methods before, so I would appreciate any help in explaining how I would implement this concept.

Aucun commentaire:

Enregistrer un commentaire