public async Task<List<ShoppingListItem>> GetListItems (ShoppingList list) { if ( ! IsLoggedIn ) { return new List<ShoppingListItem> (); } HttpResponseMessage response = await client.GetAsync (SHOPPING_LISTS_URL + list.Id + "/items/"); return await response.Content.ReadAsAsync<List<ShoppingListItem>> (); }
private static ShoppingList CreateDefault() { ISupermarketSectionService supermarketSectionService = new SupermarketSectionService(); int id = 1; var result = new ShoppingList { new ShoppingListItem(id++) { Description = "Large Eggs", Quantity = "6", Notes = "Free range please!", Section = supermarketSectionService.Select("Dairy") }.WithImage("eggs.jpg"), new ShoppingListItem(id++) { Description = "Pints of Milk", Quantity = "4", Section = supermarketSectionService.Select("Dairy") }.WithImage("milk.jpg"), new ShoppingListItem(id++) { Description = "Bag of Apples", Section = supermarketSectionService.Select("Fruit N Veg"), Quantity = "1" }, new ShoppingListItem(id) { Description = "Boxes of Wine", Section = supermarketSectionService.Select("Booze"), Quantity = "4" } }; return result; }
public void itemButton_Click(object sender, EventArgs e) { IService service = new ServiceClient(); Form1 form1 = (Form1)ParentForm; int listNumber = Int32.Parse(((Button)sender).Tag.ToString()); form1.ItemPanel.Visible = true; form1.ListPanel.Visible = false; form1.ItemPanel.shoppingListID = listNumber; ShoppingList sl = new ShoppingList(); foreach (ShoppingList list in form1.p.shoppingLists) { if(list.ShoppingListNumber == listNumber) { sl = list; } } PartList[] pslArray = sl.PartLists; List<PartList> psl = pslArray.ToList(); foreach (Person user in sl.Users) { if (user.Username != form1.p.Username) { form1.DgvPersons.Rows.Add(user.Name, user.Username); } } form1.ItemPanel.PopulatePanel(psl,sl); form1.TxtNote.Text = sl.Note; form1.Size = new System.Drawing.Size(1041, 598); form1.ItemPanel.BtnSaveList.Enabled = false; }
public ShoppingListDeleter Delete(ShoppingList list) { if (list == ShoppingList.DefaultList) throw new FluentExpressionException("Cannot delete default shopping list."); return new ShoppingListDeleter(context, list); }
public ShoppingListUpdater(IKPCContext context, ShoppingList list) { this.context = context; this.list = list; this.addQueue = new List<ShoppingListAdder>(); this.updateQueue = new List<ShoppingListItemUpdater>(); this.removeQueue = new List<ShoppingListItem>(); }
public ShoppingListDeleter Delete(ShoppingList list) { if (list == ShoppingList.Default) { throw new FluentExpressionException("Cannot delete default shopping list."); } var result = new ShoppingListDeleter(this.context, list); return result; }
public static ShoppingList ToShoppingList(ShoppingLists dtoList) { var result = new ShoppingList { Id = dtoList.ShoppingListId, Title = dtoList.Title }; return result; }
public ShoppingListLoader Load(ShoppingList list) { if (this.loadAll) { throw new FluentExpressionException("To specify individual shopping lists to load, remove the LoadAll clause from your expression."); } this.listsToLoad.Add(list); return this; }
public ShoppingListDeleter Delete(ShoppingList list) { if (list == ShoppingList.Default) { throw new FluentExpressionException("Cannot delete default shopping list."); } this.deleteQueue.Add(list); return this; }
protected void ItemButton_Click(object sender, EventArgs e) { itemTable.Visible = true; Label2.Visible = true; personTable.Visible = true; Label3.Visible = true; int listNumber = Int32.Parse(((Button)sender).ID); ShoppingList sl = new ShoppingList(); foreach (ShoppingList list in p.shoppingLists) { if (list.ShoppingListNumber == listNumber) { sl = list; } } Label2.Text = "Varer på: " +sl.Title; PartList[] pslArray = sl.PartLists; List<PartList> psl = pslArray.ToList(); foreach (PartList pl in psl) { TableRow row = new TableRow(); TableCell vare = new TableCell(); vare.Text = pl.Item.Name; row.Cells.Add(vare); TableCell butik = new TableCell(); butik.Text = pl.Item.Location; row.Cells.Add(butik); TableCell antal = new TableCell(); antal.Text = pl.Amount.ToString(); row.Cells.Add(antal); TableCell pris = new TableCell(); pris.Text = pl.Item.Price.ToString(); row.Cells.Add(pris); TableCell købt = new TableCell(); CheckBox chkBought = new CheckBox(); chkBought.Checked = pl.Bought; købt.Controls.Add(chkBought); row.Cells.Add(købt); itemTable.Rows.Add(row); } foreach (Person p in sl.Users) { TableRow row = new TableRow(); TableCell navn = new TableCell(); navn.Text = p.Name; row.Cells.Add(navn); TableCell brugernavn = new TableCell(); brugernavn.Text = p.Username; row.Cells.Add(brugernavn); personTable.Rows.Add(row); } }
public ShoppingList GetOrCreate(int weekNumber) { var week = _db.Single<WeekSchedule>(q => q.Id == weekNumber); var shoppingList = _db.Single<ShoppingList>(q => q.WeekNumber == weekNumber); if (shoppingList == null) { shoppingList = new ShoppingList() { WeekNumber = weekNumber, Items = CreateShoppingListItems(week, _db.Select<Recipe>(), _db.Select<Product>()).OrderByDescending(i => i.Buy).ThenBy(i => i.Product).ToList() }; shoppingList.Id = (int)_db.Insert(shoppingList); } return shoppingList; }
public void PopulatePanel(List<PartList> l, ShoppingList sl) { lblTitle.Text = sl.Title; CurrentShoppingList = sl; flowLayoutPanel1.Controls.Clear(); foreach (PartList psl in l) { ItemLine il = new ItemLine(); il.NotifyParentAmountEvent += new NotifyParentAmountDelegate(AmountChanged); il.SetValues(psl.Item.Name, psl.Item.Price.ToString(), psl.Amount, psl.Bought, psl.Item.Location, psl.Id); flowLayoutPanel1.Controls.Add(il); } btnSaveList.Enabled = false; CalculateSum(); lblSaved.Text = ""; }
public IHttpActionResult PostItem(Item item) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ShoppingList shoppingList = db.ShoppingLists .Where(s => s.Id == item.ShoppingListId) .Include(s => s.Items) .FirstOrDefault(); db.Items.Add(item); db.SaveChanges(); return(Ok(shoppingList)); }
// Overwrites the given shopping list with the stored one that has the same Id. // Throws ShoppingListNotFoundException if there is no such list stored. Use AddList in that case first. public async Task <bool> UpdateList(ShoppingList list, string userId) { ShoppingList listEntity = GetShoppingListEntity(list.SyncId); if (listEntity == null) { throw new ShoppingListNotFoundException(list.SyncId); } CheckPermissionWithException(listEntity, userId, ShoppingListPermissionType.Write); bool success = UpdateShoppingList(list); if (success) { await _hubService.SendListUpdated(_userService.GetById(userId), list, ShoppingListPermissionType.Read); } return(success); }
private void DeleteFromShoppingList() { if (SelectedRow == -1) { MessageBox.Show("Du skal markere at produkt før du kan slette", "Error", MessageBoxButton.OK); } else if (ShoppingList.Count == 0) { MessageBox.Show("Der er ikke tilføjet nogen produkter", "Error", MessageBoxButton.OK); } else { ShoppingList.RemoveAt(SelectedRow); } }
private void RemoveItemFromShoppingList(SalesItem item) { var matchingItem = ShoppingList.Where(x => x.Name.Contains(item.Name)).FirstOrDefault(); if (matchingItem == null) { return; } else if (matchingItem != null && matchingItem.Quantity > 1) { matchingItem.Quantity -= 1; } else if (matchingItem.Quantity == 1) { ShoppingList.Remove(item); } }
public ActionResult Edit([Bind(Include = "ID,Label,DateCreated,ListPriorityID")] ShoppingList shoppingList) { // sort the list items!!! if (ModelState.IsValid) { db.Entry(shoppingList).State = EntityState.Modified; db.SaveChanges(); SortShoppingListItems(shoppingList.ID); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ListPriorityID = new SelectList(db.ListPriorities, "ListPriorityID", "Label", shoppingList.ListPriorityID); return(View(shoppingList)); }
public void DeleteItemTest() { var list = new ShoppingList { Name = "test", GroupId = 1 }; var item = new ShoppingListItem { Name = "testItem", ShoppingListId = list.Id }; list.ShoppingListItems.Add(item); DbContext.ShoppingLists.Add(list); DbContext.SaveChanges(); Service.DeleteShoppingListItemAsync(item.Id); Assert.DoesNotContain(item, DbContext.ShoppingListItems); }
public IHttpActionResult DeleteItem(int id) { Item item = db.Items.Find(id); if (item == null) { return(NotFound()); } ShoppingList shoppingList = db.ShoppingLists.Where(s => s.Id == item.ShoppingListId).Include(s => s.Items).FirstOrDefault(); db.Items.Remove(item); db.SaveChanges(); return(Ok(shoppingList)); }
public void AddItem() { if (!string.IsNullOrWhiteSpace(_searchString) && _searchString.Length > 2) { var newList = new ShoppingList() { Name = _searchString }; ShoppingLists.Insert(0, newList); Device.BeginInvokeOnMainThread(async() => { Clear(); _shoppingService.AddList(newList); await LoadData(); }); } }
public ShoppingList Get(long id, bool includeListItems = false, bool includeCreator = false) { ShoppingList shoppingList = _dbContext.ShoppingLists.Find(id); if (shoppingList != null) { if (includeListItems) { _dbContext.Entry(shoppingList).Collection(sl => sl.ListItems).Load(); } if (includeCreator) { _dbContext.Entry(shoppingList).Reference(sl => sl.Creator).Load(); } } return(shoppingList); }
public void AddShoppingList(ShoppingList shoppingList) { if (shoppingList == null) { throw new ArgumentNullException(nameof(shoppingList)); } //the repository fills the id (instead of using identity columns) shoppingList.Id = Guid.NewGuid(); foreach (var shoppingItem in shoppingList.ShoppingItems) { shoppingItem.Id = Guid.NewGuid(); } _context.ShoppingLists.Add(shoppingList); }
// POST: api/Item public IHttpActionResult Post([FromBody] Item item) { ShoppingList shoppingList = ShoppingListController.shoppingLists .Where(s => s.Id == item.ShoppingListId) .FirstOrDefault(); if (shoppingList == null) { return(NotFound()); } item.Id = shoppingList.Items.Max(i => i.Id) + 1; shoppingList.Items.Add(item); return(Ok(shoppingList)); }
public async Task <ShoppingList> UpdateAsync(string id, ShoppingList item) { if (!ItemCanBeUpdated(item)) { throw new ItemAlreadyExistsException(typeof(ShoppingList), item.Id); } var existing = await GetAsync(id); existing.Name = item.Name; existing.ListDate = item.ListDate; existing.OwnerId = item.OwnerId; var deleteItems = existing.Items .Where(i => !item.Items.Any(j => j.ProductItemId == i.ProductItemId)) .Select(i => i.Id) .ToList(); foreach (var deleteId in deleteItems) { var delete = await _context.ShoppingListItems.FirstOrDefaultAsync(i => i.Id == deleteId); if (delete != null) { _context.ShoppingListItems.Remove(delete); } } foreach (var updateItem in item.Items) { var existingItem = await _context.ShoppingListItems.FirstOrDefaultAsync(i => i.Id == updateItem.Id); if (existing == null) { _context.ShoppingListItems.Add(updateItem); } else { existingItem.Amount = updateItem.Amount; existingItem.Done = updateItem.Done; } } await _context.SaveChangesAsync(); return(existing); }
private void Form1_Load(object sender, EventArgs e) { Imcones.ColumnsListViewIncome(listViewIncome); Imcones.DisplayIncomeDB(listViewIncome); Payments.ColumnsListViewPayment(listViewPayment); Payments.DisplayPaymentDB(listViewPayment); Payments.ComboBoxTitleElements(comBoxTitle); ShoppingList.ColumnsShoppingList(listViewShoppingList); ShoppingList.DisplayShoppingList(listViewShoppingList); Summary.IncomeDisplayThree(lblIncomeName1, lblIncomeName2, lblIncomeName3, lblIncomeData1, lblIncomeData2, lblIncomeData3, lblIncomeValue1, lblIncomeValue2, lblIncomeValue3); Summary.PaymentDisplayThree(lblPaymentName1, lblPaymentName2, lblPaymentName3, lblPaymentDate1, lblPaymentDate2, lblPaymentDate3, lblPaymentValue1, lblPaymentValue2, lblPaymentValue3); Summary.IncomeDisplayPeriod(lblIncomeMonth, lblIncomeYear, lblIncomeAll); Summary.PaymentDisplayPeriod(lblPaymentMonth, lblPaymentYear, lblPaymentAll); lblLoggedUser.Text = userLogin; txtName.Text = userLogin; txtBuyerName.Text = userLogin; }
public void TestSerialization() { ShoppingList myList = new ShoppingList(); myList.AddItem(new Item("eggs", 1.49)); myList.AddItem(new Item("ground beef", 3.69)); myList.AddItem(new Item("bread", 0.89)); // Serialization XmlSerializer s = new XmlSerializer(typeof(ShoppingList)); TextWriter w = new StreamWriter(@"c:\list.xml"); s.Serialize(w, myList); w.Close(); // Deserialization }
public async Task <bool> DeleteListForEveryone(string shoppingListId, string userId) { ShoppingList listEntity = GetShoppingListEntity(shoppingListId); if (listEntity == null) { throw new ShoppingListNotFoundException(shoppingListId); } CheckPermissionWithException(listEntity, userId, ShoppingListPermissionType.Delete); // Send to all with permission Read await _hubService.SendListRemoved(_userService.GetById(userId), shoppingListId, ShoppingListPermissionType.Read); bool success = DeleteListWithoutChecks(shoppingListId); return(success); }
public async Task <IActionResult> UpdateShoppingList(ShoppingList updatedShoppingList) { IApiResponse response; if (updatedShoppingList == null) { response = new ApiResponse(HttpStatusCode.BadRequest) { Message = "Cannot update an invalid shopping list." }; return(new ObjectResult(response)); } response = await _service.UpdateAsync(updatedShoppingList); return(new ObjectResult(response)); }
public IActionResult Post([FromBody] ShoppingList shoppinglist) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (shoppinglist.Id == 0) { _shoppinglistservices.createShoppingList(shoppinglist); } else { _shoppinglistservices.updateShoppingList(shoppinglist); } return(Ok(shoppinglist)); }
private static ShoppingList CreateDefault() { var result = new ShoppingList { new ShoppingListItem { Description = "Large Eggs", Quantity = "6", Notes = "Free range please!", Image = "/images/eggs.jpg" }, new ShoppingListItem { Description = "Pints of Milk", Quantity = "4", Image = "/images/milk.jpg" }, new ShoppingListItem { Description = "Bag of Apples", Quantity = "1" }, new ShoppingListItem { Description = "Boxes of Wine", Quantity = "4" } }; return result; }
/// <summary> /// Creates a new <c>ShoppingList</c>-Object, adds it to the <c>ShoppingLists</c>-Collection (located in the <c>MainPageViewModel</c>). /// </summary> private async void CreateShoppingList() { if (IsDataValid()) { ShoppingList shList = new ShoppingList(Guid.NewGuid().ToString(), ListName.Trim(), SelectedShop); ServiceLocator.Current.GetInstance <MainPageViewModel>().AddShoppingList(shList); InitializeFields(); navigationService.GoBack(); } else { await dialogService.ShowMessage( ResourceLoader.GetForCurrentView().GetString("AddShoppingListValidationErrorContent"), ResourceLoader.GetForCurrentView().GetString("ErrorTitle")); } }
public async Task <bool> DeleteList(string shoppingListId, string thisUserId, string targetUserId) { ShoppingList listEntity = GetShoppingListEntity(shoppingListId); if (listEntity == null) { throw new ShoppingListNotFoundException(shoppingListId); } bool success = await RemoveListPermission(thisUserId, targetUserId, shoppingListId); if (success) { // Send to target user await _hubService.SendListRemoved(_userService.GetById(thisUserId), shoppingListId, targetUserId); } return(success); }
public override void StartAction() { // New Shopping List ShoppingList ShoppingListScript = ShoppingListManager.shoppingListScript; ShoppingListScript.GenerateNewShoppingList(productCount); ShoppingListManager.GenerateTextForShoppingList(); ShoppingListManager.ShowShoppingList(); // Empty Basket ProductsInTheBasket ProductsInTheBasket = ProductsInTheBasketManager.ProductsInTheBasketScript; ProductsInTheBasket.InitializeNewBasket(); ProductsInTheBasketManager.GenerateNewTextForProductsInTheBasket(); // Reset(prepareTime, ShoppingListManager.HideShoppingList); }
private void AddShoppingListItem(Item item) { var matchedItems = ShoppingList.Where(x => x.InventoryModel.InventoryId == item.InventoryModel.InventoryId).ToList(); if (matchedItems.Count > 0) { var matchedItemIndex = ShoppingList.IndexOf(matchedItems.FirstOrDefault()); ShoppingList[matchedItemIndex].InventoryModel.Quantity += item.InventoryModel.Quantity; ShoppingList = new ObservableCollection <Item>(ShoppingList); } else { ShoppingList.Add(item); } CalculateTotalPrice(); }
public void UpdateItemTest() { var list = new ShoppingList { Name = "test", GroupId = 1 }; var item = new ShoppingListItem { Name = "testItem", ShoppingListId = list.Id }; list.ShoppingListItems.Add(item); DbContext.ShoppingLists.Add(list); DbContext.SaveChanges(); item.Name = "testItem2"; Service.UpdateShoppingListItemAsync(item).Wait(); Assert.True(DbContext.ShoppingListItems.Any(i => i.Name == "testItem2")); }
public IHttpActionResult Put(string name, ShoppingItem shoppingItem) { if (!ShoppingList.ExistsInList(name)) { return(NotFound()); } if (name != shoppingItem.Item.Name) { return(BadRequest("Wrong Item")); } var res = ShoppingList.UpdateQuantity(name, shoppingItem.Quantity); if (res) { return(Ok(shoppingItem)); } return(BadRequest("Could not update item")); }
public async Task <IApiResponse> AddAsync(string shoppingListName) { var currentDate = DateTime.Now; var shoppingList = new ShoppingList { Name = shoppingListName, CreatedAt = currentDate, LastUpdated = currentDate }; await _repository.AddAsync(shoppingList); return(new ApiResponse(HttpStatusCode.Created) { Result = shoppingList }); }
public static ShoppingList GetSortedList(string GroupID, string marketID) { Group group = GroupBL.GetGroupByID(GroupID); ShoppingList list = group.CurrentList; List <Category> order = GetCategoriesDependecies(marketID); ShoppingList ordered = new ShoppingList(); // Adds all products by the category order order.ForEach(c => ordered.ProductsList.AddRange(list.ProductsList.Where(p => c.Products.Contains(p.Name)))); // Adds the rest of the products list.ProductsList.Where(p => !ordered.ProductsList.Contains(p)).ToList() /*.OrderBy(p=>p.Category).ToList()*/ .ForEach(p => ordered.ProductsList.Add(p)); group.CurrentList = ordered; return(ordered); }
public ShoppingListPermissionType GetUserListPermission(string shoppingListId, string thisUserId, string targetUserId) { ShoppingList listEntity = GetShoppingListEntity(shoppingListId); if (listEntity == null) { throw new ShoppingListNotFoundException(shoppingListId); } CheckPermissionWithException(listEntity, thisUserId, ShoppingListPermissionType.Read); var query = from list in _db.Set <ShoppingList>() join perm in _db.Set <ShoppingListPermission>() on list.SyncId equals perm.ShoppingListId where perm.UserId.Equals(targetUserId) && perm.ShoppingListId.Equals(shoppingListId) select perm.PermissionType; return(query.ToList().FirstOrDefault()); }
public ActionResult RemoveFromCart(int id) { var cart = ShoppingList.GetCart(this.HttpContext); string productName = db.Carts.FirstOrDefault(item => item.IngredientId == id).Ingredient.Name; int itemCount = cart.RemoveFromCart(id); var results = new ShoppingCartRemoveViewModel { Message = Server.HtmlEncode(productName) + " has been removed from your shopping cart", CartCount = cart.GetCount(), ItemCount = itemCount, DeleteId = id }; return(Json(results)); }
public void AddOrUpdateShoppingList(ShoppingList shoppingList) { if (shoppingList.Id != 0) { var shoppingListEntity = _context.ShoppingLists.Include("Ingredients").Include("Recipes").FirstOrDefault(n => n.Id == shoppingList.Id); shoppingListEntity.Name = shoppingList.Name; shoppingListEntity.Description = shoppingList.Description; DeleteData(shoppingListEntity.Ingredients); shoppingListEntity.Ingredients.AddRange(shoppingList.Ingredients); DeleteData(shoppingListEntity.Recipes); shoppingListEntity.Recipes.AddRange(shoppingList.Recipes); _context.ShoppingLists.Update(shoppingListEntity); } else { _context.ShoppingLists.Add(shoppingList); } }
public void GivenAShoppingListExists_WhenAttemptToRetrieveShoppingListItem_ShouldReturnCorrectItemDto(string name) { var random = new Random(); var id = Guid.NewGuid(); var quantity = (uint)random.Next(int.MaxValue); var expectedShoppingList = new ShoppingList(id, new Dictionary <string, Item>() { { name, new Item(name, quantity) } }); shoppingListRepositoryMock.Setup(x => x.Get(id)).Returns(() => expectedShoppingList); var sut = fixture.Create <ShoppingListService>(); var result = sut.GetShoppingListItem(id, name); result.Name.Should().Be(name); result.Quantity.Should().Be(quantity); }
public ActionResult UpdateList(int id, ShoppingList sl) { try { if (ModelState.IsValid) { // caut lista de cumparaturi in baza de date ShoppingList list = ctx.ShoppingLists.Find(id); list.Titlu = sl.Titlu; ctx.SaveChanges(); return(RedirectToAction("Index", "ShoppingList")); } return(View("EditList", sl)); } catch (Exception e) { return(View("EditList", sl)); } }
public ShoppingListResult CreateShoppingList(ShoppingList list) { throw new NotImplementedException(); }
/// <summary> /// Creates a new shopping list for the current user. /// </summary> /// <param name="list">A ShoppingList object containing a normalized shopping list.</param> /// <returns>A result indicating the ID assigned to the newly created list.</returns> public ShoppingListResult CreateShoppingList(ShoppingList list) { var ret = new ShoppingListResult(); var dbList = new Data.DTO.ShoppingLists { ShoppingListId = Guid.NewGuid(), Title = list.Title.Trim(), UserId = Identity.UserId }; store.ShoppingLists.Add(dbList); if (list.Any()) // Create ShoppingListItems { list.ToList().ForEach(i => store.ShoppingListItems.Add(new ShoppingListItems { ItemId = Guid.NewGuid(), UserId = Identity.UserId, ShoppingListId = dbList.ShoppingListId, CrossedOut = i.CrossedOut, IngredientId = i.Ingredient != null ? (Guid?) i.Ingredient.Id : null, RecipeId = i.Recipe != null ? (Guid?) i.Recipe.Id : null, Raw = i.Raw, Qty = i.Amount != null ? (float?) i.Amount.SizeHigh : null, Unit = i.Amount != null ? (Units?) i.Amount.Unit : null })); } ret.NewShoppingListId = dbList.ShoppingListId; ret.List = list; return ret; }
/// <summary> /// Deletes one or more shopping lists owned by the current user. /// </summary> /// <param name="lists">One or more shopping lists to delete. Note, the default shopping list cannot be deleted.</param> public void DeleteShoppingLists(ShoppingList[] lists) { var ids = lists.Where(p => p.Id.HasValue).Select(p => p.Id.Value).ToList(); var dbItems = store.ShoppingListItems .Where(p => p.UserId == Identity.UserId) .Where(p => p.ShoppingListId.HasValue) .Where(p => ids.Contains(p.ShoppingListId.Value)); var dbLists = store.ShoppingLists .Where(p => p.UserId == Identity.UserId) .Where(p => ids.Contains(p.ShoppingListId)); store.ShoppingListItems.RemoveAll(dbItems.Contains); store.ShoppingLists.RemoveAll(dbLists.Contains); }
public ShoppingListLoader(IKpcContext context, ShoppingList list) { this.context = context; this.listsToLoad = new List<ShoppingList>() { list }; }
/// <summary> /// Updates a shopping list. /// </summary> /// <param name="list">A shopping list owned by the current user.</param> /// <param name="updates">A set of update commands indicating how the shopping list should be updated.</param> /// <param name="newName">An optional new name for this shopping list.</param> /// <returns></returns> public virtual ShoppingListResult UpdateShoppingList(ShoppingList list, ShoppingListUpdateCommand[] updates, string newName = null) { // Aggregate new items var parsedIngredients = Parser.ParseAll(updates.Where(u => !string.IsNullOrWhiteSpace(u.NewRaw)).Select(r => r.NewRaw).ToArray()).ToList(); var recipeAggregation = this.AggregateRecipes(updates.Where(u => u.NewRecipe != null) .Select(r => r.NewRecipe.Id).ToArray()); var ingredientsAggregation = updates.Where(u => u.NewIngredient != null) .Select(i => new IngredientAggregation(i.NewIngredient, null)); var ingredientUsages = this.AggregateIngredients(updates.Where(u => u.NewUsage != null) .Select(u => u.NewUsage).ToArray()); var parsedUsages = this.AggregateIngredients(parsedIngredients.Where(u => u is Match) .Select(u => u.Usage).ToArray()); var rawInputs = parsedIngredients .Where(u => u is NoMatch) .Select(u => new ShoppingListItem(u.Input)); var newItems = recipeAggregation .Concat(ingredientsAggregation) .Concat(ingredientUsages) .Concat(parsedUsages) .Concat(rawInputs) .ToArray(); var removedItems = updates .Where(u => u.Command == ShoppingListUpdateType.RemoveItem) .Select(i => i.RemoveItem.Value) .ToArray(); var modifiedItems = updates .Where(u => u.Command == ShoppingListUpdateType.ModifyItem) .Select(i => i.ModifyItem) .ToArray(); return this.Adapter.UpdateShoppingList(this.Identity, list.Id, removedItems, modifiedItems, newItems, newName); }
public ShoppingListUpdater Update(ShoppingList list) { var result = new ShoppingListUpdater(this.context, list); return result; }
/// <summary> /// Creates a new shopping list for the current user. /// </summary> /// <param name="list">A ShoppingList object containing a normalized shopping list.</param> /// <returns>A result indicating the ID assigned to the newly created list.</returns> public virtual ShoppingListResult CreateShoppingList(ShoppingList list) { return this.Adapter.CreateShoppingList(this.Identity, list); }
public ShoppingListLoader Load(ShoppingList list) { var result = new ShoppingListLoader(this.context, list); return result; }
/// <summary> /// Deletes one or more shopping lists owned by the current user. /// </summary> /// <param name="lists">One or more shopping lists to delete. Note, the default shopping list cannot be deleted.</param> public virtual void DeleteShoppingLists(ShoppingList[] lists) { this.Adapter.DeleteShoppingLists(this.Identity, lists); }
public ShoppingListUpdater Update(ShoppingList list) { return new ShoppingListUpdater(this.context, list); }
public ShoppingListLoader Load(ShoppingList list) { return new ShoppingListLoader(this.context, list); }
public void DeleteShoppingLists(ShoppingList[] lists) { throw new NotImplementedException(); }
/// <summary> /// Creates a new shopping list for the current user. /// </summary> /// <param name="name">The name of the new shopping list.</param> /// <param name="recipes">Zero or more recipes to add to this list.</param> /// <param name="ingredients">Zero or more ingredients to add to this list.</param> /// <param name="usages">Zero or more ingredient usages to add to this list.</param> /// <param name="items">Zero or more raw usages. Raw usages will be parsed using NLP, and unsuccessful matches will be added to the list as raw items.</param> /// <returns>A fully aggregated shopping list, with like items combined and forms normalized.</returns> public virtual ShoppingListResult CreateShoppingList( string name, Recipe[] recipes, Ingredient[] ingredients, IngredientUsage[] usages, string[] items) { var parsedIngredients = Parser.ParseAll(items).ToList(); var recipeAggregation = this.AggregateRecipes(recipes.Select(r => r.Id).ToArray()); var ingredientsAggregation = ingredients.Select(i => new IngredientAggregation(i, null)); var ingredientUsages = this.AggregateIngredients(usages); var parsedUsages = this.AggregateIngredients(parsedIngredients.Where(u => u is Match).Select(u => u.Usage).ToArray()); var rawInputs = parsedIngredients.Where(u => u is NoMatch).Select(u => new ShoppingListItem(u.Input)); var allItems = recipeAggregation .Concat(ingredientsAggregation) .Concat(ingredientUsages) .Concat(parsedUsages) .Concat(rawInputs); var list = new ShoppingList(null, name, allItems); return this.CreateShoppingList(list); }
public ShoppingListResult UpdateShoppingList(ShoppingList list, ShoppingListUpdateCommand[] updates, string newName = null) { throw new NotImplementedException(); }
public ShoppingListResult CreateShoppingList(AuthIdentity identity, ShoppingList list) { using (var session = GetSession()) { var ret = new ShoppingListResult(); using (var transaction = session.BeginTransaction()) { var dbList = new Models.ShoppingLists(); dbList.Title = list.Title.Trim(); dbList.UserId = identity.UserId; session.Save(dbList); if (list.Any()) // Create ShoppingListItems { list.ToList().ForEach(i => { var dbItem = ShoppingListItems.FromShoppingListItem(i); dbItem.ShoppingList = dbList; dbItem.UserId = dbList.UserId; session.Save(dbItem); }); } transaction.Commit(); ret.NewShoppingListId = dbList.ShoppingListId; } ret.List = list; return ret; } }
public void DeleteShoppingLists(AuthIdentity identity, ShoppingList[] lists) { if (!lists.Any()) throw new ArgumentException("DeleteShoppingLists requires at least one list to delete."); using (var session = GetSession()) { using (var transaction = session.BeginTransaction()) { var dbLists = session.QueryOver<Models.ShoppingLists>() .AndRestrictionOn(p => p.ShoppingListId).IsInG(lists.Where(l => l.Id.HasValue).Select(l => l.Id.Value)) .Where(p => p.UserId == identity.UserId) .List(); dbLists.ForEach(session.Delete); transaction.Commit(); } } }
public ShoppingListDeleter(IKPCContext context, ShoppingList list) { this.context = context; this.deleteQueue = new List<ShoppingList>() { list }; }