public void GetById_ShouldReturnStatusOk() { var ingredientRequest = new RestRequest("Ingredient", Method.POST); var ingredient = new IngredientModel { Name = "ingredient1", Price = 123 }; ingredientRequest.AddJsonBody(ingredient); var ingredientResponse = Client.Execute(ingredientRequest); Assert.That(ingredientResponse, Is.Not.Null); Assert.That(ingredientResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var returnedIngredientModel = _jsonDeserializer.Deserialize<IngredientModel>(ingredientResponse); var pizzaRequest = new RestRequest("Pizza", Method.POST); var pizza = new PizzaModel { Name = "pizza1", Price = 123, Toppings = new List<IngredientModel> { returnedIngredientModel } }; pizzaRequest.AddJsonBody(pizza); var pizzaResponse = Client.Execute(pizzaRequest); Assert.That(pizzaResponse, Is.Not.Null); Assert.That(pizzaResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var returnedPizzaModel = _jsonDeserializer.Deserialize<PizzaModel>(pizzaResponse); var request = new RestRequest(ResourceName, Method.POST); var order = new OrderModel { CreationDate = DateTimeOffset.Now, Price = 123, Address = "address", Pizzas = new List<PizzaModel> { returnedPizzaModel } }; request.AddJsonBody(order); var response = Client.Execute(request); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var orderModel = _jsonDeserializer.Deserialize<OrderModel>(response); var getRequest = new RestRequest(ResourceNameWithParameter, Method.GET); getRequest.AddUrlSegment("id", orderModel.Id.ToString()); var getResponse = Client.Execute(getRequest); Assert.That(getResponse, Is.Not.Null); Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK)); var returnedOrderModel = _jsonDeserializer.Deserialize<IngredientModel>(getResponse); Assert.That(returnedOrderModel, Is.Not.Null); Assert.That(returnedOrderModel.Id, Is.EqualTo(orderModel.Id)); }
public MainViewModel() { DBList = new ObservableCollection <IngredientModel>(IngredientModel.GetAll()); RecipeList = new ObservableCollection <RecipeModel>(); RecipeModel recipe = new RecipeModel { Name = "Kababs" }; recipe.Ingredients.Add(new RecipeItemModel { Ingredient = new IngredientModel { Name = "Onions" }, NumberOf = 3 }); recipe.Ingredients.Add(new RecipeItemModel { Ingredient = new IngredientModel { Name = "Peppers" }, NumberOf = 3 }); RecipeList.Add(recipe); RecipeModel recipe2 = new RecipeModel { Name = "Steak" }; recipe2.Ingredients.Add(new RecipeItemModel { Ingredient = new IngredientModel { Name = "Steak" }, NumberOf = 1 }); RecipeList.Add(recipe2); SelectedRecipe = RecipeList.First(); }
public async Task <IActionResult> CreateIngredient(IngredientModel model) { try { //Checks if model is valid if (!ModelState.IsValid) { return(View(model)); } //Changes photo path from the model model.PhotoPath = ControllerHelperMethods.UpdateIngridientPhotoPath(_ingredientPhotoFolderPath, model.Photo.FileName); //Converts model to Ingredient type Ingredient ingredientEntity = model.ToIngredientEntity(); //Adds new ingredient to database Ingredient newIngredient = await _ingredientRepository.Add(ingredientEntity); //Adds photo to server await ControllerHelperMethods.SaveIngredientPhoto(model.Photo, _ingredientPhotoFolderPath); return(RedirectToAction("IngredientInfo", new { id = newIngredient.Id })); } catch { return(View(model)); } }
public int Create(IngredientModel ingredientModel) { var ingredient = _mapper.Map <Ingredient>(ingredientModel); var addedId = _ingredientRepository.Create(ingredient); return(addedId); }
public static int AddIngredient(IngredientModel ingredient) { SqlConnection connection = RecipeListDB.GetConnection(); string insertStatement = "INSERT INTO Ingredient " + "(IngredientName) " + "VALUES(@Name)"; SqlCommand insertCommand = new SqlCommand(insertStatement, connection); insertCommand.Parameters.AddWithValue("Name", ingredient.Name); try { connection.Open(); insertCommand.ExecuteNonQuery(); string selectStatement = "SELECT IDENT_CURRENT('Ingredient') " + "FROM Ingredient"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); int ingredientID = Convert.ToInt32(selectCommand.ExecuteScalar().ToString()); return(ingredientID); } catch (SqlException ex) { throw ex; } finally { connection.Close(); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.Cookies["RecipeID"] != null) { string RecipeID = Server.HtmlEncode(Request.Cookies["RecipeID"].Value); RecipeModel item = new RecipeModel(); recipe Recipes = new recipe(); Recipes = item.GetRecipeByRecipeID(Convert.ToInt32(RecipeID)); //lblData.Text += string.Format("Recipe Name:{0}</br>Description: {1}</br>Submitted By: {2}</br>Category: {3}</br>Cooking time(mins): {4}</br>Number of serving: {5} </br>", // Recipes.Name, Recipes.Description, Recipes.SubmitedBy,Recipes.Category, Recipes.CookingTime, Recipes.Serving); txtName.Text = Recipes.Name; txtDescription.Text = Recipes.Description; lblSubmitedBy.Text = Recipes.SubmittedBy; DropDownList1.SelectedValue = Recipes.Category; txtTime.Text = Recipes.PrepTime.ToString(); txtNumOfServing.Text = Recipes.Servings.ToString(); IngredientModel item2 = new IngredientModel(); RecipeIngredientModel item1 = new RecipeIngredientModel(); List <recipeingredient> combine = new List <recipeingredient>(); combine = item1.getIngredientDetailByRecipeID(Convert.ToInt32(RecipeID)); int i = 1; grd.DataSource = GetTableWithInitialData(item1, item2, RecipeID); // get first initial data grd.DataBind(); //foreach(var x in combine) //{ // lblData1.Text += string.Format("{3}. {0} {1} {2}</br>", item2.getIngredientByID(x.Ingredient), x.quantity, x.UnitOfMeasure, i); // i++; //} } } }
public void GetById_ShouldReturnStatusCodeOk() { var postRequest = new RestRequest(ResourceName, Method.POST); var expectedIngredient = new IngredientModel { Name = "ingredient1", Price = 123 }; postRequest.AddJsonBody(expectedIngredient); var postResponse = Client.Execute(postRequest); Assert.That(postResponse, Is.Not.Null); Assert.That(postResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var ingredientModel = _jsonDeserializer.Deserialize<IngredientModel>(postResponse); var getRequest = new RestRequest(ResourceNameWithParameter, Method.GET); getRequest.AddUrlSegment("id", ingredientModel.Id.ToString()); var getResponse = Client.Execute(getRequest); Assert.That(getResponse, Is.Not.Null); Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK)); var returnedIngredientModel = _jsonDeserializer.Deserialize<IngredientModel>(getResponse); Assert.That(returnedIngredientModel, Is.Not.Null); Assert.That(returnedIngredientModel.Id, Is.EqualTo(ingredientModel.Id)); }
// only allowing updating of user submitted ingredients for now public async Task <bool> Update(int id, IngredientModel model) { try { using (IDbConnection connection = new SqlConnection(SqlHelper.connectionString)) { if (connection.State == ConnectionState.Closed) { connection.Open(); } model.updated_date = DateTime.Now.ToString(); var query = @"UPDATE FOODS SET name = @name, diet_type = @diet_type, description = @description, updated_date = @updated_date WHERE DATA_SOURCE = 4 AND Id = " + id; await connection.ExecuteAsync(query, model); return(true); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
public void AddIngredient(IngredientModel ingredientModel) { Ingredient objIngredient = new Ingredient() { IngredientId = ingredientModel.IngredientId, Name = ingredientModel.Name, Category = ingredientModel.Category, //Type = ingredientModel.Type, OperatorId = ingredientModel.OperatorId, OperatorLocationId = ingredientModel.OperatorLocationId, CommercialIngredientId = ingredientModel.CommercialIngredientId, ProductionTimeHours = ingredientModel.ProductionTimeHours, ProductionTimeDays = ingredientModel.ProductionTimeDays, ProductionTimeMonths = ingredientModel.ProductionTimeMonths, PerishabilityIndexHours = ingredientModel.PerishabilityIndexHours, PerishabilityIndexDays = ingredientModel.PerishabilityIndexDays, PerishabilityIndexMonths = ingredientModel.PerishabilityIndexMonths, StorageCapacityInLiquid = ingredientModel.StorageCapacityInLiquid, StorageCapacityInVolume = ingredientModel.StorageCapacityInVolume, StorageUsedCapacityLiquid = ingredientModel.StorageUsedCapacityLiquid, StorageUsedCapacityVolume = ingredientModel.StorageUsedCapacityVolume, CurrentPrice = ingredientModel.CurrentPrice, LastCost = ingredientModel.LastCost, date_creation = ingredientModel.date_creation, created_by = ingredientModel.created_by, modified_by = ingredientModel.modified_by, date_modified = ingredientModel.date_modified }; db.Ingredients.Add(objIngredient); db.SaveChanges(); }
public ActionResult Create(IngredientModel newIngredient, HttpPostedFileBase file, string description) { if (newIngredient.Price < 0) { ModelState.AddModelError("Price", "Ingredient price can't be negative"); } if (ModelState.IsValid) { newIngredient.Description = description; if (file != null) { string pic = Path.GetFileName(file.FileName); string path = Path.Combine( Server.MapPath("~/Content/Images/Ingredient"), pic); file.SaveAs(path); // save the image path path to the database using (MemoryStream ms = new MemoryStream()) { file.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); } newIngredient.ImgUrl = "/Content/Images/Ingredient/" + pic; } else { newIngredient.ImgUrl = "/Content/Images/Ingredient/default_ingredient.jpg"; } _repository.CreateIngredient(newIngredient); return(RedirectToAction("Index")); } return(View(newIngredient)); }
/// <summary> /// Creates new ingredient /// </summary> /// <param name="newObject">ingredient to be added to database</param> /// <returns>Ingredient that has been added to database or errors (depending on result type)</returns> public async Task <IServiceResult <IngredientModel> > CreateAsync(IngredientModel newObject) { try { // check if ingredient with that name already exists in db bool doesExistInDb = (await _repository.Ingredients.GetByExpressionAsync(x => x.Name.ToLower() == newObject.Name.ToLower(), null)).SingleOrDefault() == null ? false : true; if (doesExistInDb == false) { // try to add ingredient to database await _repository.Ingredients.CreateAsync(newObject); // save changes in database context await _repository.SaveChangesAsync(); // return Ok service result with created object return(new ServiceResult <IngredientModel>(ResultType.Created, newObject)); } return(new ServiceResult <IngredientModel>(ResultType.Error, new List <string> { $"Ingredient with name {newObject.Name} already exists in database" })); } catch (Exception e) { // catch exception and pass errors to controller return(new ServiceResult <IngredientModel>(ResultType.Error, new List <string> { e.Message })); } }
/// <summary> /// Gets ingredient with id passed by parameter /// </summary> /// <param name="id">identifier of ingredient</param> /// <returns>Ingredient from database or list of errors (depending on result type)</returns> public async Task <IServiceResult <IngredientModel> > GetByIdAsync(int id) { try { // try to get ingredient with specific id IngredientModel result = (await _repository.Ingredients.GetByExpressionAsync(x => x.Id == id, i => i.Include(id => id.IngredientDetails))).SingleOrDefault(); if (result != null) { // return it to controller return(new ServiceResult <IngredientModel>(ResultType.Correct, result)); } return(new ServiceResult <IngredientModel>(ResultType.Error, new List <string>() { $"Object with id: {id} has not been found" })); } catch (Exception e) { // catch errors and pass them to controller return(new ServiceResult <IngredientModel>(ResultType.Error, new List <string>() { e.Message })); } }
public ActionResult AddIngredient(IngredientModel objIngredient) { objIngredient.IngredientId = Guid.NewGuid(); ingredientRepository.AddIngredient(objIngredient); return(RedirectToAction("GetAllIngredients")); }
public IngredientListModel CreateIngredientListModel(int count, int skipIndex) { var ingredients = _ingredientService.GetIngredients(count, skipIndex); var ingredientModels = new List <IngredientModel>(); foreach (var ingredient in ingredients) { var ingredientModel = new IngredientModel { IngredientId = ingredient.IngredientId, Name = ingredient.Name, Description = ingredient.Description, CarbonHydrateWeightPercent = ingredient.CarbonHydrateWeightPercent, EnergyInKcal = ingredient.EnergyInKcal, FatWeightPercent = ingredient.FatWeightPercent, ProteineWeightPercent = ingredient.ProteineWeightPercent, AlcoholVolumePercent = ingredient.AlcoholVolumePercent }; ingredientModels.Add(ingredientModel); } var ingredientListModel = new IngredientListModel { Ingredients = ingredientModels }; ingredientListModel.NextPageNo = skipIndex + 1; return(ingredientListModel); }
public int InsertNewGeneratedCocktail(IngredientModel ingredientModel, int cocktailId) { dynamic id = 0; string query = "insert into [EyesAppIncTest.DB.Context].[dbo].[CocktailIngredients] " + "(CocktailId, IngredientId) " + "values " + "(@CocktailId, @IngredientId) "; using (SqlConnection connection = Connection.createConnection()) { SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@CocktailId", cocktailId); command.Parameters.AddWithValue("@IngredientId", ingredientModel.Id); connection.Open(); try { id = command.ExecuteScalar(); } finally { // Always call Close when done reading. connection.Close(); } } return(Convert.ToInt32(id)); }
//[Authorize(Policy = PermissionsList.PermissionsIngredientAdd)] public IActionResult AddIngredient([FromBody] IngredientModel ingredientModel) { Guid ingredientId = Guid.NewGuid(); var ingredientExist = _ingredientRepository.GetIngredient(ingredientModel.Name); if (!ModelState.IsValid || ingredientExist.Result != null) { return(BadRequest()); } Ingredient ingredient = new Ingredient() { Id = ingredientId, Name = ingredientModel.Name, Quantity = ingredientModel.Quantity, Price = ingredientModel.Price, ExpirationDate = ingredientModel.ExpirationDate }; _ingredientRepository.Create(ingredient); return(Ok(new { ingredient })); }
private string ValidationIngredient(IngredientModel ingredientModel) { string ErrorString = string.Empty; if (string.IsNullOrEmpty(ingredientModel.IngredientName)) { ErrorString = _locService.GetLocalizedHtmlString("ValidIngredientName"); return(ErrorString); } if (string.IsNullOrEmpty(ingredientModel.CategoryId.ToString()) || ingredientModel.CategoryId == 0) { ErrorString = _locService.GetLocalizedHtmlString("ValidCategory"); return(ErrorString); } if (string.IsNullOrEmpty(ingredientModel.UnitId.ToString()) || ingredientModel.UnitId == 0) { ErrorString = _locService.GetLocalizedHtmlString("ValidUnit"); return(ErrorString); } if (string.IsNullOrEmpty(ingredientModel.TaxId.ToString()) || ingredientModel.TaxId == 0) { ErrorString = _locService.GetLocalizedHtmlString("ValidTax"); return(ErrorString); } if (string.IsNullOrEmpty(ingredientModel.SalesPrice.ToString()) || ingredientModel.SalesPrice == 0) { ErrorString = _locService.GetLocalizedHtmlString("ValidSalesPrice"); return(ErrorString); } return(ErrorString); }
public IngredientModel GetIngredients(int id) { //get ingredient from the database Ingredient ingredient = _inventoryEntities.Ingredients .Include("IngredientQuantities") .FirstOrDefault(m => m.id == id); if (ingredient != null) { //convert data type Int to Enum for ingredient.type IngredientType ingredientParsed = (IngredientType)Enum.Parse(typeof(IngredientType), ingredient.type.ToString()); //convert ingredient to IngredientModel for controller to use IngredientModel ingredientModel = new IngredientModel(ingredient.id, ingredient.name, ingredientParsed, ingredient.expirationDate, ingredient.placeOfPurchase, ingredient.notes); //convert ingredient quantities List <IngredientQuantityModel> ingredientQuantities = ingredient.IngredientQuantities .AsEnumerable() .Select(m => new IngredientQuantityModel(m.ID, m.IngredientID, m.Amount, m.Unit)) .ToList(); //pass ingredient quantities tot he ingredient ingredientModel.IngredientQuantities = ingredientQuantities; //return the IngredientModel return(ingredientModel); } else { return(null); } }
public IngredientModel Detail(Guid IngredientId) { //return db.Recipe.Find(RecipeId); var Ingredient = db.Ingredients.Find(IngredientId); IngredientModel ingredientModel = new IngredientModel(); ingredientModel.IngredientId = Ingredient.IngredientId; ingredientModel.Name = Ingredient.Name; ingredientModel.Category = Ingredient.Category; //ingredientModel.Type = Ingredient.Type; ingredientModel.OperatorId = Ingredient.OperatorId; ingredientModel.OperatorLocationId = Ingredient.OperatorLocationId; ingredientModel.CommercialIngredientId = Ingredient.CommercialIngredientId; ingredientModel.ProductionTimeHours = Ingredient.ProductionTimeHours; ingredientModel.ProductionTimeDays = Ingredient.ProductionTimeDays; ingredientModel.ProductionTimeMonths = Ingredient.ProductionTimeMonths; ingredientModel.PerishabilityIndexHours = Ingredient.PerishabilityIndexHours; ingredientModel.PerishabilityIndexDays = Ingredient.PerishabilityIndexDays; ingredientModel.PerishabilityIndexMonths = Ingredient.PerishabilityIndexMonths; ingredientModel.StorageCapacityInLiquid = Ingredient.StorageCapacityInLiquid; ingredientModel.StorageCapacityInVolume = Ingredient.StorageCapacityInVolume; ingredientModel.StorageUsedCapacityLiquid = Ingredient.StorageUsedCapacityLiquid; ingredientModel.StorageUsedCapacityVolume = Ingredient.StorageUsedCapacityVolume; ingredientModel.CurrentPrice = Ingredient.CurrentPrice; ingredientModel.LastCost = Ingredient.LastCost; ingredientModel.date_creation = Ingredient.date_creation; ingredientModel.created_by = Ingredient.created_by; ingredientModel.modified_by = Ingredient.modified_by; ingredientModel.date_modified = Ingredient.date_modified; return(ingredientModel); }
/// <summary> /// Deletes ingredient with id passed by parameter /// </summary> /// <param name="ingredientId">id of ingredient</param> /// <returns>Service Result with statuses: Deleted or Error</returns> public async Task <IServiceResult> DeleteAsync(int ingredientId) { try { // get ingredient from database IngredientModel ingredientToDelete = (await _repository.Ingredients.GetByExpressionAsync(x => x.Id == ingredientId)).SingleOrDefault(); if (ingredientToDelete != null) { // try to delete it _repository.Ingredients.Delete(ingredientToDelete); // save changes in database context await _repository.SaveChangesAsync(); // return service result with Deleted status return(new ServiceResult(ResultType.Deleted)); } return(new ServiceResult(ResultType.Error, new List <string> { $"Ingredient with id {ingredientId} was not found in database" })); } catch (Exception e) { // catch exception and pass errors to controller return(new ServiceResult(ResultType.Error, new List <string> { e.Message })); } }
public Task AddIngredient(IngredientModel ingredientModel) { Guid ingredientId = Guid.NewGuid(); var ingredientExist = _ingredientRepository.GetIngredient(ingredientModel.Name).Result; var ingredientsOld = _ingredientRepository.GetAll().Result; if (ingredientExist != null) { return(Clients.All.SendAsync("GetIngredients", ingredientsOld)); } Ingredient ingredient = new Ingredient() { Id = ingredientId, Name = ingredientModel.Name, Quantity = ingredientModel.Quantity, Price = ingredientModel.Price, ExpirationDate = ingredientModel.ExpirationDate }; _ingredientRepository.Create(ingredient); var ingredients = _ingredientRepository.GetAll().Result; return(Clients.All.SendAsync("GetIngredients", ingredients)); }
public static bool RemoveIngredient(IngredientModel ingredient) { SqlConnection connection = RecipeListDB.GetConnection(); string deleteStatement = "DELETE FROM Ingredient " + "WHERE IngredientID = @IngredientID"; SqlCommand deleteCommand = new SqlCommand(deleteStatement, connection); deleteCommand.Parameters.AddWithValue("IngredientID", ingredient.Id); try { connection.Open(); int rows = deleteCommand.ExecuteNonQuery(); if (rows >= 1) { return(true); } else { return(false); } } catch (SqlException ex) { throw ex; } finally { connection.Close(); } }
internal static Ingredient ConvertIngredientModelToIngredient(IngredientModel ingredientModel) { return(new Ingredient { Name = ingredientModel.Name }); }
public static void RemoveIngredient(IngredientModel model) { UnitOfWorkRepository unitOfWork = new UnitOfWorkRepository(); var ingredient = IngredientFactory.ConvertIngredientModel(model); unitOfWork.IngredientRepository.RemoveIngredient(ingredient.Id); }
public async Task <(string, bool, IngredientModel model)> Add(IngredientModel model) { try { using (IDbConnection connection = new SqlConnection(SqlHelper.connectionString)) { if (connection.State == ConnectionState.Closed) { connection.Open(); } model.created_date = DateTime.Now.ToString(); model.updated_date = DateTime.Now.ToString(); model.data_source = 4; // user submitted data source var param = this.SetParameters(model); await connection.QueryAsync <IngredientModel>("spAddFood", param, commandType : CommandType.StoredProcedure); IngredientModel ingredient = null; if (param.Get <Int32>("foodID") > -1) { ingredient = await GetById(param.Get <Int32>("foodID")); } return(param.Get <String>("responseMessage"), param.Get <Boolean>("successVal"), ingredient); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(ex.Message, false, null); } }
void BuildCompanyCraftDrafts() { foreach (var sCompanyCraftDraft in _builder.Sheet <Saint.CompanyCraftDraft>()) { var name = sCompanyCraftDraft.Name.ToString(); if (string.IsNullOrEmpty(name)) { continue; } var draft = _builder.CreateItem("draft" + sCompanyCraftDraft.Key); _builder.Localize.Strings((JObject)draft, sCompanyCraftDraft, Utils.CapitalizeWords, "Name"); draft.en.description = "Unlocks company recipes for " + sCompanyCraftDraft.CompanyCraftDraftCategory.Name.ToString() + "."; draft.ilvl = 1; draft.category = -2; draft.icon = "custom/draft"; // Setup unlocks as a recipe. dynamic recipe = new JObject(); recipe.id = "draft" + sCompanyCraftDraft.Key; recipe.job = 0; recipe.rlvl = 1; recipe.lvl = 1; recipe.fc = 1; recipe.ingredients = new JArray(); foreach (var sRequiredItem in sCompanyCraftDraft.RequiredItems) { var ingredient = new IngredientModel(sRequiredItem.Item, sRequiredItem.Count, null, 0); recipe.ingredients.Add(ConvertIngredient(ingredient, draft)); } draft.craft = new JArray(recipe); // Record unlocks. draft.unlocks = new JArray(); foreach (var sUnlockedSequence in sCompanyCraftDraft.UnlockedSequences) { if (sUnlockedSequence.ResultItem.Key == 0) { continue; } var unlockedItem = _builder.Db.ItemsById[sUnlockedSequence.ResultItem.Key]; foreach (var innerRecipe in unlockedItem.craft) { innerRecipe.unlockId = draft.id; } draft.unlocks.Add(sUnlockedSequence.ResultItem.Key); _builder.Db.AddReference(draft, "item", sUnlockedSequence.ResultItem.Key, false); _builder.Db.AddReference(unlockedItem, "item", (string)draft.id, false); } } // Special category for the drafts. dynamic category = new JObject(); category.id = -2; category.name = "Company Drafts"; _builder.Db.ItemCategories.Add(category); }
// , decimal weight, string units, string meal public void AddMeal(int productId, int weight, string meal, decimal userWeight, decimal userHeight, int userAge, string userSex) { var ingredient = DownloadIngredient(); var addingMeal = db.Products.Where(k => k.ProductId == productId).SingleOrDefault(); var result = 0.0; if (userSex.Equals("Male")) { result = 66.47 + 13.75 * (double)userWeight + 5.033 * (double)userHeight - 6.75 * userAge + 400; } else { result = 655.09 + 9.56 * (double)userWeight + 1.84 * (double)userHeight - 4.67 * userAge + 400; } if (addingMeal != null) { var newMeal = new IngredientModel() { Model = addingMeal, Weight = weight, Meal = meal, RemaindingCalories = (decimal)result, RemaindingCarbs = (decimal)(0.5 * result), RemaindingProtein = (decimal)(0.2 * result), RemaindingFat = (decimal)(0.3 * result) }; ingredient.Add(newMeal); } session.Set(Consts.MealKey, ingredient); }
public void Update(IngredientModel ingredientModel) { var Ingredient = db.Ingredients.Find(ingredientModel.IngredientId); Ingredient.IngredientId = ingredientModel.IngredientId; Ingredient.Name = ingredientModel.Name; Ingredient.Category = ingredientModel.Category; //Ingredient.Type = ingredientModel.Type; Ingredient.OperatorId = ingredientModel.OperatorId; Ingredient.OperatorLocationId = ingredientModel.OperatorLocationId; Ingredient.CommercialIngredientId = ingredientModel.CommercialIngredientId; Ingredient.ProductionTimeHours = ingredientModel.ProductionTimeHours; Ingredient.ProductionTimeDays = ingredientModel.ProductionTimeDays; Ingredient.ProductionTimeMonths = ingredientModel.ProductionTimeMonths; Ingredient.PerishabilityIndexHours = ingredientModel.PerishabilityIndexHours; Ingredient.PerishabilityIndexDays = ingredientModel.PerishabilityIndexDays; Ingredient.PerishabilityIndexMonths = ingredientModel.PerishabilityIndexMonths; Ingredient.StorageCapacityInLiquid = ingredientModel.StorageCapacityInLiquid; Ingredient.StorageCapacityInVolume = ingredientModel.StorageCapacityInVolume; Ingredient.StorageUsedCapacityLiquid = ingredientModel.StorageUsedCapacityLiquid; Ingredient.StorageUsedCapacityVolume = ingredientModel.StorageUsedCapacityVolume; Ingredient.CurrentPrice = ingredientModel.CurrentPrice; Ingredient.LastCost = ingredientModel.LastCost; Ingredient.date_creation = ingredientModel.date_creation; Ingredient.created_by = ingredientModel.created_by; Ingredient.modified_by = ingredientModel.modified_by; Ingredient.date_modified = ingredientModel.date_modified; db.Ingredients.Add(Ingredient); db.Entry(Ingredient).State = EntityState.Modified; db.SaveChanges(); }
public IngredientViewModels DisplayResult(IngredientModel IngMod, int limit = 4) { IngredientViewModels model = new IngredientViewModels() { ListIng = db.Ingredients.OrderBy(c => c.calories).ToList() }; if (IngMod.Category != String.Empty) { model.ListIng.RemoveAll(m => !m.category.ToLower().Contains(IngMod.Category.ToLower())); } if (IngMod.Name != String.Empty) { model.ListIng.RemoveAll(m => !m.name.ToLower().Contains(IngMod.Name.ToLower())); } if (IngMod.Min >= 0 && IngMod.Max != 0) { if (IngMod.Min < IngMod.Max) { model.ListIng.RemoveAll(m => m.calories >= IngMod.Max); model.ListIng.RemoveAll(m => m.calories <= IngMod.Min); } else { model = new IngredientViewModels(); } } if (model.ListIng != null) { model.Result = new List <DisplayedIngredients>(); foreach (var item in model.ListIng) { int lvlCal = 0; if (model.ListIng.Count > 1) { lvlCal = ((item.calories) * 100) / (db.Ingredients.Where(c => c.category == item.category).Max(c => c.calories)); } else { lvlCal = 100; } model.Result.Add(new DisplayedIngredients { level = lvlCal, ingredient = item, SimIngredient = db.Ingredients.Where(c => c.category == item.category && c.id != item.id).OrderBy(c => c.calories).Take(limit - 1).ToList() }); } } return(model); }
public ActionResult DeleteConfirmed(int id) { IngredientModel ingredientModel = db.IngredientModels.Find(id); db.IngredientModels.Remove(ingredientModel); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Create() { IngredientModel model = new IngredientModel(); model.ReceivingQty = 1; model.GetFillData(CurrentUser.ListOrganizationId); return(View(model)); }
public async Task <Guid> AddIngredient([FromBody] IngredientModel ingredient) { await _validator.ValidateAndThrowAsync(ingredient); var mIngredient = Mapper.Map <IngredientModel, Ingredient>(ingredient); return(await _repository.Create(mIngredient)); }
public IHttpActionResult CreateIngredient(IngredientModel ingredientModel) { var ingredient = Mapper.Map<Ingredient>(ingredientModel); var ingredientDb = _ingredientService.Add(ingredient); return CreatedAtRoute("GetIngredientById", new {id = ingredient.Id}, Mapper.Map<IngredientModel>(ingredientDb)); }
public ActionResult Create(IngredientModel ingredientmodel) { if (ModelState.IsValid) { DataContext.Ingredients.Add(ingredientmodel); DataContext.SaveChanges(); return RedirectToAction("Index"); } ViewBag.DosageID = this.OrderedDosageSelectList(ingredientmodel.DosageID);//new SelectList(this.OrderedDosageList(), "DosageID", "Display", ingredientmodel.DosageID); return View(ingredientmodel); }
public void Post_ShouldReturnStatusCodeCreated() { var ingredientRequest = new RestRequest("Ingredient", Method.POST); var ingredient = new IngredientModel { Name = "ingredient1", Price = 123 }; ingredientRequest.AddJsonBody(ingredient); var ingredientResponse = Client.Execute(ingredientRequest); Assert.That(ingredientResponse, Is.Not.Null); Assert.That(ingredientResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var returnedIngredientModel = _jsonDeserializer.Deserialize<IngredientModel>(ingredientResponse); var pizzaRequest = new RestRequest("Pizza", Method.POST); var pizza = new PizzaModel { Name = "pizza1", Price = 123, Toppings = new List<IngredientModel> { returnedIngredientModel } }; pizzaRequest.AddJsonBody(pizza); var pizzaResponse = Client.Execute(pizzaRequest); Assert.That(pizzaResponse, Is.Not.Null); Assert.That(pizzaResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var returnedPizzaModel = _jsonDeserializer.Deserialize<PizzaModel>(pizzaResponse); var request = new RestRequest(ResourceName, Method.POST); var order = new OrderModel { CreationDate = DateTimeOffset.Now, Price = 123, Address = "address", Pizzas = new List<PizzaModel> { returnedPizzaModel} }; request.AddJsonBody(order); var response = Client.Execute(request); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created)); }
public void Get_ShouldReturnStatusCodeOk() { var postRequest = new RestRequest(ResourceName, Method.POST); var expectedIngredient = new IngredientModel { Name = "ingredient1", Price = 123 }; postRequest.AddJsonBody(expectedIngredient); var postResponse = Client.Execute(postRequest); Assert.That(postResponse, Is.Not.Null); Assert.That(postResponse.StatusCode, Is.EqualTo(HttpStatusCode.Created)); var getRequest = new RestRequest(ResourceName, Method.GET); var getResponse = Client.Execute(getRequest); Assert.That(getResponse, Is.Not.Null); Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK)); var ingredients = _jsonDeserializer.Deserialize<List<IngredientModel>>(getResponse); CollectionAssert.IsNotEmpty(ingredients); }
public void Post_ShouldReturnStatusCodeCreated() { var request = new RestRequest(ResourceName, Method.POST); var ingredient = new IngredientModel { Name = "ingredient1", Price = 123 }; request.AddJsonBody(ingredient); var response = Client.Execute(request); Assert.That(response, Is.Not.Null); Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created)); }
public ActionResult Edit(IngredientModel ingredientmodel) { if (ModelState.IsValid) { DataContext.Entry(ingredientmodel).State = EntityState.Modified; DataContext.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Dosages = new SelectList(this.OrderedDosageList(), "DosageID", "Display", ingredientmodel.DosageID); return View(ingredientmodel); }