diff --git a/Source Code/FileExtract.cs b/Source Code/FileExtract.cs new file mode 100644 index 0000000..0f214ae --- /dev/null +++ b/Source Code/FileExtract.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TeamHobby.HobbyProjectGenerator.DataAccess; +using TeamHobby.HobbyProjectGenerator.UserManagement; + +namespace main +{ + internal class FileExtract + { + public static void Main(string[] args) + { + string[] lines = { "First line", "Second line", "Third line" }; + using StreamWriter file = new ("BulkRequest.txt"); + + var serviceTest = new AccountService(); + string dbType = "sql"; + RDSFactory dbFactory = new RDSFactory(); + + + // Testing Data Access Layer + string dbInfo = "DRIVER={MariaDB ODBC 3.1 Driver};" + + "TCPIP=1;" + + "SERVER=localhost;" + + "DATABASE=hobby;" + + "UID=root;" + + "PASSWORD=hobby;" + + "OPTION=3"; + IDataSource datasource = dbFactory.getDataSource(dbType, dbInfo); + + // Create a file + for (int i = 0; i < 10000; i++) + { + var TestAcc = new UserAccount("newUser" + $"{i}", "4567", $"email{i}@a.com", "regular", DateTime.Now); + file.Write(serviceTest.CreateUserRecord(TestAcc, "Rifat", datasource)); + } + } + } +} diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.Archive/ArchiveManager.cs b/Source Code/TeamHobby.HobbyProjectGenerator.Archive/ArchiveManager.cs index 2eee2fe..051ec59 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.Archive/ArchiveManager.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.Archive/ArchiveManager.cs @@ -72,29 +72,6 @@ namespace TeamHobby.HobbyProjectGenerator.Archive } } - // Method overload to take in a specific path - public string CreateOutFileName(string archivePath) - { - try - { - //string path = archivePath + "\\HobbyArchive"; - Console.WriteLine("The current directory is {0}", archivePath); - //string date = DateTime.Now.ToString("M_d_yyyy_H:mm:ss"); - string date = DateTime.Now.ToString("M_d_yyyy"); - string fileName = date + "_archive.csv"; - string filePath = Path.Combine(archivePath, fileName); - - Console.WriteLine("Date: {0}", date); - Console.WriteLine("Filepath: {0}", filePath); - return filePath; - } - catch - { - Console.WriteLine("ArchiveCon: Creating a file name failed. "); - return ""; - } - } - // put everything toget here public bool Controller(){ diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.Archive/TeamHobby - Backup.HobbyProjectGenerator.Archive.csproj b/Source Code/TeamHobby.HobbyProjectGenerator.Archive/TeamHobby - Backup.HobbyProjectGenerator.Archive.csproj new file mode 100644 index 0000000..65fcde5 --- /dev/null +++ b/Source Code/TeamHobby.HobbyProjectGenerator.Archive/TeamHobby - Backup.HobbyProjectGenerator.Archive.csproj @@ -0,0 +1,25 @@ + + + + net6.0 + enable + enable + AnyCPU;x86 + + + + + + + + + + + + + + + + + + diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.ArchiveTests/ArchivingTests.cs b/Source Code/TeamHobby.HobbyProjectGenerator.ArchiveTests/ArchivingTests.cs index 7da2223..9775996 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.ArchiveTests/ArchivingTests.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.ArchiveTests/ArchivingTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Data.Odbc; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -197,6 +198,98 @@ namespace TeamHobby.HobbyProjectGenerator.ArchiveTests } + public void RemoveEntriesTest(IDataSource sqlDAO) + { + Console.WriteLine("TESTING - REMOVE ENTRIES"); + + // Arrange + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + SqlDAO sqlDS = null; + + if (sqlDAO.GetType() == typeof(SqlDAO)) + { + sqlDS = (SqlDAO)sqlDAO; + //sqlDS.GetConnection().Open(); + + // Act + Console.WriteLine("\nInserting into archive..."); + sqlDS.WriteData("INSERT into log(LtimeStamp, LvName, catname, userop, logmessage) values " + + "('2021-08-07 23:00:00', 'Info', 'View', 'create some projects', 'new account created')," + + "('2021-06-04 23:00:00', 'Info', 'Business', 'create some projects', 'new projects made')," + + "('2021-07-02 23:00:00', 'Info', 'View', 'log out', 'log out successful')," + + "('2021-09-03 23:00:00', 'Info', 'Business', 'log in', 'log in successfully')," + + "('2021-10-20 23:00:00', 'Info', 'View', 'search for projects', 'result return')," + + "('2021-09-03 23:00:00', 'Info', 'Business', 'log in', 'log in successfully');"); + + OdbcDataReader odbcObj = (OdbcDataReader)sqlDS.ReadData("SELECT * FROM log WHERE DATEDIFF(CURRENT_TIMESTAMP, log.LtimeStamp) > 30;"); + + int count = 0; + while (odbcObj.Read()) { ++count; } + Console.WriteLine("Number of entries > 30 days old: " + count); + + Console.WriteLine("\nRemoving entries from archive..."); + sqlDS.RemoveEntries(); + + odbcObj = (OdbcDataReader)sqlDS.ReadData("SELECT * FROM log WHERE DATEDIFF(CURRENT_TIMESTAMP, log.LtimeStamp) > 30;"); + + count = 0; + while (odbcObj.Read()) { ++count; } + Console.WriteLine("Number of entries > 30 days old: " + count); + + // Assert + bool expectedVal = true; + bool actualVal = !Convert.ToBoolean(count); + + if (expectedVal == actualVal) + { + Console.WriteLine("\nExpected: {0}, Actual: {0}. Entries removed correctly.", expectedVal, actualVal); + } + else + { + Console.WriteLine("\nExpected: {0}, Actual: {1}. Entries not removed.", expectedVal, actualVal); + } + + //sqlDS.GetConnection().Close(); + } + + return; + } + + public void RemoveOutputFileTest(IDataSource sqlDAO) + { + Console.WriteLine("TESTING - REMOVE OUTPUT FILE\n"); + + // Arrange + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + SqlDAO sqlDS = null; + + if (sqlDAO.GetType() == typeof(SqlDAO)) + { + sqlDS = (SqlDAO)sqlDAO; + } + + // Act + string filepath = archiveManager.CreateOutFileName(); + Console.WriteLine("\nRemoving file..."); + sqlDS.RemoveOutputFile(filepath); + + // Assert + bool expectedVal = false; + bool actualVal = File.Exists(filepath); + Console.WriteLine("Checking if file exists: " + actualVal); + + if (expectedVal == actualVal) + { + Console.WriteLine("\nExpected: {0}, Actual: {0}. Output file removed correctly.", expectedVal, actualVal); + } + else + { + Console.WriteLine("\nExpected: {0}, Actual: {1}. Output file NOT removed.", expectedVal, actualVal); + } + + return; + } + public static void Main(string[] args) { string dbInfo = "DRIVER={MariaDB ODBC 3.1 Driver};" + @@ -206,6 +299,7 @@ namespace TeamHobby.HobbyProjectGenerator.ArchiveTests "PASSWORD=Teamhobby;" + "OPTION=3"; SqlDAO sqlDAO = new SqlDAO(dbInfo); + sqlDAO.GetConnection().Open(); //ArchiveManager archiveManager = new ArchiveManager(sqlDAO); // Testing folder creation @@ -226,12 +320,21 @@ namespace TeamHobby.HobbyProjectGenerator.ArchiveTests Console.WriteLine(""); - // Testing clean up sequence //test.IsCleaningUpCompleted(sqlDAO); //Console.WriteLine("-----------------"); //Console.WriteLine(""); + // Testing remove entries + test.RemoveEntriesTest(sqlDAO); + Console.WriteLine("-----------------"); + Console.WriteLine(""); + + // Testing remove output file + test.RemoveOutputFileTest(sqlDAO); + Console.WriteLine("-----------------"); + Console.WriteLine(""); + sqlDAO.GetConnection().Close(); } } diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/SqlDAO.cs b/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/SqlDAO.cs index 949eb5d..487838e 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/SqlDAO.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/SqlDAO.cs @@ -68,10 +68,10 @@ namespace TeamHobby.HobbyProjectGenerator.DataAccess try { _conn.Open(); - + OdbcCommand command = new OdbcCommand(cmd, _conn); command.ExecuteNonQuery(); - + _conn.Close(); return true; @@ -111,7 +111,7 @@ namespace TeamHobby.HobbyProjectGenerator.DataAccess } finally { - _conn.Close(); + _conn.Close(); } } @@ -155,8 +155,10 @@ namespace TeamHobby.HobbyProjectGenerator.DataAccess // Check to see if the file is hidden or already compressed before compressing the file. if (atrribute != FileAttributes.Hidden && atrribute != FileAttributes.Compressed) { - using FileStream outputFile = File.Create(fileName + ".gz"); - + var compFileName = Path.ChangeExtension(fileName, ".gz"); + //using FileStream outputFile = File.Create(fileName + ".gz"); + using FileStream outputFile = File.Create(compFileName); + using GZipStream compressor = new GZipStream(outputFile, CompressionMode.Compress); origFile.CopyTo(compressor); diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/UiPrint.cs b/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/UiPrint.cs index 6d06cb8..d9f19aa 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/UiPrint.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.DataAccess/Implementations/UiPrint.cs @@ -6,6 +6,9 @@ namespace TeamHobby.HobbyProjectGenerator.DataAccess { public void UserManagementMenu(string username) { + // File must be within the main folder path + // Get the current directory. + string path = Directory.GetCurrentDirectory(); // Menu for all UserManagement options int menu = 0; Console.WriteLine("-------------------------------------\n"); @@ -23,6 +26,8 @@ namespace TeamHobby.HobbyProjectGenerator.DataAccess menu += 1; Console.WriteLine(menu + ") Enable an account.\n"); menu += 1; + Console.WriteLine(menu + $") Bulk operation from file within the directory.\n{path}\\BulkOps\n"); + menu += 1; Console.WriteLine(menu + ") View log path.\n"); menu += 1; Console.WriteLine(menu + ") View archive path.\n"); diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/AccountService.cs b/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/AccountService.cs index cf332f7..de6c7e8 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/AccountService.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/AccountService.cs @@ -15,14 +15,26 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement try { // Insert into users table - string sqlUser = $"INSERT INTO users (UserName, Password, Role, IsActive," + - $"CreatedBy, CreatedDate, Email) VALUES ('{newUser.username}', " + - $"'{newUser.password}','{newUser.role}', 1," + - $"'{CreatedBy}', NOW(),'{newUser.email}');"; + if (newUser.email == null || newUser.email == "NULL") + { + string sqlUser = $"INSERT INTO users (UserName, Password, Role, IsActive," + + $"CreatedBy, CreatedDate, Email) VALUES ('{newUser.username}', " + + $"'{newUser.password}','{newUser.role}', 1," + + $"'{CreatedBy}', NOW(),{newUser.email});"; - bool insertNewUser = dbSource.WriteData(sqlUser); - return insertNewUser; + bool insertNewUser = dbSource.WriteData(sqlUser); + return insertNewUser; + } + else + { + string sqlUser = $"INSERT INTO users (UserName, Password, Role, IsActive," + + $"CreatedBy, CreatedDate, Email) VALUES ('{newUser.username}', " + + $"'{newUser.password}','{newUser.role}', 1," + + $"'{CreatedBy}', NOW(),'{newUser.email}');"; + bool insertNewUser = dbSource.WriteData(sqlUser); + return insertNewUser; + } } catch (Exception ex) { @@ -34,13 +46,24 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement try { // Insert into users table - string sqlUser = $"UPDATE users t SET t.Password = '{editUser.password}', " + - $"t.Role = '{editUser.role}',t.Email = '{editUser.email}' " + - $"WHERE t.UserName = '{editUser.username}';"; + if (editUser.email == null || editUser.email == "NULL") + { + string sqlUser = $"UPDATE users t SET t.Password = '{editUser.password}', " + + $"t.Role = '{editUser.role}',t.Email = '{editUser.email}' " + + $"WHERE t.UserName = {editUser.username};"; - bool updateNewUser = dbSource.UpdateData(sqlUser); - return updateNewUser; + bool updateNewUser = dbSource.UpdateData(sqlUser); + return updateNewUser; + } + else + { + string sqlUser = $"UPDATE users t SET t.Password = '{editUser.password}', " + + $"t.Role = '{editUser.role}',t.Email = '{editUser.email}' " + + $"WHERE t.UserName = '{editUser.username}';"; + bool updateNewUser = dbSource.UpdateData(sqlUser); + return updateNewUser; + } } catch (Exception ex) { @@ -98,5 +121,181 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement return false; } } + public bool BulkOperation(string signedUser, IDataSource dbSource) + { + try + { + // Get the current directory. + string path = Directory.GetCurrentDirectory(); + // Open file reader stream + using StreamReader fileRead = new(path + "\\BulkOps\\Bulk.txt"); // path + "\\BulkOps\\{input}" + // Show location of the file being written + Console.WriteLine(path + "\\BulkOps\\Bulk.txt"); + + // List choices of operations + List ops = new List {"Create Account", "Edit Account", + "Delete Account", "Disable Account", "Enable Account"}; + + // List to hold file operation and credentials + List fileList = new List(); + string operation = ""; + string UN = ""; + string PWD = ""; + string Role = ""; + string Email = ""; + + // Loop through file rows + while (!fileRead.EndOfStream) + { + // Create variable to hold current line + string line = fileRead.ReadLine(); + + // Check if line is not empty and contains the separator + if (line != null && line.Contains(":")) + { + // Assign value to hold current line parameter + string value = line.Split(':')[1].Trim(); + + // Check what operation is being called + if (ops.Contains(value)) + { + // Add operation into temp + //Console.WriteLine("Found operation"); + //Console.WriteLine(value); + operation = value; + } + else + { + string checkCredential = line.Split(':')[0].Trim(); + //Console.WriteLine("Found credential"); + switch (checkCredential) + { + case "Username": + UN = value; + break; + case "Password": + PWD = value; + break; + case "Role": + Role = value; + break; + case "Email": + Email = value; + break; + default: + break; + } + } + } + else if(line != null) + { + switch (operation) + { + case "Create Account": + //Console.WriteLine(operation); + if (!String.IsNullOrEmpty(UN)) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Email, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + break; + case "Edit Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + if (String.IsNullOrEmpty(UN)) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Email, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + break; + case "Delete Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + if (String.IsNullOrEmpty(UN)) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Email, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + break; + case "Disable Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + if (String.IsNullOrEmpty(Role) && UN != null) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Email, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + else if (String.IsNullOrEmpty(Email) && UN != null) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Role); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + else if (String.IsNullOrEmpty(Role) && String.IsNullOrEmpty(Email) && UN != null) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + break; + case "Enable Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + if (String.IsNullOrEmpty(Role) && UN != null) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Email, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + else if (String.IsNullOrEmpty(Email) && UN != null) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Role); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + else if (String.IsNullOrEmpty(Role) && String.IsNullOrEmpty(Email) && UN != null) + { + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + break; + default: + break; + } + } + } + fileRead.Close(); + return true; + } + catch (Exception e) + { + Console.WriteLine("Error reading file"); + Console.WriteLine(e.Message); + return false; + } + } } } diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/SystemAccountManager.cs b/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/SystemAccountManager.cs index 49b0e48..4abe273 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/SystemAccountManager.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/SystemAccountManager.cs @@ -239,7 +239,6 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement case 2: // State what account is being edited string userName = newCredentials.GetUserName(); - string userRole = newCredentials.GetRole(); // Notify the user of what can be edited Console.WriteLine($"\n****The following information will be used to update {userName}"); @@ -304,11 +303,55 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement return "User does not exist"; } break; - // View logs + // Bulk operation through file case 6: + AccountService bulkOP = new AccountService(); + // Get path to defualt bin location + string path = Directory.GetCurrentDirectory(); + while (true) + { + // Get name of file and update path to correct folder + Console.WriteLine("Please input the name of the file:(Example.txt)"); + string filename = $"{path}\\BulkOps\\{Console.ReadLine()}"; + + // Get filesize + long fileSize = filename.Length; + long fileSizeGB = fileSize / (1024 * 1024); + //Console.WriteLine($"File size is {fileSize}kb"); + + // Check if input is empty + if (filename == null) + { + Console.WriteLine("Invalid file name.\n"); + } + // Check if file is over 2GB + else if (fileSizeGB > 2) + { + Console.WriteLine($"File size is {fileSizeGB}GB\n"); + Console.WriteLine("File is too large, please enter a smaller file.\n"); + } + else + { + // Begin bulk operation + Console.WriteLine("Running bulk operation..."); + bool bulkReq = bulkOP.BulkOperation(user.username, dbSource); + if (bulkReq is true) + { + Console.WriteLine("\nBulk operation complete"); + break; + } + else + { + return "Bulk operation failed"; + } + } + } + break; + // View logs + case 7: break; // View archive - case 7: + case 8: break; default: Console.WriteLine("Invalid input.\nPlease enter a valid option.\n"); diff --git a/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/UserAccount.cs b/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/UserAccount.cs index 58d6b13..e048653 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/UserAccount.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator.UserManagement/UserAccount.cs @@ -47,7 +47,25 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement } public string GetRole() { - Console.WriteLine("Please enter the role of the user:"); + while (true) + { + // List of possible roles + List roles = new List {"Admin", "regular" }; + // Get role + Console.WriteLine("Please enter the role of the user:(Admin or regular)"); + string? userRole = Console.ReadLine(); + // Check if passwords match + if (roles.Contains(userRole)) + { + return userRole; + } + else + { + Console.WriteLine("Not an available role.\n"); + } + } + + return Console.ReadLine(); } } @@ -65,26 +83,62 @@ namespace TeamHobby.HobbyProjectGenerator.UserManagement { _userName = un; _password = pwd; + _Role = "regular"; + _Email = "NULL"; _Time = TimeStamp; } + public UserAccount(string un, string pwd, string role) + { + if (String.IsNullOrEmpty(role)) + { + _Role = "regular"; + } + else { _Role = role; } + _userName = un; + _password = pwd; + _Email = "NULL"; + _Time = DateTime.UtcNow; + } public UserAccount(string un, string role) { _userName = un; _Role = role; + _Email = "NULL"; _Time = DateTime.UtcNow; } + public UserAccount(string un, string pwd, string Email, DateTime TimeStamp) + { + if (String.IsNullOrEmpty(Email)) + { + _Email = "NULL"; + } + else { _Email = Email; } + _userName = un; + _password = pwd; + _Role = "regular"; + _Time = TimeStamp; + } public UserAccount(string newUN, string newPWD, string Email, string role, DateTime newTime) { + if (String.IsNullOrEmpty(role)) + { + _Role = "regular"; + } + else { _Role = role; } + if (String.IsNullOrEmpty(Email)) + { + _Email = "NULL"; + } + else { _Email = Email; } _userName = newUN; _password = newPWD; - _Role = role; - _Email = Email; _Time = newTime; } public UserAccount() { _Role = "regular"; - _Time= DateTime.Now; + _Email = "NULL"; + _Time = DateTime.Now; } public string username { get { return _userName; } } diff --git a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.Archiving.xTests/ArchivingXUnitTest.cs b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.Archiving.xTests/ArchivingXUnitTest.cs new file mode 100644 index 0000000..5b04c84 --- /dev/null +++ b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.Archiving.xTests/ArchivingXUnitTest.cs @@ -0,0 +1,324 @@ +using System; +using System.Data.Odbc; +using System.Diagnostics; +using System.IO; +using System.Threading; +using TeamHobby.HobbyProjectGenerator.Archive; +using TeamHobby.HobbyProjectGenerator.DataAccess; +using Xunit; + +namespace TeamHobby.Archiving.xTests +{ + public class ArchivingXUnitTest + { + string dbInfo = "DRIVER={MariaDB ODBC 3.1 Driver};" + + "SERVER=localhost;" + + "DATABASE=hobby;" + + "UID=root;" + + "PASSWORD=Teamhobby;" + + "OPTION=3"; + + [Fact] + public void IsArchiveFolderCreated() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + string folderPath = @"C:/HobbyArchive"; + bool expectedVal = true; + + // Act + archiveManager.CreateArchiveFolder(); + + + // Assert + bool actualVal = Directory.Exists(folderPath); + Assert.Equal(expectedVal, actualVal); + // Cleaning up directory after test + try + { + Directory.Delete(folderPath, true); + } + catch + { + Console.WriteLine("Folder failed to be deleted"); + } + } + + [Fact] + public void IsFileNameCreated() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + string foldPath = @"C:\HobbyArchive"; + string fileName = DateTime.Now.ToString("M_d_yyyy") + "_archive.csv"; + string expectedFilePath = System.IO.Path.Combine(foldPath, fileName); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + + // Act + string actualFilePath = archiveManager.CreateOutFileName(); + + // Assert + + Assert.Equal(expectedFilePath, actualFilePath); + } + + [Fact] + public void IsCSVFileExist() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + SqlDAO sqlDS = null; + string folderPath = @"C:/HobbyArchive"; + + try + { + bool folderRes = archiveManager.CreateArchiveFolder(); + } + catch (Exception ex) + { + Console.WriteLine("Folder creation for copying failed"); + } + string filePath = archiveManager.CreateOutFileName(); + bool expectedVal = true; + + if (sqlDAO.GetType() == typeof(SqlDAO)) + { + sqlDS = (SqlDAO)sqlDAO; + } + + // Act + if (sqlDS != null) + { + try + { + sqlDS.CopyToFile(filePath); + } + catch (Exception ex) + { + Console.WriteLine("Copying to a file failed !!"); + Console.WriteLine(ex.Message); + } + } + + // Assert + bool actualVal = File.Exists(filePath); + Assert.Equal(expectedVal, actualVal); + + try + { + Directory.Delete(folderPath, true); + } + catch + { + Console.WriteLine("Folder failed to be deleted"); + } + } + + [Fact] + public void RemoveEntriesTest() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + OdbcDataReader odbcObj = null; + Object resultData = null; + bool expectedVal = false; + + sqlDAO.WriteData("INSERT into log(LtimeStamp, LvName, catname, userop, logmessage) values" + + "('2021-08-07 23:00:00', 'Info', 'View', 'create some projects', 'new account created')," + + "('2021-06-04 23:00:00', 'Info', 'Business', 'create some projects', 'new projects made')," + + "('2021-07-02 23:00:00', 'Info', 'View', 'log out', 'log out successful')," + + "('2021-09-03 23:00:00', 'Info', 'Business', 'log in', 'log in successfully')," + + "('2021-10-20 23:00:00', 'Info', 'View', 'search for projects', 'result return');"); + + // Act + sqlDAO.RemoveEntries(); + + // Assert + bool actualVal; + + resultData = sqlDAO.ReadData("SELECT * FROM log WHERE DATEDIFF(CURRENT_TIMESTAMP, log.LtimeStamp) > 30;"); + if ((resultData != null) && (resultData.GetType() == typeof(OdbcDataReader))) + { + odbcObj = (OdbcDataReader)resultData; + } + OdbcConnection conn = sqlDAO.GetConnection(); + actualVal = odbcObj.HasRows; + conn.Close(); + + Assert.Equal(expectedVal, actualVal); + + } + + + [Fact] + public void RemoveOutputFileTest() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + bool expectedVal = false; + //Thread.Sleep(5000); + + // Create the folder and the csv file for compressing + archiveManager.CreateArchiveFolder(); + string filepath = archiveManager.CreateOutFileName(); + sqlDAO.CopyToFile(filepath); + + // Act + if (sqlDAO != null) + { + sqlDAO.RemoveOutputFile(filepath); + } + + // Assert + bool actualVal = File.Exists(filepath); + Assert.Equal(expectedVal, actualVal); + } + + [Fact] + public void IsFileCompressed() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + + // Create the folder and the csv file to be compressed. + archiveManager.CreateArchiveFolder(); + string filePath = archiveManager.CreateOutFileName(); + sqlDAO.CopyToFile(filePath); + FileAttributes expectedAttribute = FileAttributes.Archive; + string compFilePath = Path.ChangeExtension(filePath, ".gz"); + + // Act + sqlDAO.CompressFile(filePath); + + // Assert + FileAttributes actualAttribute = File.GetAttributes(compFilePath); + Assert.Equal(expectedAttribute, actualAttribute); + + } + + [Fact] + public void IsArchive_Under_60s_10kRecords() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + var timer = new Stopwatch(); + double expectedVal = 60; + string folderPath = @"C:/HobbyArchive"; + + sqlDAO.WriteData("INSERT into log(LtimeStamp, LvName, catname, userop, logmessage) values" + + "('2021-08-07 23:00:00', 'Info', 'View', 'create some projects', 'new account created')," + + "('2021-06-04 23:00:00', 'Info', 'Business', 'create some projects', 'new projects made')," + + "('2021-07-02 23:00:00', 'Info', 'View', 'log out', 'log out successful')," + + "('2021-09-03 23:00:00', 'Info', 'Business', 'log in', 'log in successfully')," + + "('2021-10-20 23:00:00', 'Info', 'View', 'search for projects', 'result return');"); + + for (int i = 0; i < 11; i++) + { + sqlDAO.WriteData("INSERT INTO log(LtimeStamp, LvName, catName, userOP, logMessage) " + + "SELECT LtimeStamp, LvName, catName, userOP, logMessage FROM log WHERE DATEDIFF(CURRENT_TIMESTAMP, log.LtimeStamp) > 30;"); + } + + // Act + timer.Start(); + archiveManager.Controller(); + timer.Stop(); + + // Arrange + double actualVal = timer.ElapsedMilliseconds; + Assert.True((actualVal / 1000) < expectedVal); + + // Clean up resources after testing + try + { + Directory.Delete(folderPath, true); + } + catch + { + Console.WriteLine("Folder failed to be deleted"); + } + } + + [Fact] + public void IsArchive_Under_60s_10mRecords() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + var timer = new Stopwatch(); + double expectedVal = 60; + string folderPath = @"C:/HobbyArchive"; + + sqlDAO.WriteData("INSERT into log(LtimeStamp, LvName, catname, userop, logmessage) values" + + "('2021-08-07 23:00:00', 'Info', 'View', 'create some projects', 'new account created')," + + "('2021-06-04 23:00:00', 'Info', 'Business', 'create some projects', 'new projects made')," + + "('2021-07-02 23:00:00', 'Info', 'View', 'log out', 'log out successful')," + + "('2021-09-03 23:00:00', 'Info', 'Business', 'log in', 'log in successfully')," + + "('2021-10-20 23:00:00', 'Info', 'View', 'search for projects', 'result return');"); + + for (int i = 0; i < 18; i++) + { + sqlDAO.WriteData("INSERT INTO log(LtimeStamp, LvName, catName, userOP, logMessage) " + + "SELECT LtimeStamp, LvName, catName, userOP, logMessage FROM log WHERE DATEDIFF(CURRENT_TIMESTAMP, log.LtimeStamp) > 30;"); + } + + // Act + timer.Start(); + archiveManager.Controller(); + timer.Stop(); + + // Arrange + double actualVal = timer.ElapsedMilliseconds; + Assert.True((actualVal / 1000) < expectedVal); + + //Clean up resources after testing + try + { + Directory.Delete(folderPath, true); + } + catch + { + Console.WriteLine("Folder failed to be deleted"); + } + } + + [Fact] + public void IsArchiveOnFirstOfMonth() + { + // Arrange + + // Act + + // + } + + + [Fact] + public void IsWriteData() + { + // Arrange + SqlDAO sqlDAO = new SqlDAO(dbInfo); + ArchiveManager archiveManager = new ArchiveManager(sqlDAO); + var timer = new Stopwatch(); + double expectedVal = 60; + string folderPath = @"C:/HobbyArchive"; + + // Act + sqlDAO.WriteData("INSERT into log(LtimeStamp, LvName, catname, userop, logmessage) values" + + "('2021-08-07 23:00:00', 'Info', 'View', 'create some projects', 'new account created')," + + "('2021-06-04 23:00:00', 'Info', 'Business', 'create some projects', 'new projects made')," + + "('2021-07-02 23:00:00', 'Info', 'View', 'log out', 'log out successful')," + + "('2021-09-03 23:00:00', 'Info', 'Business', 'log in', 'log in successfully')," + + "('2021-10-20 23:00:00', 'Info', 'View', 'search for projects', 'result return');"); + + // Assert + Assert.True(true); + } + + } +} \ No newline at end of file diff --git a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.Archiving.xTests/TeamHobby.Archiving.xTests.csproj b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.Archiving.xTests/TeamHobby.Archiving.xTests.csproj new file mode 100644 index 0000000..308e40a --- /dev/null +++ b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.Archiving.xTests/TeamHobby.Archiving.xTests.csproj @@ -0,0 +1,27 @@ + + + + net6.0 + enable + + false + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.HobbyProjectGenerator.sln b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.HobbyProjectGenerator.sln index 60e405e..8ab06bf 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.HobbyProjectGenerator.sln +++ b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.HobbyProjectGenerator.sln @@ -19,6 +19,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TeamHobby.HobbyProjectGener EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TeamHobby.HobbyProjectGenerator.UserManagement", "..\TeamHobby.HobbyProjectGenerator.UserManagement\TeamHobby.HobbyProjectGenerator.UserManagement.csproj", "{2E7193B8-86B6-48DA-9671-CD84615A5F5D}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TeamHobby.HobbyProjectGenerator.Logging.Tests", "..\TeamHobby.HobbyProjectGenerator.Logging.Tests\TeamHobby.HobbyProjectGenerator.Logging.Tests.csproj", "{CA8D11CF-807C-4C90-A529-0371F73518F6}" +EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TeamHobby.HobbyProjectGenerator.ArchiveTests", "..\TeamHobby.HobbyProjectGenerator.ArchiveTests\TeamHobby.HobbyProjectGenerator.ArchiveTests.csproj", "{C5EBD1F8-C806-4BF9-B2D7-8876072630FD}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TeamHobby.UserManagement.xTests", "TeamHobby.UserManagement.xTests\TeamHobby.UserManagement.xTests.csproj", "{6D575AF1-C138-44C5-B701-5AEC4ACEAA7A}" @@ -28,6 +30,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution TeamHobby.HobbyProjectGenerator.csproj = TeamHobby.HobbyProjectGenerator.csproj EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TeamHobby.Archiving.xTests", "TeamHobby.Archiving.xTests\TeamHobby.Archiving.xTests.csproj", "{8C039F49-13D3-4AEE-A1C3-A880751852BB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -38,6 +42,7 @@ Global {5C5A44B4-EC3C-44F2-8F39-F917F8ED932F}.Release|Any CPU.ActiveCfg = Release|Any CPU {5C5A44B4-EC3C-44F2-8F39-F917F8ED932F}.Release|Any CPU.Build.0 = Release|Any CPU {75DED6C2-D404-4E71-A58B-0F616DB5C062}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {75DED6C2-D404-4E71-A58B-0F616DB5C062}.Debug|Any CPU.Build.0 = Debug|Any CPU {75DED6C2-D404-4E71-A58B-0F616DB5C062}.Release|Any CPU.ActiveCfg = Release|Any CPU {75DED6C2-D404-4E71-A58B-0F616DB5C062}.Release|Any CPU.Build.0 = Release|Any CPU {30C7EBF3-3957-46E5-86C1-C13356841ECA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -45,6 +50,7 @@ Global {30C7EBF3-3957-46E5-86C1-C13356841ECA}.Release|Any CPU.ActiveCfg = Release|Any CPU {30C7EBF3-3957-46E5-86C1-C13356841ECA}.Release|Any CPU.Build.0 = Release|Any CPU {B88ED0D9-72E2-4245-BD8F-856FF42E500C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B88ED0D9-72E2-4245-BD8F-856FF42E500C}.Debug|Any CPU.Build.0 = Debug|Any CPU {B88ED0D9-72E2-4245-BD8F-856FF42E500C}.Release|Any CPU.ActiveCfg = Release|Any CPU {B88ED0D9-72E2-4245-BD8F-856FF42E500C}.Release|Any CPU.Build.0 = Release|Any CPU {AA48A66C-FA36-4AF9-A782-CEC22838EB8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -55,13 +61,22 @@ Global {2E7193B8-86B6-48DA-9671-CD84615A5F5D}.Debug|Any CPU.Build.0 = Debug|Any CPU {2E7193B8-86B6-48DA-9671-CD84615A5F5D}.Release|Any CPU.ActiveCfg = Release|Any CPU {2E7193B8-86B6-48DA-9671-CD84615A5F5D}.Release|Any CPU.Build.0 = Release|Any CPU + {CA8D11CF-807C-4C90-A529-0371F73518F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA8D11CF-807C-4C90-A529-0371F73518F6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA8D11CF-807C-4C90-A529-0371F73518F6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA8D11CF-807C-4C90-A529-0371F73518F6}.Release|Any CPU.Build.0 = Release|Any CPU {C5EBD1F8-C806-4BF9-B2D7-8876072630FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C5EBD1F8-C806-4BF9-B2D7-8876072630FD}.Debug|Any CPU.Build.0 = Debug|Any CPU {C5EBD1F8-C806-4BF9-B2D7-8876072630FD}.Release|Any CPU.ActiveCfg = Release|Any CPU {C5EBD1F8-C806-4BF9-B2D7-8876072630FD}.Release|Any CPU.Build.0 = Release|Any CPU {6D575AF1-C138-44C5-B701-5AEC4ACEAA7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6D575AF1-C138-44C5-B701-5AEC4ACEAA7A}.Debug|Any CPU.Build.0 = Debug|Any CPU {6D575AF1-C138-44C5-B701-5AEC4ACEAA7A}.Release|Any CPU.ActiveCfg = Release|Any CPU {6D575AF1-C138-44C5-B701-5AEC4ACEAA7A}.Release|Any CPU.Build.0 = Release|Any CPU + {8C039F49-13D3-4AEE-A1C3-A880751852BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8C039F49-13D3-4AEE-A1C3-A880751852BB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8C039F49-13D3-4AEE-A1C3-A880751852BB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8C039F49-13D3-4AEE-A1C3-A880751852BB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/TeamHobby.UserManagement.xTests.csproj b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/TeamHobby.UserManagement.xTests.csproj index 9f77f5f..ef2ea1d 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/TeamHobby.UserManagement.xTests.csproj +++ b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/TeamHobby.UserManagement.xTests.csproj @@ -20,4 +20,9 @@ + + + + + diff --git a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/UnitTest1.cs b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/UnitTest1.cs index b6985f1..5591ec9 100644 --- a/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/UnitTest1.cs +++ b/Source Code/TeamHobby.HobbyProjectGenerator/TeamHobby.UserManagement.xTests/UnitTest1.cs @@ -32,7 +32,7 @@ namespace TeamHobby.UserManagement.xTests "SERVER=localhost;" + "DATABASE=hobby;" + "UID=root;" + - "PASSWORD=hobby;" + + "PASSWORD=Teamhobby;" + "OPTION=3"; IDataSource datasource = dbFactory.getDataSource(dbType, dbInfo); @@ -165,7 +165,7 @@ namespace TeamHobby.UserManagement.xTests "SERVER=localhost;" + "DATABASE=hobby;" + "UID=root;" + - "PASSWORD=hobby;" + + "PASSWORD=Teamhobby;" + "OPTION=3"; IDataSource datasource = dbFactory.getDataSource(dbType, dbInfo); @@ -174,7 +174,7 @@ namespace TeamHobby.UserManagement.xTests for (int i = 0; i < 10000; i++) { var TestAcc = new UserAccount("newUser" + $"{i}", "4567", $"email{i}@a.com", "regular", sTime); - serviceTest.CreateUserRecord(TestAcc, "Rifat", datasource); + serviceTest.DeleteUserRecord(TestAcc, "Rifat", datasource); } DateTime eTime = DateTime.Now; diff --git a/Source Code/main/Controller.cs b/Source Code/main/Controller.cs index d4dcfd0..7de8d21 100644 --- a/Source Code/main/Controller.cs +++ b/Source Code/main/Controller.cs @@ -5,8 +5,8 @@ using TeamHobby.HobbyProjectGenerator.DataAccess; using TeamHobby.HobbyProjectGenerator.UserManagement; namespace TeamHobby.HobbyProjectGenerator.Main -{ - public class Controller +{ + public class Controller { public static void Main(string[] args) @@ -45,8 +45,6 @@ namespace TeamHobby.HobbyProjectGenerator.Main // Get time of login attempt DateTime TimeStamp = DateTime.UtcNow; - - // String for checking query return type string dbType = "sql"; @@ -70,7 +68,7 @@ namespace TeamHobby.HobbyProjectGenerator.Main string currentDate = DateTime.Now.ToString("dd"); string currentTime = DateTime.Now.ToString("T"); //Console.WriteLine("Current date: {0}, Current Time: {1}", currentDate, currentTime); - if (String.Equals(currentDate, "1") && String.Equals(currentTime, "00:00:00 AM")) + if (String.Equals(currentDate, "01") && String.Equals(currentTime, "00:00:00 AM")) { ArchiveManager archive = new ArchiveManager(datasource); archive.Controller(); @@ -82,64 +80,22 @@ namespace TeamHobby.HobbyProjectGenerator.Main // Create UserAccount class UserAccount user = new UserAccount(username, password, TimeStamp); - + // Call user object and wait for return string string isLogin = manager.CreateUserRecord(user, datasource); - + // If login is not incorrect and user is returning to login menu if (isLogin != "Access Denied: Unauthorized\n") { Console.WriteLine("Returning to login...\n"); Console.WriteLine("-------------------------------------\n"); } + // If login is incorrect else { Console.WriteLine("******Access Denied: Unauthorized******"); } - + } - - //Creating the folder Archive - //Console.WriteLine("Creating a new folder ..."); - //archive.CreateArchiveFolder(); - //Console.WriteLine(""); - - //// Creating a file name: - //string filePath = @"C:\HobbyArchive"; - ////Console.WriteLine("Creating file name ... "); - ////string curPath = archive.CreateOutFileName(); - //string curPath = archive.CreateOutFileName(filePath); - - ////string pathForward = @"C:\Users\Chunchunmaru\Documents\csulbFall2021\HobbyProject\Source Code\main\bin\Debug\net6.0\HobbyArchive"; - ////string pathTemp = "C:/Temp/oldlogs10.txt"; - ////string pathTempBack = @"C:\Temp\oldlogs10.txt"; - //Console.WriteLine("----------------"); - - ////Output SQL to a text file - //sqlDS.CopyToFile(curPath); - - //// Compress the file - //sqlDS.CompressFile(curPath); - - ////Remove output file - //sqlDS.RemoveOutputFile(curPath); - - //// Remove entries fromt the database - //sqlDS.RemoveEntries(); - - - // 2.Inserting Data into the database: - //string sqlWrite = "INSERT into log(lvname, catname, userop, logmessage) values " + - // "('Info', 'View', 'Testing DAL stuffs', 'new DAL method tested');"; - - //Console.WriteLine("Writing to the database... "); - //datasource.WriteData(sqlWrite); - //Console.WriteLine("Writing completed. "); - - // 3. Removing from a database - //string sqlRemove = "DELETE from log where logID = 28;"; - //Console.WriteLine("Writing to the database... "); - //datasource.WriteData(sqlRemove); - //Console.WriteLine("Writing completed. "); } } } diff --git a/Source Code/main/ExtractBulkOp.cs b/Source Code/main/ExtractBulkOp.cs new file mode 100644 index 0000000..e4396c5 --- /dev/null +++ b/Source Code/main/ExtractBulkOp.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Data.Odbc; +using TeamHobby.HobbyProjectGenerator.DataAccess; +using TeamHobby.HobbyProjectGenerator.UserManagement; + +namespace main +{ + public class ExtractBulkOp + { + public void ExtractBulkOP(string signedUser, IDataSource dbSource) + //public static void Main(string[] args) + { + try + { + // Get the current directory. + string path = Directory.GetCurrentDirectory(); + // Open file reader stream + using StreamReader fileRead = new(path + "\\BulkOps\\Bulk.txt"); // path + "\\BulkOps\\{input}" + // Show location of the file being written + Console.WriteLine(path + "\\BulkOps\\Bulk.txt"); + + // List choices of operations + List ops = new List {"Create Account", "Edit Account", + "Delete Account", "Disable Account", "Enable Account"}; + + // List to hold file operation and credentials + List fileList = new List(); + string operation = ""; + string UN = ""; + string PWD = ""; + string Role = ""; + string Email = ""; + + // Loop through file rows + while (!fileRead.EndOfStream) + { + // Create variable to hold current line + string line = fileRead.ReadLine(); + + // Check if line is not empty and contains the separator + if (line != null && line.Contains(":")) + { + // Assign value to hold current line parameter + string value = line.Split(':')[1].Trim(); + + // Check what operation is being called + if (ops.Contains(value)) + { + // Add operation into temp + //Console.WriteLine("Found operation"); + //Console.WriteLine(value); + operation = value; + } + else + { + string checkCredential = line.Split(':')[0].Trim(); + //Console.WriteLine("Found credential"); + switch (checkCredential) + { + case "Username": + UN = value; + break; + case "Password": + PWD = value; + break; + case "Role": + Role = value; + break; + case "Email": + Email = value; + break; + default: + break; + } + } + } + switch (operation) + { + case "Create Account": + //Console.WriteLine(operation); + if (String.IsNullOrEmpty(Role)) + { + Role = null; + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Email, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + Console.WriteLine($"VALUES ('{user.username}', " + + $"'{user.password}','{user.role}', 1," + + $"'Jacob', NOW(),'{user.email}');"); + //Console.WriteLine(serviceTest.CreateUserRecord(user, 'Jacob', dbSource)); + } + else if (String.IsNullOrEmpty(Email)) + { + Email = null; + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, Role); + // Create Account service object + AccountService serviceTest = new AccountService(); + Console.WriteLine($"VALUES ('{user.username}', " + + $"'{user.password}','{user.role}', 1," + + $"'Jacob', NOW(),'{user.email}');"); + //serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + else + { + // Console.WriteLine(UN); + // Create UserAccount object + UserAccount user = new UserAccount(UN, PWD, DateTime.UtcNow); + // Create Account service object + AccountService serviceTest = new AccountService(); + if (user.email == null) + { + Console.WriteLine("wokring correctly"); + } + else + { + Console.WriteLine($"VALUES ('{user.username}', " + + $"'{user.password}','{user.role}', 1," + + $"'Jacob', NOW(),'{user.email}');"); + //serviceTest.CreateUserRecord(user, signedUser, dbSource); + } + } + break; + case "Edit Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + + break; + case "Delete Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + + break; + case "Disable Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + + break; + case "Enable Account": + //Console.WriteLine(operation); + //Console.WriteLine(operation); + + break; + default: + break; + + } + } + fileRead.Close(); + } + catch (Exception e) + { + Console.WriteLine("Error reading file"); + Console.WriteLine(e.Message); + } + } + } +} diff --git a/Source Code/main/GenerateOpFile.cs b/Source Code/main/GenerateOpFile.cs new file mode 100644 index 0000000..22fc33e --- /dev/null +++ b/Source Code/main/GenerateOpFile.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TeamHobby.HobbyProjectGenerator.DataAccess; +using TeamHobby.HobbyProjectGenerator.UserManagement; + +namespace main +{ + public class GenerateOpFile + { + public void GenerateOPFile() + //public static void Main(string[] args) + { + try + { + // Get the current directory. + string path = Directory.GetCurrentDirectory(); + // Open file stream + using StreamWriter file = new(path + "\\BulkOps\\Bulk.txt", append: true); + // Show location of the file being written + Console.WriteLine(path + "\\BulkOps\\Bulk.txt"); + + // List choices of operations + List ops = new List {"Create Account", "Edit Account", + "Delete Account", "Disable Account", "Enable Account"}; + // Create Account service object + AccountService serviceTest = new AccountService(); + + // Find database and connect to it + string dbType = "sql"; + RDSFactory dbFactory = new RDSFactory(); + + // Testing Data Access Layer + string dbInfo = "DRIVER={MariaDB ODBC 3.1 Driver};" + + "TCPIP=1;" + + "SERVER=localhost;" + + "DATABASE=hobby;" + + "UID=root;" + + "PASSWORD=Teamhobby;" + + "OPTION=3"; + IDataSource datasource = dbFactory.getDataSource(dbType, dbInfo); + + // Create a file + // Initialize value for random operation + Random random = new Random(); + int index = 0; + for (int i = 0; i < 10000; i++) + { + // Choose random operation + index = random.Next(ops.Count); + // Create next dummy data + UserAccount testAcc = new UserAccount("newUser" + $"{i}", "4567", $"email{i}@aol.com", "regular", DateTime.Now); + // Write to file + // Write Operation: for now it is only create accounts to avoid errors + file.WriteLine($"Operation: {ops[0]}"); + // Write credentials in the format of: (UserName, Password, Role, IsActive, CreatedBy, CreatedDate, Email) + file.WriteLine($"Username: {testAcc.username}\nPassword: {testAcc.password}\nRole: {testAcc.role}\nEmail: {testAcc.email}\n"); + } + file.Close(); + } + catch (Exception e) + { + Console.WriteLine("Error reading file"); + Console.WriteLine(e.Message); + } + } + } +} diff --git a/Source Code/main/main - Backup.csproj b/Source Code/main/main - Backup.csproj new file mode 100644 index 0000000..73a9e47 --- /dev/null +++ b/Source Code/main/main - Backup.csproj @@ -0,0 +1,23 @@ + + + + Exe + net6.0 + enable + enable + AnyCPU + AnyCPU + + + + + + + + + + + + + + diff --git a/Source Code/main/main.csproj b/Source Code/main/main.csproj index 6236e85..f8ad87e 100644 --- a/Source Code/main/main.csproj +++ b/Source Code/main/main.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/src/dbCode/fullDDL.txt b/src/dbCode/fullDDL.txt index ffcc31a..ce96ed7 100644 --- a/src/dbCode/fullDDL.txt +++ b/src/dbCode/fullDDL.txt @@ -42,16 +42,12 @@ INSERT INTO hobby.roles (Role, CreatedBy, CreatedDate) VALUES SET Global innodb_file_per_table=ON; --- SET GLOBAL innodb_file_format='Barracuda'; SET GLOBAL innodb_default_row_format='dynamic'; SET GLOBAL innodb_compression_algorithm='zlib'; --- Check for system settings -SHOW VARIABLES LIKE 'innodb_compression_algorithm'; -SHOW VARIABLES LIKE 'innodb_default_row_format'; -SHOW VARIABLES LIKE '%innodb%'; + CREATE TABLE Persons ( PersonID int, @@ -97,23 +93,6 @@ create table Log ); -create table Archive -( - LtimeStamp datetime null, - logID int not null, - LvName varchar(50) not null, - catName varchar(50) not null, - userOP varchar(50) not null, - logMessage varchar(255) not null, - - constraint Archive_pk primary key (logID) -) - ENGINE=InnoDB - PAGE_COMPRESSED=1 - PAGE_COMPRESSION_LEVEL=9; - -drop table archive; - -- Dummy data for testing purposes -- Log categories data INSERT into logcategories(catName, catComment) values @@ -137,8 +116,6 @@ INSERT into log(lvname, catname, userop, logmessage) values ('Info', 'Business', 'log in', 'log in successfully'), ('Info', 'View', 'search for projects', 'result return'); -select * from logcategories; -select * from log;