/// <summary> /// Checks TaskRepeat /// </summary> /// <param name="taskRepeating">times to see if it's time</param> /// <param name="sendBefore">Time to tell how much in future should the task be sent</param> /// <returns>True if it's time to execute a task</returns> public bool CorrectTime(TaskRepeating taskRepeating, int sendBefore) { taskRepeating.ExecutionTimes.Sort(); if (taskRepeating.ExceptionDates != null) { taskRepeating.ExceptionDates.Sort(); } else { taskRepeating.ExceptionDates = new List <ExceptionDate>(); } bool eligible = false; foreach (DateTime item in taskRepeating.ExecutionTimes) { if ((item - DateTime.Now).TotalMilliseconds < sendBefore && eligible == false) { eligible = true; foreach (var value in taskRepeating.ExceptionDates) { if (item < value.End && item > value.Start) { eligible = false; break; } } } } return(eligible); }
/// <summary> /// Extends a <see cref="TaskRepeating"/> /// </summary> /// <param name="taskRepeating">Taskrepeating to extend</param> /// <returns>new Taskrepeating</returns> public TaskRepeating TaskExtend(TaskRepeating taskRepeating) { TaskRepeating reference = taskRepeating; taskRepeating.ExecutionTimes.Sort(); for (int i = taskRepeating.ExecutionTimes.Count - 1; i >= 0; i--) { if (taskRepeating.ExecutionTimes[i] <= DateTime.Now) { while (taskRepeating.ExecutionTimes[i] <= DateTime.Now) { taskRepeating.ExecutionTimes[i] = taskRepeating.ExecutionTimes[i] + taskRepeating.Repeating; } if (taskRepeating.ExecutionTimes[i] >= taskRepeating.RepeatTill) { taskRepeating.ExecutionTimes.RemoveAt(i); } } } if (taskRepeating.ExecutionTimes.Count == 0) { return(null); } return(taskRepeating); }
public void UpdateEmail(int AdminId, EditEmailRequest email) { using (MySqlConnection connection = WebApiConfig.Connection()) using (MySqlCommand command = new MySqlCommand("DELETE FROM `tbEmailPreferences` WHERE `IdAdmin` = " + AdminId, connection)) { connection.Open(); command.ExecuteNonQuery(); if (email.RecieveMail) { TaskRepeating rep = new TaskRepeating() { ExceptionDates = email.Repeating.ExceptionDates, ExecutionTimes = email.Repeating.ExecutionTimes, Repeating = new TimeSpan(0, 0, email.Repeating.Repeating), RepeatTill = email.Repeating.RepeatTill }; command.CommandText = $"INSERT INTO `tbEmailPreferences`(`IdAdmin`, `RepeatInJSON`, `RecievingEmail`) VALUES ({AdminId},@repeating,@email)"; command.Parameters.AddWithValue("@repeating", JsonSerializationUtility.Serialize(rep)); command.Parameters.AddWithValue("@email", GetAdminEmail(AdminId)); command.ExecuteNonQuery(); } } }
/// <summary> /// Updates TaskRepeating in database. /// </summary> /// <param name="taskRepeating">times to edit</param> /// <param name="Id">Id of column to edit time in</param> /// <param name="TableName">Name of the table to edit time in</param> /// <param name="ColumnName">Name of the column to edit value in</param> public TaskRepeating TaskExtendDatabase(TaskRepeating taskRepeating, int Id, string TableName, string ColumnName) { TaskRepeating reference = taskRepeating; taskRepeating.ExecutionTimes.Sort(); for (int i = taskRepeating.ExecutionTimes.Count - 1; i >= 0; i--) { if (taskRepeating.ExecutionTimes[i] <= DateTime.Now) { while (taskRepeating.ExecutionTimes[i] <= DateTime.Now) { taskRepeating.ExecutionTimes[i] = taskRepeating.ExecutionTimes[i] + taskRepeating.Repeating; } if (taskRepeating.ExecutionTimes[i] >= taskRepeating.RepeatTill) { taskRepeating.ExecutionTimes.RemoveAt(i); } } } if (taskRepeating.ExecutionTimes.Count == 0) { mySql.AlterTable(new ChangeTable() { Id = Id, TableName = TableName, ColumnName = ColumnName, Value = DBNull.Value }); return(null); } else if (taskRepeating.Equals(reference)) { mySql.AlterTable(new ChangeTable() { Id = Id, TableName = TableName, ColumnName = ColumnName, Value = JsonSerializationUtility.Serialize(taskRepeating) }); } return(taskRepeating); }
/// <summary> /// If next execution time exists new task is created and current is marked as completed else task is removed with <see cref="TaskRemove(TaskComplete)"/> /// </summary> /// <param name="taskComplete">Completed task</param> /// <param name="JsonTime">T<see cref="TaskRepeating"/> in json</param> private void TaskExtend(TaskComplete taskComplete, string JsonTime) { using (MySqlConnection connection = WebApiConfig.Connection()) { connection.Open(); TaskRepeating repeat = JsonSerializationUtility.Deserialize <TaskRepeating>(JsonTime); repeat = timer.TaskExtend(repeat); if (repeat == null) { TaskRemove(taskComplete); return; } else { foreach (var item in repeat.ExecutionTimes) { while (this.HasDateException(item, repeat.ExceptionDates)) { item.Add(repeat.Repeating); } } } repeat = timer.TaskExtend(repeat); //new task Task originalTask = null; Task newTask; string order = ""; //BackupType: 0=Full, 1=Incr, 2=Diff int previousTaskID = 0; using (MySqlCommand command = new MySqlCommand("SELECT * FROM `tbTasks` WHERE `Id` = @id", connection)) { command.Parameters.AddWithValue("@id", taskComplete.IDTask); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { originalTask = JsonSerializationUtility.Deserialize <Task>((string)reader["Task"]); order = (string)reader["BackupTypePlan"]; previousTaskID = (int)reader["Id"]; } } } if (originalTask == null) { throw new Exception("Task " + taskComplete.IDTask + "cannot be found in database"); } TaskRemove(taskComplete); string newOrder = ""; newOrder += order.Substring(1, order.Length - 1); newOrder += order[0]; int previousTaskIDLast = previousTaskID; ISource[] previousTasksSources = new ISource[newOrder.Length]; int[] previousTasksIds = new int[newOrder.Length]; //List<string> previousTasksData = new List<string>(order.Length); //Dictionary<int, string> previousTasksData = new Dictionary<int, string>(order.Length); for (int i = 0; i < newOrder.Length; i++) { using (MySqlCommand command = new MySqlCommand("SELECT Task, IdPreviousTask FROM `tbTasks` WHERE `Id` = " + previousTaskIDLast, connection)) { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { //previousTasksTypes.Add((int)reader["PreviousTaskID"], (byte)reader["BackupType"]); previousTasksSources[i] = JsonSerializationUtility.Deserialize <Task>((string)reader["Task"]).Sources; previousTasksIds[i] = previousTaskIDLast; previousTaskIDLast = (int)reader["IdPreviousTask"]; } } } } if (newOrder != null && newOrder.Length > 0) { newTask = originalTask; newTask.TimeToBackup = repeat.ExecutionTimes[0]; if (newOrder[0] == '0') { for (int i = newOrder.Length - 1; i > 0; i--) { if (previousTasksSources[i] is SourceFolders) { newTask.Sources = previousTasksSources[i]; break; } } } else if (newOrder[0] == '1') { for (int i = newOrder.Length - 1; i > 0; i--) { if (previousTasksSources[i] is SourceFolders) { using (MySqlCommand command = new MySqlCommand("SELECT BackupJournal FROM tbTasksCompleted WHERE IdTask = " + previousTasksIds[i], connection)) { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { newTask.Sources = JsonConvert.DeserializeObject <BackupJournalObject>((string)reader["BackupJournal"]); } } } break; } } //int lastID = previousTasksIds[newOrder.Length - 1]; //int i = 0; //while (lastID == 0) //{ // lastID = previousTasksIds[newOrder.Length - 1 - i]; // i++; //} //using (MySqlCommand command = new MySqlCommand("SELECT BackupJournal FROM tbTasksCompleted WHERE IdTask = " + lastID, connection)) //{ // using (MySqlDataReader reader = command.ExecuteReader()) // { // while (reader.Read()) // { // //previousTasksTypes.Add((int)reader["PreviousTaskID"], (byte)reader["BackupType"]); // newTask.Sources = JsonConvert.DeserializeObject<BackupJournalObject>(b.Base64Decode((string)reader["BackupJournal"])); // } // } //} } else if (newOrder[0] == '2') { for (int i = newOrder.Length - 1; i > 0; i--) { int lastID = previousTasksIds[i]; int y = 1; while (lastID == 0) { lastID = previousTasksIds[i] - y; y++; } if (newOrder[i] == '0') { using (MySqlCommand command = new MySqlCommand("SELECT BackupJournal FROM tbTasksCompleted WHERE IdTask = " + previousTasksIds[i], connection)) { using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { //previousTasksTypes.Add((int)reader["PreviousTaskID"], (byte)reader["BackupType"]); newTask.Sources = JsonConvert.DeserializeObject <BackupJournalObject>((string)reader["BackupJournal"]); } } } break; } } } } else { throw new Exception("Order is undefined"); } newTask.IDTask = sqlAdmin.NextAutoIncrement("tbTasks"); sqlAdmin.AlterTable(new Models.Tables.ChangeTable() { ColumnName = "RepeatInJSON", Id = taskComplete.IDTask, TableName = "tbTasks", Value = JsonSerializationUtility.Serialize(repeat) }); using (MySqlCommand command = new MySqlCommand("INSERT INTO `tbTasks`(`IdDaemon`, `Task`, `TimeOfExecution`, `IdPreviousTask`, `BackupTypePlan`, `RepeatInJSON`, `Completed`)" + " VALUES (@IdDaemon, @Task, @TimeOfExecution, @IdPreviousTask, @BackupPlan, @Repeat, 0 )", connection)) { command.Parameters.AddWithValue("@IdDaemon", GetDaemonId(taskComplete.DaemonInfo)); command.Parameters.AddWithValue("@Task", JsonSerializationUtility.Serialize(newTask)); command.Parameters.AddWithValue("@TimeOfExecution", repeat.ExecutionTimes[0]); command.Parameters.AddWithValue("@Repeat", JsonSerializationUtility.Serialize(repeat)); command.Parameters.AddWithValue("@IdPreviousTask", taskComplete.IDTask); command.Parameters.AddWithValue("@BackupPlan", newOrder); command.ExecuteNonQuery(); } /* * repeat.ExecutionTimes.Sort(); * DateTime nextDate = repeat.ExecutionTimes.Last(); * bool DateChanged = false; * foreach (var item in repeat.ExecutionTimes) * { * if (item > DateTime.Now) * { * bool NotException = HasDateException(item, repeat.ExceptionDates); * if (NotException) * { * nextDate = item; * DateChanged = true; * break; * } * } * } * if (!DateChanged) * { * if (repeat.RepeatTill == null) * { * bool DateOk = true; * while (repeat.ExecutionTimes[0] < DateTime.Now || !DateOk) * { * for (int i = 0; i < repeat.ExecutionTimes.Count; i++) * { * repeat.ExecutionTimes[i] += repeat.Repeating; * } * DateOk = DateAvailable(repeat.ExecutionTimes, repeat.ExceptionDates); * } * } * else * { * bool DateOk = true; * while (repeat.ExecutionTimes[0] < DateTime.Now || !DateOk) * { * List<int> ToDelete = new List<int>(); * for (int i = 0; i < repeat.ExecutionTimes.Count; i++) * { * if (repeat.ExecutionTimes[i] + repeat.Repeating < repeat.RepeatTill) * repeat.ExecutionTimes[i] += repeat.Repeating; * else * ToDelete.Add(i); * } * for (int i = ToDelete.Count - 1; i >= 0; i--) * { * repeat.ExecutionTimes.RemoveAt(ToDelete[i]); * } * if (repeat.ExecutionTimes.Count == 0) * break; * DateOk = DateAvailable(repeat.ExecutionTimes, repeat.ExceptionDates); * } * } * foreach (var item in repeat.ExecutionTimes) * { * if (item > DateTime.Now) * { * nextDate = item; * break; * } * } * } * if (repeat.ExecutionTimes.Count == 0) * { * TaskRemove(taskComplete); * } * else * { * using (MySqlCommand command = new MySqlCommand(@"SELECT * FROM `tbTasks` WHERE Id = @Id", connection)) * { * int IdDaemon; * string Task; * DateTime TimeOfExecution; * string RepeatInJSON; * command.Parameters.AddWithValue("@Id", taskComplete.IDTask); * using (MySqlDataReader reader = command.ExecuteReader()) * { * if (reader.Read()) * { * IdDaemon = (int)reader["IdDaemon"]; * Task = (string)reader["Task"]; * TimeOfExecution = (DateTime)reader["TimeOfExecution"]; * RepeatInJSON = (string)reader["RepeatInJSON"]; * } * else * { * throw new Exception(); * } * } * Task TaskClass = JsonSerializationUtility.Deserialize<Task>(Task); * TaskRemove(taskComplete); * command.CommandText = "SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '3b1_kocourekmatej_db2' AND TABLE_NAME = 'tbTasks'"; * using (MySqlDataReader reader = command.ExecuteReader()) * { * if (reader.Read()) * taskComplete.IDTask = Convert.ToInt32(reader["AUTO_INCREMENT"]); * else * throw new Exception(); * } * TaskClass.IDTask = taskComplete.IDTask; * TaskClass.Sources = taskComplete.DatFile; * Task = JsonSerializationUtility.Serialize(TaskClass); * command.CommandText = "INSERT INTO `tbTasks` VALUES (null, @IdDaemon, @Task, @TimeOfExecution, @RepeatInJSON, @Completed)"; * command.Parameters.AddWithValue("@IdDaemon", IdDaemon); * command.Parameters.AddWithValue("@Task", Task); * command.Parameters.AddWithValue("@TimeOfExecution", TimeOfExecution); * command.Parameters.AddWithValue("@RepeatInJSON", RepeatInJSON); * command.Parameters.AddWithValue("@Completed", 0); * command.ExecuteNonQuery(); * } * }*/ } }
/// <summary> /// Uploads task to mySql database /// </summary> /// <param name="tasks">Defines task</param> public void SetTasks(List <SetTasks> tasks) { using (MySqlConnection connection = WebApiConfig.Connection()) { connection.Open(); foreach (var item in tasks) { using (MySqlCommand command = new MySqlCommand("INSERT INTO `tbTasks` VALUES (null, @DaemonId, @Task, @DateOfCompletion,@IdPreviousTask, @BackupTypePlan,@Repeating,0)", connection)) { TaskRepeating taskRepeating = new TaskRepeating() { ExceptionDates = item.ExecutionTimes.ExceptionDates, ExecutionTimes = item.ExecutionTimes.ExecutionTimes, RepeatTill = item.ExecutionTimes.RepeatTill, Repeating = new TimeSpan(0, 0, item.ExecutionTimes.Repeating) }; taskRepeating.ExecutionTimes.Sort(); Task task = new Task() { IDTask = NextAutoIncrement("tbTasks"), Destinations = item.Destinations, LogLevel = item.LogLevel, ScriptBefore = item.ScriptBefore, ScriptAfter = item.ScriptAfter, TemporaryFolderMaxBuffer = item.TemporaryFolderMaxBuffer, InProgress = false, TimeToBackup = taskRepeating.ExecutionTimes[0] }; if (item.FollowupTo == 0) { task.Sources = item.Sources; } else { command.CommandText = "SELECT * FROM `tbTasksCompleted` WHERE `Id` = " + item.FollowupTo; using (MySqlDataReader reader = command.ExecuteReader()) { int i = 0; while (reader.Read()) { if ((string)reader["BackupJournal"] != "null" && reader["BackupJournal"] != DBNull.Value) { i++; task.Sources = JsonConvert.DeserializeObject <BackupJournalObject>(Verification.Base64Decode((string)reader["BackupJournal"])); break; } } if (i == 0) { throw new Exception("Cannot follow up to task with no backup journal"); } } } dynamic Repeating; command.CommandText = "INSERT INTO `tbTasks` VALUES (null, @DaemonId, @Task, @DateOfCompletion,@IdPreviousTask, @BackupTypePlan,@Repeating,0)"; if (item.ExecutionTimes != null) { Repeating = JsonSerializationUtility.Serialize(taskRepeating); } else { throw new Exception("Task repeating cannot be null"); } command.Parameters.AddWithValue("@DaemonId", item.DaemonId); command.Parameters.AddWithValue("@Task", JsonSerializationUtility.Serialize(task)); command.Parameters.AddWithValue("@DateOfCompletion", taskRepeating.ExecutionTimes[0]); command.Parameters.AddWithValue("@Repeating", Repeating); command.Parameters.AddWithValue("@IdPreviousTask", item.FollowupTo); command.Parameters.AddWithValue("@BackupTypePlan", item.FullAfterBackup); command.ExecuteNonQuery(); } } } }