public async Task<IHttpActionResult> Post(Chore chore) { if (!ModelState.IsValid) return BadRequest(ModelState); chore.Id = Guid.NewGuid(); chore.Active = true; chore.CreatedDate = _time.UtcNow; chore.ObjectState = ObjectState.Added; _choreService.Insert(chore); await _unitOfWorkAsync.SaveChangesAsync(); return new CreatedContentActionResult(Request, Url.Link("GetChore", new { id = chore.Id })); }
public async Task <ActionResult> PutAsync([FromBody] Chore chore) { try { await _choreService.PutAsync(chore); return(Ok()); } catch (NotFoundException ex) { return(NotFound()); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError)); } }
/// <summary> /// Updates the chore /// </summary> public void Update(Chore chore) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"UPDATE chore SET Name = @name, WHERE Id = @id"; cmd.Parameters.AddWithValue("@name", chore.Name); cmd.Parameters.AddWithValue("@id", chore.Id); cmd.ExecuteNonQuery(); } } }
public IActionResult EditChore(Chore editedChore) { Chore dbChore = _context.Chore.Find(editedChore.ChoreId); if (ModelState.IsValid) { dbChore.PointValue = editedChore.PointValue; dbChore.ChoreName = editedChore.ChoreName; dbChore.ChoreDescription = editedChore.ChoreDescription; dbChore.DueDate = editedChore.DueDate; _context.Entry(dbChore).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.Update(dbChore); _context.SaveChanges(); } return(RedirectToAction("ViewChores")); }
static void DeleteChore() { string choreResponse; ChoreRepository choreRepo = new ChoreRepository(CONNECTION_STRING); ListChores(); Console.WriteLine("Enter the ID of the Chore to delete: "); choreResponse = Console.ReadLine(); Chore chore = choreRepo.GetById(Int32.Parse(choreResponse)); if (choreResponse != "") { choreRepo.Delete(chore.Id); Console.WriteLine("Chore has been deleted."); ListChores(); } }
public async Task <IHttpActionResult> Post(Chore chore) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } chore.Id = Guid.NewGuid(); chore.Active = true; chore.CreatedDate = _time.UtcNow; chore.ObjectState = ObjectState.Added; _choreService.Insert(chore); await _unitOfWorkAsync.SaveChangesAsync(); return(new CreatedContentActionResult(Request, Url.Link("GetChore", new { id = chore.Id }))); }
private void RefreshChore(IAssignableIdentity target) { if (chore != null) { chore.Cancel("Equipment Reassigned"); chore = null; } if (target != null) { Ownables soleOwner = target.GetSoleOwner(); Equipment component = soleOwner.GetComponent <Equipment>(); if (!component.IsEquipped(equippable)) { CreateChore(); } } }
static void UpdateChore(ChoreRepository choreRepo) { List <Chore> chores = choreRepo.GetAll(); chores.ForEach(c => Console.WriteLine($"{c.Id} - {c.Name}")); Console.Write("Which chore would you like to update? "); int selectedChoreId = int.Parse(Console.ReadLine()); Chore selectedChore = chores.FirstOrDefault(c => c.Id == selectedChoreId); Console.Write("New Chore Name: "); selectedChore.Name = Console.ReadLine(); choreRepo.Update(selectedChore); Console.WriteLine($"Chore has been successfully updated"); ContinueMenu(); }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } Chore = await _context.Chores.FindAsync(id); if (Chore != null) { _context.Chores.Remove(Chore); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
///<summary> ///Add a new chore to the database ///Note: This method SENDS data to the db and retrieves nothing, ///so there is nothing to return ///</summary> public void Insert(Chore chore) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO Chore (Name) OUTPUT INSERTED.Id VALUES (@name)"; cmd.Parameters.AddWithValue("@name", chore.Name); int id = (int)cmd.ExecuteScalar(); chore.Id = id; } } }
private static void WriteEntry(Chore chore, StreamWriter file) { StringBuilder builder = new StringBuilder(); builder.Append(chore.Key); builder.Append(","); builder.Append(chore.Name); builder.Append(","); builder.Append(chore.Value.ToString("N3")); builder.Append(","); builder.Append(chore.Description); file.WriteLine(builder.ToString()); }
public List <Chore> GetAll() { //Prep to open up a connection. We need SqlConnection for this part so we are "using" it using (SqlConnection conn = Connection) { //Actually open the connection conn.Open(); // We will be "using" SqlCommand also using (SqlCommand cmd = conn.CreateCommand()) { // Prep the SQL cmd.CommandText = "SELECT Id, Name FROM Chore"; // Execute the SQL in the database and get a "reader" that will give us access to the data. SqlDataReader reader = cmd.ExecuteReader(); //List for Chores retrieved from the db List <Chore> chores = new List <Chore>(); // Read() will return true if there's more data to read while (reader.Read()) { int idColumnPosition = reader.GetOrdinal("Id"); int idValue = reader.GetInt32(idColumnPosition); int nameColumnPosition = reader.GetOrdinal("Name"); string nameValue = reader.GetString(nameColumnPosition); Chore chore = new Chore { Id = idValue, Name = nameValue }; chores.Add(chore); } reader.Close(); return(chores); }; } }
private async Task <IHouseworkRepository> GetInMemoryHouseworkRepository() { DbContextOptions <HouseworkApiContext> options; var builder = new DbContextOptionsBuilder <HouseworkApiContext>().UseInMemoryDatabase("TestingDb"); options = builder.Options; HouseworkApiContext HouseworkApiContext = new HouseworkApiContext(options); HouseworkApiContext.Database.EnsureDeleted(); HouseworkApiContext.Database.EnsureCreated(); var repo = new HouseworkRepository(HouseworkApiContext); var kitchen = new Room() { Name = "Kitchen" }; repo.AddEntity(kitchen); var mop = new Chore() { Name = "Mop floor", LastCompleted = DateTime.MinValue, Frequency = TimeSpan.FromDays(7), RoomId = kitchen.Id }; repo.AddEntity(mop); repo.AddEntity(new Room() { Name = "Living Room" }); repo.AddEntity(new Room() { Name = "Bathroom" }); await repo.SaveAllAsync(); roomId = kitchen.Id; choreId = mop.Id; return(repo); }
public static bool ChoreTableUpdate(Chore chore) { string question1 = ""; string question2 = ""; string question3 = ""; if (chore.Questions.Count > 2) { question1 = chore.Questions[0]; question2 = chore.Questions[1]; question3 = chore.Questions[2]; } else if (chore.Questions.Count > 1) { question1 = chore.Questions[0]; question2 = chore.Questions[1]; } else if (chore.Questions.Count > 0) { question1 = chore.Questions[0]; } if (!ConnectToDatabase()) { return(false); } string sqlCMD = "UPDATE Chore SET name=@name, type=@type, description=@description, question1=@question1, question2=@question2, question3=@question3,frequency=@frequency, homeID=@homeID WHERE ID = @ID"; SqlCommand command = new SqlCommand(sqlCMD, connection); command.Parameters.AddWithValue("@ID", chore.ID); command.Parameters.AddWithValue("@name", chore.Name); command.Parameters.AddWithValue("@type", chore.Type); command.Parameters.AddWithValue("@description", chore.Description); command.Parameters.AddWithValue("@frequency", chore.Frequency); command.Parameters.AddWithValue("@homeID", chore.HomeID); command.Parameters.AddWithValue("@question1", question1); command.Parameters.AddWithValue("@question2", question2); command.Parameters.AddWithValue("@question3", question3); command.ExecuteNonQuery(); DisconnectFromDatabase(); return(true); }
/// <summary> /// Adjusts build priorities based on the options. /// </summary> /// <param name="priorityMod">The priority to modify.</param> /// <param name="chore">The parent chore.</param> private static void AdjustBuildPriority(ref int priorityMod, Chore chore) { BuildingDef def; if (chore.target is Constructable target && target != null && (def = target. GetComponent<Building>()?.Def) != null) { string id = def.PrefabID; if (Options.PrioritizeBuildings.Contains(id)) priorityMod += AIImprovementsOptions.BUILD_PRIORIY_MOD; else if (Options.DeprioritizeBuildings.Contains(id)) priorityMod -= AIImprovementsOptions.BUILD_PRIORIY_MOD; if (def.IsFoundation || def.isSolidTile) { // Avoid building a tile which would block a location recently used by // a dupe int cell = Grid.PosToCell(target); if (AllMinionsLocationHistory.Instance.WasRecentlyOccupied(cell)) priorityMod -= AIImprovementsOptions.BLOCK_PRIORITY_MOD; } } }
private void QueueDeconstruction() { if (chore == null) { if (DebugHandler.InstantBuildMode) { OnCompleteWork(null); } else { Prioritizable.AddRef(base.gameObject); chore = new WorkChore <Deconstructable>(Db.Get().ChoreTypes.Deconstruct, this, null, true, null, null, null, true, null, false, false, null, true, true, true, PriorityScreen.PriorityClass.basic, 5, true, true); GetComponent <KSelectable>().AddStatusItem(Db.Get().BuildingStatusItems.PendingDeconstruction, this); isMarkedForDeconstruction = true; Trigger(2108245096, "Deconstruct"); } } }
public async Task <IActionResult> PostChore([FromRoute] int boardId, [FromBody] NewChoreDTO newChore) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Chore chore = new Chore { Name = newChore.Name, Description = newChore.Description, BoardId = boardId }; _context.Chores.Add(chore); await _context.SaveChangesAsync(); return(CreatedAtAction("GetChore", new { id = chore.ChoreId }, chore)); }
//https://stackoverflow.com/questions/32675411/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-key-pro //Create public Chore AddChore(Chore Value) { try { Value.SortOrder = db.Chores.Count(x => x.ChoreListId == Value.ChoreListId && x.IsActive) + 1; //add to db Value = db.Chores.Add(Value); db.SaveChanges(); return(Value); } catch (Exception ex) { throw Utility.ThrowException(ex); } }
public Context(Chore chore, ChoreConsumerState consumer_state, bool is_attempting_override, object data = null) { masterPriority = chore.masterPriority; personalPriority = consumer_state.consumer.GetPersonalPriority(chore.choreType); priority = 0; priorityMod = chore.priorityMod; consumerPriority = 0; interruptPriority = 0; cost = 0; this.chore = chore; consumerState = consumer_state; failedPreconditionId = -1; isAttemptingOverride = is_attempting_override; this.data = data; choreTypeForPermission = chore.choreType; skipMoreSatisfyingEarlyPrecondition = ((UnityEngine.Object)RootMenu.Instance != (UnityEngine.Object)null && RootMenu.Instance.IsBuildingChorePanelActive()); SetPriority(chore); }
public void DropAll() { if (DebugHandler.InstantBuildMode) { OnCompleteWork(null); } else if (chore == null) { chore = new WorkChore <DropAllWorkable>(Db.Get().ChoreTypes.EmptyStorage, this, null, true, null, null, null, true, null, false, false, null, false, true, true, PriorityScreen.PriorityClass.basic, 5, false, true); } else { chore.Cancel("Cancelled emptying"); chore = null; GetComponent <KSelectable>().RemoveStatusItem(workerStatusItem, false); ShowProgressBar(false); } }
private List <Chore> CreateWeeklyChoreList(NewChoresGuideline guideline) { DateTime endTimeSpan = guideline.TimeSpanToAddChores.End; DateTime startTimeSpan = guideline.TimeSpanToAddChores.Start; DateTime dateFirstMonday = FirstMonday(startTimeSpan); List <Chore> WeeklyChores = new List <Chore>(); for (DateTime d = dateFirstMonday; d <= endTimeSpan; d = d.AddDays(7)) { DateTime choreStartDate = d; DateTime choreEndDate = GetLastDayOfWeek(d); Chore Chore = CreateChore(guideline, choreStartDate, choreEndDate); WeeklyChores.Add(Chore); } return(WeeklyChores); }
private Chore ParseEntry(string entry) { Chore chore = ChoreFactory.Empty; string[] fields = entry.Split(','); if (fields.Length >= 4) { string key = fields[0].Trim(); string name = fields[1].Trim(); double value = double.Parse(fields[2]); string description = fields[3].Trim(); chore = new FamilyChore(name, value, description); chore.SetKey(key); } return(chore); }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Chore = await _context.Chores .Where(c => c.RotatingChoresUserID == _userManager.GetUserId(User)) .SingleOrDefaultAsync(m => m.ID == id); if (Chore == null) { DangerMessage = ""; return(NotFound()); } return(Page()); }
static void Main(string[] args) { Person person = new Person() { FirstName = "pamal", LastName = "sahan", EmailAddress = "*****@*****.**", PhoneNumber = "0782916090" }; Chore chore = new Chore(); chore.ChoreName = "get trash"; chore.Owner = person; chore.PerformedWork(3); chore.PerformedWork(1.3); chore.CompleteChore(); }
/// <summary> /// Adjusts deconstruct priorities based on the options. /// </summary> /// <param name="priorityMod">The priority to modify.</param> /// <param name="chore">The parent chore.</param> private static void AdjustDeconstructPriority(ref int priorityMod, Chore chore) { BuildingDef def; if (chore.target is Deconstructable target && target != null && (def = target. GetComponent<Building>()?.Def) != null) { string id = target.GetComponent<Building>()?.Def?.PrefabID; if (Options.PrioritizeBuildings.Contains(id)) priorityMod -= AIImprovementsOptions.BUILD_PRIORIY_MOD; else if (Options.DeprioritizeBuildings.Contains(id)) priorityMod += AIImprovementsOptions.BUILD_PRIORIY_MOD; if (def.IsFoundation) { // Avoid destroying a tile recently stood on by a dupe int cell = Grid.CellAbove(Grid.PosToCell(target)); if (AllMinionsLocationHistory.Instance.WasRecentlyOccupied(cell)) priorityMod -= AIImprovementsOptions.BLOCK_PRIORITY_MOD; } } }
public bool Save(ChoreDto dto) { var entity = new Chore { Title = dto.Title, CreatedAt = dto.CreatedAt, PlantId = dto.PlantId, IntervalInDays = dto.IntervalInDays }; if (dto.Id != null) { entity.Id = (int)dto.Id; var completedChore = _context.CompletedChores.AsEnumerable()?.LastOrDefault(cc => cc.CreatedAt.Date == DateTime.Today && cc.ChoreId == dto.Id); if (dto.IsCompleted && completedChore == null) { _context.CompletedChores?.Add(new CompletedChore { Title = dto.Title, ChoreId = (int)dto.Id, CreatedAt = DateTime.Now, PlantId = dto.PlantId }); } else if (!dto.IsCompleted && completedChore != null) { _context.CompletedChores?.Remove(completedChore); } _context.Entry <Chore>(entity).State = EntityState.Modified; _context.Entry <Chore>(entity).State = EntityState.Detached; } else { _context.Chores.Add(entity); } var result = _context.SaveChanges(); return(result > 0); }
public void UpdateChore() { IUserControlledCapacity component = GetComponent <IUserControlledCapacity>(); if (component != null && component.AmountStored > component.UserMaxCapacity) { if (chore == null) { chore = new WorkChore <DropToUserCapacity>(Db.Get().ChoreTypes.EmptyStorage, this, null, true, null, null, null, true, null, false, false, null, false, true, true, PriorityScreen.PriorityClass.basic, 5, false, true); } } else if (chore != null) { chore.Cancel("Cancelled emptying"); chore = null; GetComponent <KSelectable>().RemoveStatusItem(workerStatusItem, false); ShowProgressBar(false); } }
/// <summary> /// If the Duplicant has not yet acquired a task, checks for a task that they can /// complete during this Finish Tasks block. /// </summary> private void CheckAcquireChore() { if (acquireChore) { var currentChore = driver.GetCurrentChore(); PriorityClass pc; // Allow acquiring the current chore if it is above idle and below urgent if (currentChore != null && (pc = currentChore.masterPriority.priority_class) > PriorityClass.idle && pc < PriorityClass.personalNeeds) { #if DEBUG PUtil.LogDebug("{0} may finish {1}".F(gameObject.name, currentChore. GetType().FullName)); #endif acquireChore = false; allowedChore = currentChore; } } }
static void AddChore(ChoreRepository choreRepo) { Console.Write("Chore name: "); string name = Console.ReadLine(); Console.Write("Max occupancy: "); int max = int.Parse(Console.ReadLine()); Chore choreToAdd = new Chore() { Name = name, }; choreRepo.Insert(choreToAdd); Console.WriteLine($"{choreToAdd.Name} has been added and assigned an Id of {choreToAdd.Id}"); Console.Write("Press any key to continue"); Console.ReadKey(); }
/// <summary> /// Adds a chore precondition to check if the Duplicant is allowed to use that /// building. /// </summary> /// <param name="chore">The chore to modify.</param> private static void AddProfilePrecondition(Chore chore) { var choreTypes = Db.Get().ChoreTypes; var type = chore.choreType; // Blacklist all fetch, empty storage, decon, repair, disinfect if (type != null && type != choreTypes.EmptyStorage && type != choreTypes. Deconstruct && type != choreTypes.Repair && type != choreTypes.Disinfect && !type.Id.Contains("Fetch") && chore.target is Component cmp && cmp != null && IS_ALLOWED.fn != null) { // Look for WP object var profiles = cmp.gameObject.GetComponentSafe <WorkshopProfile>(); if (profiles != null) { chore.AddPrecondition(IS_ALLOWED, profiles); } } }
static void AddNewChore(ChoreRepository choreRepo) { Console.Clear(); Console.SetCursorPosition((Console.WindowWidth - 9) / 2, Console.CursorTop); Console.WriteLine("New Chore"); Console.SetCursorPosition((Console.WindowWidth - 9) / 2, Console.CursorTop); Console.WriteLine("---------"); Console.WriteLine("\nPlease enter the name of the new chore."); Chore newChore = new Chore() { Name = Console.ReadLine() }; Console.WriteLine(" ..."); choreRepo.Add(newChore); Console.WriteLine($"\n{newChore.Name} added to the list"); }
public async Task<IHttpActionResult> Put(Chore chore) { if (!ModelState.IsValid) return BadRequest(ModelState); chore.ObjectState = ObjectState.Modified; _choreService.Update(chore); try { await _unitOfWorkAsync.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ChoreExists(chore.Id)) return NotFound(); throw; } return new NoContentActionResult(Request, Url.Link("GetChore", new {id = chore.Id})); }