mercredi 10 juillet 2019

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

I would like to build an application (in C#) using Factory Method to be able to purge files and databases logs that are older than a certain day. I want to use Factory method because I think it would be handy in allowing me to contain all my purge processes in one central location/application.

I would use the following code to purge the files:

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

And I would use the following stored procedure, to purge the database logs:

 GO
   SET ANSI_NULLS ON
   GO
   SET QUOTED_IDENTIFIER ON
   GO
   CREATE PROCEDURE [dbo].[OrderHeaders_Delete]
       @OlderThanDays int
   AS
   BEGIN
       DELETE FROM dbo.OrderHeader 
       WHERE LastUpdate < DATEADD(d, @OlderThanDays * -1, GETDATE());
   END

Passed using:

 static void Main(string[] args)
        {
            SqlConnection mySqlConnection = new SqlConnection(
                "server=MYSERVER;database=MYDATABASE;uid=UID;pwd=PASSWORD");

            SqlCommand mySqlCmd = mySqlConnection.CreateCommand();
            mySqlCmd.CommandText = "EXECUTE OrderHeaders_Delete @OlderThanDays";
            mySqlCmd.Parameters.Add("@OlderThanDays", SqlDbType.Int).Value = "7";
            mySqlConnection.Open();
            mySqlCmd.ExecuteNonQuery();
            mySqlConnection.Close();                
        }

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

The application would know what to do by the type. The application would query databases tables to build the proper objects and execute the purges.

PurgeType:
-File
-Database

PurgeDetail:
-What to purge
-How To purge it

Aucun commentaire:

Enregistrer un commentaire