public void AddTask(DatabaseTask task, DateTime addedAt) { var tasksByType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByType); var tasksByIndex = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndex); var tasksByIndexAndType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndexAndType); var type = task.GetType().FullName; var index = task.Index; var id = generator.CreateSequentialUuid(UuidType.Tasks); var idAsString = (Slice)id.ToString(); var taskStructure = new Structure <TaskFields>(tableStorage.Tasks.Schema) .Set(TaskFields.IndexId, index) .Set(TaskFields.TaskId, id.ToByteArray()) .Set(TaskFields.AddedAt, addedAt.ToBinary()) .Set(TaskFields.Type, type) .Set(TaskFields.SerializedTask, task.AsBytes()); tableStorage.Tasks.AddStruct(writeBatch.Value, idAsString, taskStructure, 0); var indexKey = CreateKey(index); tasksByType.MultiAdd(writeBatch.Value, (Slice)CreateKey(type), idAsString); tasksByIndex.MultiAdd(writeBatch.Value, (Slice)indexKey, idAsString); tasksByIndexAndType.MultiAdd(writeBatch.Value, (Slice)AppendToKey(indexKey, type), idAsString); }
public void AddTask(DatabaseTask task, DateTime addedAt) { var tasksByType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByType); var tasksByIndex = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndex); var tasksByIndexAndType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndexAndType); var type = task.GetType().FullName; var index = task.Index; var id = generator.CreateSequentialUuid(UuidType.Tasks); var idAsString = id.ToString(); tableStorage.Tasks.Add( writeBatch.Value, idAsString, new RavenJObject { { "index", index }, { "id", id.ToByteArray() }, { "time", addedAt }, { "type", type }, { "task", task.AsBytes() } }, 0); tasksByType.MultiAdd(writeBatch.Value, CreateKey(type), idAsString); tasksByIndex.MultiAdd(writeBatch.Value, CreateKey(index), idAsString); tasksByIndexAndType.MultiAdd(writeBatch.Value, CreateKey(index, type), idAsString); }
private bool ExecuteTasks() { bool foundWork = false; transactionalStorage.Batch(actions => { DatabaseTask task = GetApplicableTask(actions); if (task == null) { return; } context.UpdateFoundWork(); Log.Debug("Executing task: {0}", task); foundWork = true; context.CancellationToken.ThrowIfCancellationRequested(); try { task.Execute(context); } catch (Exception e) { Log.WarnException( string.Format("Task {0} has failed and was deleted without completing any work", task), e); } }); return(foundWork); }
private void button_Click(object sender, RoutedEventArgs e) { string hoursText = hoursBox.Text; string minutesText = minutesBox.Text; int minutes; int hours; if (!Int32.TryParse(hoursText, out hours)) { MessageBox.Show("Cannot process hours. Front format."); return; } if (!Int32.TryParse(minutesText, out minutes)) { MessageBox.Show("Cannot process minutes. Front format."); return; } int addTimeSpent = hours * 60 + minutes; task.timeSpent += addTimeSpent; DatabaseTask.UpdateTask(task); Close(); }
private void MergeSimilarTasks(DatabaseTask task, Etag taskId, Action <IComparable> updateMaxTaskId) { var type = task.GetType().FullName; var tasksByIndexAndType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndexAndType); using (var iterator = tasksByIndexAndType.MultiRead(Snapshot, (Slice)CreateKey(task.Index, type))) { if (!iterator.Seek(Slice.BeforeAllKeys)) { return; } var totalKeysToProcess = task.NumberOfKeys; do { if (totalKeysToProcess >= 5 * 1024) { break; } var currentId = Etag.Parse(iterator.CurrentKey.ToString()); // this is the same task that we are trying to merge if (currentId == taskId) { continue; } ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } DatabaseTask existingTask; try { existingTask = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException(string.Format("Could not create instance of a task: {0}", value), e); RemoveTask(iterator.CurrentKey, task.Index, type); continue; } updateMaxTaskId(currentId); totalKeysToProcess += existingTask.NumberOfKeys; task.Merge(existingTask); RemoveTask(iterator.CurrentKey, task.Index, type); } while (iterator.MoveNext()); } }
private void btnChange_Click(object sender, RoutedEventArgs e) { DialogAddTask d = new DialogAddTask(t); if (d.ShowDialog() == true) { DatabaseTask.UpdateTask(t); //repaint taskwindow EventRepaint(EventArgs.Empty); } }
private void MergeSimilarTasks(DatabaseTask task, byte[] taskId) { var id = Etag.Parse(taskId); var type = task.GetType().FullName; var tasksByIndexAndType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndexAndType); using (var iterator = tasksByIndexAndType.MultiRead(Snapshot, (Slice)CreateKey(task.Index, type))) { if (!iterator.Seek(Slice.BeforeAllKeys)) { return; } int totalTaskCount = 0; do { var currentId = Etag.Parse(iterator.CurrentKey.ToString()); if (currentId == id) { continue; } ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } DatabaseTask existingTask; try { existingTask = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException( string.Format("Could not create instance of a task: {0}", value), e); RemoveTask(iterator.CurrentKey, task.Index, type); continue; } task.Merge(existingTask); RemoveTask(iterator.CurrentKey, task.Index, type); if (totalTaskCount++ > 1024) { break; } }while (iterator.MoveNext()); } }
private void DeleteItem(object sender, DragEventArgs e) { base.OnDrop(e); if (e.Data.GetDataPresent("Task")) // task deletion { Task task = (Task)e.Data.GetData("Task"); // Process message box results string messageBoxText = "Do you want to delete task?"; string caption = "Dialog window"; MessageBoxButton button = MessageBoxButton.YesNo; MessageBoxImage icon = MessageBoxImage.Warning; MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon); // Process message box results switch (result) { case MessageBoxResult.Yes: DatabaseTask.DeleteTask(task); break; case MessageBoxResult.No: break; } Repaint(); } else if (e.Data.GetDataPresent("Note")) // note deletion { Note note = (Note)e.Data.GetData("Note"); // confirmation string messageBoxText = "Do you want to delete the note?"; string caption = "Dialog window"; MessageBoxButton button = MessageBoxButton.YesNo; MessageBoxImage icon = MessageBoxImage.Warning; MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon); switch (result) { case MessageBoxResult.Yes: DatabaseNote.DeleteNote(note); break; case MessageBoxResult.No: break; } Repaint(); } e.Handled = true; }
private void panelMiddle_Drop(object sender, DragEventArgs e) { base.OnDrop(e); // If the DataObject contains string data, extract it. if (e.Data.GetDataPresent("Task")) { Task task = (Task)e.Data.GetData("Task"); task.status = Status.DONE; DatabaseTask.UpdateTask(task); } e.Handled = true; Repaint(); }
private void butAddTask_Click(object sender, RoutedEventArgs e) { Task t = new Task(); DialogAddTask d = new DialogAddTask(t); if (d.ShowDialog() == true) { //repaint all DatabaseTask.CreateNewTask(t.text, t.prio, Status.TODO, t.startdate, t.deadline, TaskFolder); Repaint(); } else { } }
public void AddTask(DatabaseTask task, DateTime addedAt) { int actualBookmarkSize; var bookmark = new byte[bookmarkMost]; using (var update = new Update(session, Tasks, JET_prep.Insert)) { Api.SetColumn(session, Tasks, tableColumnsCache.TasksColumns["task"], task.AsBytes()); Api.SetColumn(session, Tasks, tableColumnsCache.TasksColumns["for_index"], task.Index); Api.SetColumn(session, Tasks, tableColumnsCache.TasksColumns["task_type"], task.GetType().FullName, Encoding.ASCII); Api.SetColumn(session, Tasks, tableColumnsCache.TasksColumns["added_at"], addedAt.ToBinary()); update.Save(bookmark, bookmark.Length, out actualBookmarkSize); } Api.JetGotoBookmark(session, Tasks, bookmark, actualBookmarkSize); }
public T GetMergedTask <T>() where T : DatabaseTask { var type = CreateKey(typeof(T).FullName); var tasksByType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByType); using (var iterator = tasksByType.MultiRead(Snapshot, (Slice)type)) { if (!iterator.Seek(Slice.BeforeAllKeys)) { return(null); } do { ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } DatabaseTask task; try { task = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException( string.Format("Could not create instance of a task: {0}", value), e); continue; } MergeSimilarTasks(task, value.ReadBytes(TaskFields.TaskId)); RemoveTask(iterator.CurrentKey, task.Index, type); return((T)task); }while (iterator.MoveNext()); } return(null); }
public int DeleteTasksForIndex(int indexId) { var count = 0; var tasksByIndexAndType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByIndex); using (var iterator = tasksByIndexAndType.MultiRead(Snapshot, (Slice)CreateKey(indexId))) { if (iterator.Seek(Slice.BeforeAllKeys) == false) { return(count); } do { ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } DatabaseTask task; try { task = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException( string.Format("Could not create instance of a task: {0}, for deletion", value), e); continue; } var type = task.GetType().FullName; RemoveTask(iterator.CurrentKey, task.Index, type); count++; } while (iterator.MoveNext()); } return(count); }
public T GetMergedTask <T>() where T : DatabaseTask { Api.MoveBeforeFirst(session, Tasks); while (Api.TryMoveNext(session, Tasks)) { var taskType = Api.RetrieveColumnAsString(session, Tasks, tableColumnsCache.TasksColumns["task_type"], Encoding.Unicode); if (taskType != typeof(T).FullName) { continue; } var taskAsBytes = Api.RetrieveColumn(session, Tasks, tableColumnsCache.TasksColumns["task"]); try { Api.JetDelete(session, Tasks); } catch (EsentErrorException e) { if (e.Error != JET_err.WriteConflict) { throw; } } DatabaseTask task; try { task = DatabaseTask.ToTask(taskType, taskAsBytes); } catch (Exception e) { logger.ErrorException( string.Format("Could not create instance of a task: {0}", taskAsBytes), e); continue; } MergeSimilarTasks(task); return((T)task); } return(null); }
private void panelLeft_Drop(object sender, DragEventArgs e) { base.OnDrop(e); // If the DataObject contains string data, extract it. if (e.Data.GetDataPresent("Task")) { Task task = (Task)e.Data.GetData("Task"); task.status = Status.TODO; DialogAddTask an = new DialogAddTask(task); if (an.ShowDialog() == true) { //repaint all e.Handled = true; Repaint(); DatabaseTask.UpdateTask(task); } else { } } }
private void RunTask() { try { lock (this) { if (currentTask == null) { currentTask = DatabaseTask.Create(); } else { LogText("Previous backup is still running", EventLogEntryType.Information); return; } } currentTask.Run(); LogText("Task completed successfully", EventLogEntryType.Information); lock (this) { currentTask = null; } } catch (Exception ex) { LogText(ex.ToString(), EventLogEntryType.Error); } finally { lock (this) { currentTask = null; } } }
void drawTopMenuControls(int id) { EditorGUILayout.BeginHorizontal(); { int simIndex = MyEditor.ObjectList<DatabaseSimulation>(db.simulations, selectedSimulation, "Select Simulation"); if (simIndex >=0) selectedSimulation = db.simulations[simIndex]; else selectedSimulation = null; //deselect all simulations. foreach (DatabaseSimulation s in db.simulations) s.selected = false; if (GUILayout.Button("Create Simulation")) { if (EditorUtility.DisplayDialog("Confirm", "Continuing will lose unsaved changes to current simulation", "Continue", "Cancel")) { DatabaseSimulation sim = new DatabaseSimulation(); db.simulations.Add(sim); selectedSimulation = sim; } } } EditorGUILayout.EndHorizontal(); if (selectedSimulation != null) { //select this simulation. selectedSimulation.selected = true; //Simulation variables. EditorGUILayout.BeginHorizontal(); { selectedSimulation.name = EditorGUILayout.TextField("Sim Name", selectedSimulation.name); DatabaseSimulation.SimulationLength lengthEnum = (DatabaseSimulation.SimulationLength)EditorGUILayout.EnumPopup("Length", selectedSimulation.lengthEnum); //selected new length. //do conversion from enum to number of seconds. if (lengthEnum != selectedSimulation.lengthEnum) { selectedSimulation.lengthEnum = lengthEnum; selectedSimulation.length = (int)selectedSimulation.lengthEnum; selectedSimulation.length *= 3600; //Debug.Log(selectedSimulation.length); } } EditorGUILayout.EndHorizontal(); selectedSimulation.description = EditorGUILayout.TextField("Sim Description", selectedSimulation.description); if (GUILayout.Button("Delete Simulation")) { if (EditorUtility.DisplayDialog("Confirm", "This Action Cannot Be Undone.", "Continue", "Cancel")) { db.simulations.Remove(selectedSimulation); if (db.simulations.Count > 0) { selectedSimulation = db.simulations[0]; } else { selectedSimulation = null; return; } } } //check the task list to see if the selected task is in it. if not.. set it to null. bool found = false; for(int i=0; i<selectedSimulation.tasks.Count; i++) { DatabaseTask t = selectedSimulation.tasks[i]; if (t == selectedTask) { found = true; break; } } if (!found) selectedTask = null; //the simulation's selected task. // show the selected task options. if (selectedTask != null) { EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); { selectedTask.name = EditorGUILayout.TextField("Task Name", selectedTask.name); selectedTask.type = (Task.TaskType)EditorGUILayout.EnumPopup("Type", selectedTask.type); if (selectedTask.type == Task.TaskType.MoveObject || selectedTask.type == Task.TaskType.TurnOff || selectedTask.type == Task.TaskType.TurnOn) { selectedTask.taskObject = (SimObject)EditorGUILayout.ObjectField(selectedTask.taskObject, typeof(SimObject), true); } } EditorGUILayout.EndHorizontal(); selectedTask.description = EditorGUILayout.TextField("Task Description", selectedTask.description); //START TIME EDITING...... EditorGUILayout.BeginHorizontal(); { selectedTask.startTime = EditorGUILayout.IntSlider("Start Time", selectedTask.startTime, 0, selectedSimulation.length); //move the seconds to the closest 5 min mark. int fiveMin = 300; int distance = selectedTask.startTime % fiveMin; if (distance <= 150) selectedTask.startTime -= distance; else selectedTask.startTime += (fiveMin - distance); //draw the time in 3 text fields without labels. int time = selectedTask.startTime; int hours = time / 3600; int minSec = time % 3600; int mins = minSec / 60; int secs = minSec % 60; EditorGUILayout.LabelField(hours.ToString("00 hours") + " " + mins.ToString("00 mins") + " " + secs.ToString("00 secs")); } EditorGUILayout.EndHorizontal(); //TIME LMIT EDITING EditorGUILayout.BeginHorizontal(); { selectedTask.timeLimit = EditorGUILayout.IntSlider("Time Limit", selectedTask.timeLimit, 30, DatabaseTask.maxTimeLimit); //move the seconds to the closest 5 min mark. int fiveSec = 10; int distance = selectedTask.timeLimit % fiveSec; if (distance <= 5) selectedTask.timeLimit -= distance; else selectedTask.timeLimit += (fiveSec - distance); //draw the time in 3 text fields without labels. int time = selectedTask.timeLimit; int mins = time / 60; int secs = time % 60; EditorGUILayout.LabelField(mins.ToString("00 mins") + " " + secs.ToString("00 secs")); } EditorGUILayout.EndHorizontal(); // LENGTH EDITING... EditorGUILayout.BeginHorizontal(); { selectedTask.length = EditorGUILayout.IntSlider("Length", selectedTask.length, 0, (selectedSimulation.length-selectedTask.startTime)); //move the seconds to the closest 5 min mark. int thirty = 30; int distance = selectedTask.length % thirty; if (distance <= 15) selectedTask.length -= distance; else selectedTask.length += (thirty - distance); //draw the time in 3 text fields without labels. int time = selectedTask.length; int hours = time / 3600; int minSec = time % 3600; int mins = time / 60; int secs = time % 60; EditorGUILayout.LabelField(hours.ToString("00 hours ") + mins.ToString("00 mins") + " " + secs.ToString("00 secs")); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); selectedTask.pointValue = EditorGUILayout.IntField("Point Value", selectedTask.pointValue); if (GUILayout.Button("Delete Task")) { if (EditorUtility.DisplayDialog("Confirm", "This Action Cannot Be Undone.", "Continue", "Cancel")) { selectedSimulation.tasks.Remove(selectedTask); if (selectedSimulation.tasks.Count > 0) { selectedTask = selectedSimulation.tasks[0]; } else selectedTask = null; } } EditorGUILayout.EndHorizontal(); } } }
private async Task <List <TaskEntityDTO> > GetTasks(int id) { var clientTask = new DatabaseTask(); return(await clientTask.GetTaskByProfile(id)); }
private void MergeSimilarTasks(DatabaseTask task, HashSet <IComparable> alreadySeen, List <int> indexesToSkip, int[] allIndexes) { string tree; Slice slice; var type = task.GetType().FullName; if (task.SeparateTasksByIndex) { tree = Tables.Tasks.Indices.ByIndexAndType; slice = (Slice)CreateKey(task.Index, type); } else { tree = Tables.Tasks.Indices.ByType; slice = (Slice)CreateKey(type); } using (var iterator = tableStorage.Tasks.GetIndex(tree).MultiRead(Snapshot, slice)) { if (!iterator.Seek(Slice.BeforeAllKeys)) { return; } var totalKeysToProcess = task.NumberOfKeys; do { if (totalKeysToProcess >= 5 * 1024) { break; } ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } var currentId = Etag.Parse(iterator.CurrentKey.ToString()); var indexId = value.ReadInt(TaskFields.IndexId); if (task.SeparateTasksByIndex == false && indexesToSkip.Contains(indexId)) { //need to check this only when not separating tasks by index if (Logger.IsDebugEnabled) { Logger.Debug("Skipping task id: {0} for index id: {1}", currentId, indexId); } continue; } if (alreadySeen.Add(currentId) == false) { continue; } if (task.SeparateTasksByIndex == false && allIndexes.Contains(indexId) == false) { //need to check this only when not separating tasks by index if (Logger.IsDebugEnabled) { Logger.Debug("Skipping task id: {0} for non existing index id: {0}", currentId, indexId); } continue; } DatabaseTask existingTask; try { existingTask = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException(string.Format("Could not create instance of a task: {0}", value), e); alreadySeen.Add(currentId); continue; } totalKeysToProcess += existingTask.NumberOfKeys; task.Merge(existingTask); if (Logger.IsDebugEnabled) { Logger.Debug("Merged task id: {0} with task id: {1}", currentId, task.Id); } } while (iterator.MoveNext()); } }
/// <summary> /// Saves / Updates the tasks in the database /// </summary> private void SaveTasks() { try { int startXMailboxSizes = 0; int.TryParse(txtQueryMailboxSizesEveryXDays.Text, out startXMailboxSizes); int startXMailboxDBSizes = 0; int.TryParse(txtQueryMailboxDatabaseSizesEveryXDays.Text, out startXMailboxDBSizes); if (!cbExchangeStats.Checked) { DbSql.Remove_DatabaseTask(new DatabaseTask() { TaskType = Enumerations.TaskType.ReadMailboxSizes, IsReoccurringTask = true }); DbSql.Remove_DatabaseTask(new DatabaseTask() { TaskType = Enumerations.TaskType.ReadMailboxDatabaseSizes, IsReoccurringTask = true }); } else { if (startXMailboxSizes == 0) DbSql.Remove_DatabaseTask(new DatabaseTask() { TaskType = Enumerations.TaskType.ReadMailboxSizes, IsReoccurringTask = true }); if (startXMailboxDBSizes == 0) DbSql.Remove_DatabaseTask(new DatabaseTask() { TaskType = Enumerations.TaskType.ReadMailboxDatabaseSizes, IsReoccurringTask = true }); if (startXMailboxSizes > 0) { // Convert to minutes TimeSpan minutes = new TimeSpan(startXMailboxSizes, 0, 0, 0); DatabaseTask task = new DatabaseTask(); task.TaskType = Enumerations.TaskType.ReadMailboxSizes; task.LastRun = DateTime.Now; task.NextRun = DateTime.Now.Add(minutes); task.TaskDelayInMinutes = int.Parse(minutes.TotalMinutes.ToString()); task.WhenCreated = DateTime.Now; task.IsReoccurringTask = true; DbSql.Update_DatabaseTask(task); } if (startXMailboxDBSizes > 0) { // Convert to minutes TimeSpan minutes = new TimeSpan(startXMailboxDBSizes, 0, 0, 0); DatabaseTask task = new DatabaseTask(); task.TaskType = Enumerations.TaskType.ReadMailboxDatabaseSizes; task.LastRun = DateTime.Now; task.NextRun = DateTime.Now.Add(minutes); task.TaskDelayInMinutes = int.Parse(minutes.TotalMinutes.ToString()); task.WhenCreated = DateTime.Now; task.IsReoccurringTask = true; DbSql.Update_DatabaseTask(task); } } } catch (Exception ex) { throw; } }
public T GetMergedTask <T>(List <int> indexesToSkip, int[] allIndexes, HashSet <IComparable> alreadySeen) where T : DatabaseTask { var type = CreateKey(typeof(T).FullName); var tasksByType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByType); using (var iterator = tasksByType.MultiRead(Snapshot, (Slice)type)) { if (!iterator.Seek(Slice.BeforeAllKeys)) { return(null); } do { ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } var currentId = Etag.Parse(value.ReadBytes(TaskFields.TaskId)); var indexId = value.ReadInt(TaskFields.IndexId); if (indexesToSkip.Contains(indexId)) { if (Logger.IsDebugEnabled) { Logger.Debug("Skipping task id: {0} for index id: {1}", currentId, indexId); } continue; } if (alreadySeen.Add(currentId) == false) { continue; } if (allIndexes.Contains(indexId) == false) { if (Logger.IsDebugEnabled) { Logger.Debug("Skipping task id: {0} for non existing index id: {0}", currentId, indexId); } continue; } DatabaseTask task; try { task = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException( string.Format("Could not create instance of a task: {0}", value), e); alreadySeen.Add(currentId); continue; } if (Logger.IsDebugEnabled) { Logger.Debug("Fetched task id: {0}", currentId); } task.Id = currentId; MergeSimilarTasks(task, alreadySeen, indexesToSkip, allIndexes); return((T)task); } while (iterator.MoveNext()); } return(null); }
public T GetMergedTask <T>(Func <IComparable, MaxTaskIdStatus> maxIdStatus, Action <IComparable> updateMaxTaskId, Reference <bool> foundWork, List <int> idsToSkip) where T : DatabaseTask { var type = CreateKey(typeof(T).FullName); var tasksByType = tableStorage.Tasks.GetIndex(Tables.Tasks.Indices.ByType); using (var iterator = tasksByType.MultiRead(Snapshot, (Slice)type)) { if (!iterator.Seek(Slice.BeforeAllKeys)) { return(null); } do { ushort version; var value = LoadStruct(tableStorage.Tasks, iterator.CurrentKey, writeBatch.Value, out version); if (value == null) { continue; } DatabaseTask task; try { task = DatabaseTask.ToTask(value.ReadString(TaskFields.Type), value.ReadBytes(TaskFields.SerializedTask)); } catch (Exception e) { Logger.ErrorException( string.Format("Could not create instance of a task: {0}", value), e); continue; } if (idsToSkip.Contains(task.Index)) { continue; } var currentId = Etag.Parse(value.ReadBytes(TaskFields.TaskId)); switch (maxIdStatus(currentId)) { case MaxTaskIdStatus.ReachedMaxTaskId: // we found work and next run the merge option will be enabled foundWork.Value = true; return(null); case MaxTaskIdStatus.Updated: MergeSimilarTasks(task, currentId, updateMaxTaskId); break; case MaxTaskIdStatus.MergeDisabled: default: // returning only one task without merging break; } RemoveTask(iterator.CurrentKey, task.Index, type); return((T)task); } while (iterator.MoveNext()); } return(null); }
public T GetMergedTask <T>(Func <IComparable, MaxTaskIdStatus> maxIdStatus, Action <IComparable> updateMaxTaskId, Reference <bool> foundWork) where T : DatabaseTask { Api.MoveBeforeFirst(session, Tasks); while (Api.TryMoveNext(session, Tasks)) { var taskType = Api.RetrieveColumnAsString(session, Tasks, tableColumnsCache.TasksColumns["task_type"], Encoding.Unicode); if (taskType != typeof(T).FullName) { continue; } var taskAsBytes = Api.RetrieveColumn(session, Tasks, tableColumnsCache.TasksColumns["task"]); DatabaseTask task; try { task = DatabaseTask.ToTask(taskType, taskAsBytes); } catch (Exception e) { logger.ErrorException( string.Format("Could not create instance of a task: {0}", taskAsBytes), e); continue; } var currentId = Api.RetrieveColumnAsInt32(session, Tasks, tableColumnsCache.TasksColumns["id"]).Value; try { Api.JetDelete(session, Tasks); } catch (EsentErrorException e) { if (e.Error != JET_err.WriteConflict) { throw; } } switch (maxIdStatus(currentId)) { case MaxTaskIdStatus.ReachedMaxTaskId: // we found work and next run the merge option will be enabled foundWork.Value = true; return(null); case MaxTaskIdStatus.Updated: MergeSimilarTasks(task, updateMaxTaskId); break; case MaxTaskIdStatus.MergeDisabled: default: // returning only one task without merging break; } return((T)task); } return(null); }
public void MergeSimilarTasks(DatabaseTask task) { var expectedTaskType = task.GetType().FullName; Api.JetSetCurrentIndex(session, Tasks, "by_index_and_task_type"); if (task.SeparateTasksByIndex) { Api.MakeKey(session, Tasks, task.Index, MakeKeyGrbit.NewKey); Api.MakeKey(session, Tasks, expectedTaskType, Encoding.Unicode, MakeKeyGrbit.None); // there are no tasks matching the current one, just return if (Api.TrySeek(session, Tasks, SeekGrbit.SeekEQ) == false) { return; } Api.MakeKey(session, Tasks, task.Index, MakeKeyGrbit.NewKey); Api.MakeKey(session, Tasks, expectedTaskType, Encoding.Unicode, MakeKeyGrbit.None); Api.JetSetIndexRange(session, Tasks, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit); } else { if (Api.TryMoveFirst(session, Tasks) == false) { return; } } int totalTaskCount = 0; do { // esent index ranges are approximate, and we need to check them ourselves as well if (Api.RetrieveColumnAsString(session, Tasks, tableColumnsCache.TasksColumns["task_type"]) != expectedTaskType) { continue; } try { var taskAsBytes = Api.RetrieveColumn(session, Tasks, tableColumnsCache.TasksColumns["task"]); var taskType = Api.RetrieveColumnAsString(session, Tasks, tableColumnsCache.TasksColumns["task_type"], Encoding.Unicode); DatabaseTask existingTask; try { existingTask = DatabaseTask.ToTask(taskType, taskAsBytes); } catch (Exception e) { logger.ErrorException( string.Format("Could not create instance of a task: {0}", taskAsBytes), e); Api.JetDelete(session, Tasks); continue; } task.Merge(existingTask); Api.JetDelete(session, Tasks); } catch (EsentErrorException e) { if (e.Error == JET_err.WriteConflict) { continue; } throw; } totalTaskCount++; } while (Api.TryMoveNext(session, Tasks) && totalTaskCount < 1024); }
//creating and editing tasks. bool createTaskAtPosition(Vector2 mPos) { if (selectedSimulation == null) return false; if (mPos.y < timeLineStartY) return false; //check if it's the same position as a current task. int x = convertMouseXToTimeLineX(mPos.x); for (int i=0; i<selectedSimulation.tasks.Count; i++) { DatabaseTask t = selectedSimulation.tasks[i]; //convert start time to x value. int taskX = convertTimeLineXToWindowX(t.startTime); //Debug.Log("Task X = " + taskX); float range = 5; if (mPos.x > taskX-range && mPos.x < taskX+range) { if ((mPos.y > t.startY-range) && (mPos.y < t.startY+range)) { //falls in the range of y..just select that task. selectedTask = t; return false; } else continue; } else continue; } //create new task. DatabaseTask newTask = new DatabaseTask(x, (int)mPos.y); //add task to task list of selected simulation. selectedSimulation.tasks.Add(newTask); //selectedSimulation.tasks.Sort(); //set task as selected task. selectedTask = newTask; return true; }
public T GetMergedTask <T>(List <int> indexesToSkip, int[] allIndexes, HashSet <IComparable> alreadySeen) where T : DatabaseTask { var expectedTaskType = typeof(T).FullName; Api.JetSetCurrentIndex(session, Tasks, "by_task_type"); Api.MakeKey(session, Tasks, expectedTaskType, Encoding.ASCII, MakeKeyGrbit.NewKey); if (Api.TrySeek(session, Tasks, SeekGrbit.SeekEQ) == false) { return(null); } Api.MakeKey(session, Tasks, expectedTaskType, Encoding.ASCII, MakeKeyGrbit.NewKey); Api.JetSetIndexRange(session, Tasks, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit); do { var taskType = Api.RetrieveColumnAsString(session, Tasks, tableColumnsCache.TasksColumns["task_type"], Encoding.ASCII); // esent index ranges are approximate, and we need to check them ourselves as well if (taskType != expectedTaskType) { //this shouldn't happen logger.Warn("Tasks type mismatch: expected task type: {0}, current task type: {1}", expectedTaskType, taskType); continue; } var currentId = Api.RetrieveColumnAsInt32(session, Tasks, tableColumnsCache.TasksColumns["id"]).Value; var index = Api.RetrieveColumnAsInt32(session, Tasks, tableColumnsCache.TasksColumns["for_index"]).Value; if (indexesToSkip.Contains(index)) { if (logger.IsDebugEnabled) { logger.Debug("Skipping task id: {0} for index id: {1}", currentId, index); } continue; } if (alreadySeen.Add(currentId) == false) { continue; } if (allIndexes.Contains(index) == false) { if (logger.IsDebugEnabled) { logger.Debug("Skipping task id: {0} for non existing index id: {0}", currentId, index); } continue; } var taskAsBytes = Api.RetrieveColumn(session, Tasks, tableColumnsCache.TasksColumns["task"]); DatabaseTask task; try { task = DatabaseTask.ToTask(taskType, taskAsBytes); } catch (Exception e) { logger.ErrorException( string.Format("Could not create instance of a task: {0}", taskAsBytes), e); alreadySeen.Add(currentId); continue; } if (logger.IsDebugEnabled) { logger.Debug("Fetched task id: {0}", currentId); } task.Id = currentId; MergeSimilarTasks(task, alreadySeen, indexesToSkip, allIndexes); return((T)task); } while (Api.TryMoveNext(session, Tasks)); return(null); }
private void MergeSimilarTasks(DatabaseTask task, HashSet <IComparable> alreadySeen, List <int> indexesToSkip, int[] allIndexes) { var expectedTaskType = task.GetType().FullName; if (task.SeparateTasksByIndex) { Api.JetSetCurrentIndex(session, Tasks, "by_index_and_task_type"); Api.MakeKey(session, Tasks, task.Index, MakeKeyGrbit.NewKey); Api.MakeKey(session, Tasks, expectedTaskType, Encoding.ASCII, MakeKeyGrbit.None); if (Api.TrySeek(session, Tasks, SeekGrbit.SeekEQ) == false) { // there are no tasks matching the current one, just return return; } Api.MakeKey(session, Tasks, task.Index, MakeKeyGrbit.NewKey); Api.MakeKey(session, Tasks, expectedTaskType, Encoding.ASCII, MakeKeyGrbit.None); Api.JetSetIndexRange(session, Tasks, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit); } else { Api.JetSetCurrentIndex(session, Tasks, "by_task_type"); Api.MakeKey(session, Tasks, expectedTaskType, Encoding.ASCII, MakeKeyGrbit.NewKey); if (Api.TrySeek(session, Tasks, SeekGrbit.SeekEQ) == false) { // there are no tasks matching the current one, just return return; } Api.MakeKey(session, Tasks, expectedTaskType, Encoding.ASCII, MakeKeyGrbit.NewKey); Api.JetSetIndexRange(session, Tasks, SetIndexRangeGrbit.RangeInclusive | SetIndexRangeGrbit.RangeUpperLimit); } var totalKeysToProcess = task.NumberOfKeys; do { if (totalKeysToProcess >= 5 * 1024) { break; } var taskType = Api.RetrieveColumnAsString(session, Tasks, tableColumnsCache.TasksColumns["task_type"], Encoding.ASCII); // esent index ranges are approximate, and we need to check them ourselves as well if (taskType != expectedTaskType) { //this shouldn't happen logger.Warn("Tasks type mismatch: expected task type: {0}, current task type: {1}", expectedTaskType, taskType); continue; } var currentId = Api.RetrieveColumnAsInt32(session, Tasks, tableColumnsCache.TasksColumns["id"]).Value; var index = Api.RetrieveColumnAsInt32(session, Tasks, tableColumnsCache.TasksColumns["for_index"]).Value; if (task.SeparateTasksByIndex == false && indexesToSkip.Contains(index)) { //need to check this only when not separating tasks by index if (logger.IsDebugEnabled) { logger.Debug("Skipping task id: {0} for index id: {1}", currentId, index); } continue; } if (alreadySeen.Add(currentId) == false) { continue; } if (task.SeparateTasksByIndex == false && allIndexes.Contains(index) == false) { //need to check this only when not separating tasks by index if (logger.IsDebugEnabled) { logger.Debug("Skipping task id: {0} for non existing index id: {0}", currentId, index); } continue; } var taskAsBytes = Api.RetrieveColumn(session, Tasks, tableColumnsCache.TasksColumns["task"]); DatabaseTask existingTask; try { existingTask = DatabaseTask.ToTask(taskType, taskAsBytes); } catch (Exception e) { logger.ErrorException( string.Format("Could not create instance of a task: {0}", taskAsBytes), e); alreadySeen.Add(currentId); continue; } totalKeysToProcess += existingTask.NumberOfKeys; task.Merge(existingTask); if (logger.IsDebugEnabled) { logger.Debug("Merged task id: {0} with task id: {1}", currentId, task.Id); } } while (Api.TryMoveNext(session, Tasks)); }