public void deselectIngredient(ingredient ing)
 {
     if (selectedIngredients.Remove(ing))
         ingredientsChanged = true;
     ing.checkMark.SetActive(false);
 }
Exemplo n.º 2
0
        public ActionResult CreateINGREDIENT(mycook.Models.ingredient usermodel)
        {
            mycookEntities me = new mycookEntities();



            var ingDetails = me.ingredients.Where(x => x.name_ingredient == usermodel.name_ingredient).FirstOrDefault();

            if (ingDetails == null)
            {
                ingredient newING = new ingredient();
                newING.name_ingredient = usermodel.name_ingredient;
                newING.status          = "ON";

                me.ingredients.Add(newING);
                me.SaveChanges();

                TempData["msg"] = "Record Saved Successfully.";
                // ViewBag.DataExists = true;
                // ViewBag.Javascript = "<script language='javascript' type='text/javascript'>alert('Data Already Exists');</script>";

                return(RedirectToAction("Index"));
            }
            else
            {
                usermodel.ErrorMessage = "Error";
            }


            return(View("Create"));
        }
Exemplo n.º 3
0
        public IngredientView()
        {
            Button back = new Button
            {
                Text = "Back",
                HorizontalOptions = LayoutOptions.Start,
                VerticalOptions   = LayoutOptions.Start
            };

            back.Clicked += (sender, e) =>
            {
                Navigation.PopModalAsync();
            };
            var    client = new HttpClient();
            string url    = "http://api.kitchen.support/pantry?offset=0&limit=30&api_token=";
            string token  = DependencyService.Get <localDataInterface>().load("token");

            url += token;
            var response = client.GetStringAsync(new Uri(url));
            var ye       = response.Result;
            List <ingredient> ingredients = parseIngredients(response.Result);
            Label             header      = new Label
            {
                Text = "Your Ingredients",
                Font = Font.BoldSystemFontOfSize(50),
                HorizontalOptions = LayoutOptions.Center
            };

            listview = new ListView
            {
                RowHeight = 30
            };

            listview.ItemsSource = ingredients;

            listview.ItemTemplate = new DataTemplate(typeof(TextCell));
            listview.ItemTemplate.SetBinding(TextCell.TextProperty, ".term");
            Button button = new Button();

            button.Text = "Add Ingredient";



            button.Clicked += (sender, e) =>
            {
                ingredient newIngredient = new ingredient();
                Navigation.PushModalAsync(new AddIngredient(newIngredient));
            };
            // Build the page.
            this.Content = new StackLayout
            {
                Children =
                {
                    back,
                    header,
                    listview,
                    button
                }
            };
        }
Exemplo n.º 4
0
            public void addingredient(ingredient x)
            {
                Double tprice = Double.Parse(this.price) + Double.Parse(x.price);

                this.price = tprice.ToString();
                this.add.Add(x);
            }
Exemplo n.º 5
0
            public void removeingredient(ingredient x)
            {
                bool found = false;

                foreach (ingredient i in this.ingredients)
                {
                    if (i.Equals(x))
                    {
                        this.add.Remove(i);
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    Double tprice = Double.Parse(this.price) - Double.Parse(x.price);
                    this.price = tprice.ToString();
                    foreach (ingredient i in this.add)
                    {
                        if (i.Equals(x))
                        {
                            this.add.Remove(i);
                            break;
                        }
                    }
                }
            }
Exemplo n.º 6
0
        public IHttpActionResult Putingredient(decimal id, ingredient ingredient)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != ingredient.id_ingredient)
            {
                return(BadRequest());
            }

            db.Entry(ingredient).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ingredientExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        //update ingredient in database
        public ingredientDto PutIngredient(ingredientDto IngredientDto, ref string f)
        {
            using (HealthyMenuEntities db = new HealthyMenuEntities())
            {
                try
                {
                    ingredient Ingredient = db.ingredients.FirstOrDefault(x => x.id == IngredientDto.id);
                    if (Ingredient == null)
                    {
                        f = "לא קיים";
                        return(null);
                    }

                    Ingredient.id                    = IngredientDto.id;
                    Ingredient.CDescription          = IngredientDto.CDescription;
                    Ingredient.RecommendedDoseMale   = IngredientDto.RecommendedDoseMale;
                    Ingredient.RecommendedDoseFemale = IngredientDto.RecommendedDoseFemale;
                    Ingredient.UnitCode              = IngredientDto.UnitCode;
                    return(Convertion.IngredientConvertion.convert(Ingredient));
                }
                catch
                {
                    return(null);
                }
            }
        }
 public void addIngredient(ingredient ingred)
 {
     ingredients.Add(ingred);
     newButton(ingred);
     saveIngredients();
     selectIngredient(ingred);
 }
Exemplo n.º 9
0
        public ActionResult testeEdit([Bind(Include = "id_user,username,password,role, subscription")] ingredient i, mycook.Models.ingredient usermodel)
        {
            mycookEntities me = new mycookEntities();



            var ingDetails = me.ingredients.Where(x => x.id_ingredient == usermodel.id_ingredient).FirstOrDefault();

            if (ingDetails != null)
            {
                ingredient editado = ingDetails;
                editado.name_ingredient = usermodel.name_ingredient;
                editado.status          = "ON";
                usermodel.status        = "ON";

                i.status = "ON";

                me.SaveChanges();
                db.Entry(i).State = EntityState.Modified;
                //db.SaveChanges();
                // return RedirectToAction("Index");
                TempData["msg"] = "Record Saved Successfully.";
                // ViewBag.DataExists = true;
                // ViewBag.Javascript = "<script language='javascript' type='text/javascript'>alert('Data Already Exists');</script>";

                return(RedirectToAction("Index"));
            }
            else
            {
                usermodel.ErrorMessage = "Error";
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 10
0
        public ActionResult Step3(mycook.Models.recipe usermode, FormCollection fc)
        {
            mycookEntities me = new mycookEntities();


            string test  = fc["txttest"];
            string test2 = fc["txttestnumber"];

            List <ingredient> ingredients = new List <ingredient>();

            //foreach(String s in fc)
            //{

            //    ingredient i = new ingredient();
            //    i.name_ingredient = fc[s];
            //    ingredients.Add(i);

            //}

            List <String> names = test.Split(',').ToList();

            if (names.Count == 1 && names[0] == "")
            {
                ViewData["Success"] = "Data was saved successfully.";
                return(View("CreateRecipeStep2"));
            }
            else
            {
                List <int> quantities = test2.Split(',').Select(int.Parse).ToList();
                List <ingredients_recipe> all_ingredients = new List <ingredients_recipe>();

                int contador = 0;
                foreach (String s in names)
                {
                    ingredient         i  = new ingredient();
                    ingredients_recipe ir = new ingredients_recipe();

                    i.name_ingredient       = s;
                    ir.ingredient           = i;
                    ir.quantity_per_portion = quantities[contador];
                    ingredients.Add(i);
                    me.ingredients.Add(i);


                    all_ingredients.Add(ir);

                    contador++;
                }

                me.SaveChanges();



                int x = ingredients.Count();

                Session["all_ingridients"] = all_ingredients;
                return(View("CreateRecipeStep3"));
            }
        }
Exemplo n.º 11
0
        public ActionResult DeleteConfirmed(decimal id)
        {
            ingredient ingredient = db.ingredients.Find(id);

            db.ingredients.Remove(ingredient);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public void selectIngredient(ingredient ing)
 {
     if (!selectedIngredients.Contains(ing))
     {
         selectedIngredients.Add(ing);
         ing.checkMark.SetActive(true);
         ingredientsChanged = true;
     }
 }
Exemplo n.º 13
0
    public void add_ingred(basic_resource ingred, int n)
    {
        ingredient tmp;

        tmp     = new ingredient();
        tmp.rss = ingred;
        tmp.num = n;
        ingreds.Add(tmp);
    }
Exemplo n.º 14
0
        public Ingredients()
        {
            Label header = new Label
            {
                Text = "Your Ingredients",
                Font = Font.BoldSystemFontOfSize(50),
                HorizontalOptions = LayoutOptions.Center
            };
            listview = new ListView
            {
                RowHeight = 50
            };

            ingredients = new List<ingredient>();
            ingredients.Add(new ingredient { name = "Orange", quantity = 1, unit = " " });
            ingredients.Add(new ingredient { name = "Beef", quantity = 2, unit = "Pounds" });
            ingredients.Add(new ingredient { name = "Milk", quantity = 10, unit = "Cups" });
            listview.ItemsSource = ingredients;

            listview.ItemTemplate = new DataTemplate(typeof(TextCell));
            listview.ItemTemplate.SetBinding(TextCell.TextProperty, ".name");
            listview.ItemTemplate.SetBinding(TextCell.DetailProperty, ".unitAndQuantity");
            Button button = new Button();
            button.Text = "Add Ingredient";

            button.Clicked += async (sender, e) =>
            {
                ingredient newIngredient = new ingredient();
                await Navigation.PushModalAsync(new AddIngredient(newIngredient));
            };

            // Build the page.

            listview.ItemSelected += async (sender, e) => {

                //UpdateIngredient u = new UpdateIngredient(newAmount, newUnit);
                if (e.SelectedItem == null)
                    return;
                listview.SelectedItem = null; // deselect row
                ing = (ingredient)e.SelectedItem;
                await Navigation.PushModalAsync(new UpdateIngredient());

                //((ingredient)e.SelectedItem).quantity = Ingredients.newAmount;
                //((ingredient)e.SelectedItem).unit = Ingredients.newUnit;

            };
            this.Content = new StackLayout
            {
                Children =
                {
                    header,
                    listview,
                    button
                }
            };
        }
Exemplo n.º 15
0
 public ActionResult Edit([Bind(Include = "id_ingredient,name_ingredient")] ingredient ingredient)
 {
     if (ModelState.IsValid)
     {
         db.Entry(ingredient).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(ingredient));
 }
Exemplo n.º 16
0
        public IngredientView()
        {
            Button back = new Button
            {
                Text = "Back",
                HorizontalOptions = LayoutOptions.Start,
                VerticalOptions = LayoutOptions.Start
            };
            back.Clicked += (sender, e) =>
            {
                Navigation.PopModalAsync();
            };
            var client = new HttpClient();
            string url = "http://api.kitchen.support/pantry?offset=0&limit=30&api_token=";
            string token = DependencyService.Get<localDataInterface>().load("token");
            url += token;
            var response = client.GetStringAsync(new Uri(url));
            var ye = response.Result;
            List<ingredient> ingredients = parseIngredients(response.Result);
            Label header = new Label
            {
                Text = "Your Ingredients",
                Font = Font.BoldSystemFontOfSize(50),
                HorizontalOptions = LayoutOptions.Center
            };
            listview = new ListView
            {
                RowHeight = 30
            };

            listview.ItemsSource = ingredients;

            listview.ItemTemplate = new DataTemplate(typeof(TextCell));
            listview.ItemTemplate.SetBinding(TextCell.TextProperty, ".term");
            Button button = new Button();
            button.Text = "Add Ingredient";

            button.Clicked += (sender, e) =>
            {
                ingredient newIngredient = new ingredient();
                Navigation.PushModalAsync(new AddIngredient(newIngredient));

            };
            // Build the page.
            this.Content = new StackLayout
            {
                Children =
                {
                    back,
                    header,
                    listview,
                    button
                }
            };
        }
Exemplo n.º 17
0
        public IHttpActionResult Getingredient(decimal id)
        {
            ingredient ingredient = db.ingredients.Find(id);

            if (ingredient == null)
            {
                return(NotFound());
            }

            return(Ok(ingredient));
        }
        //convert one ingredient to ingredientDto
        public static ingredientDto convert(ingredient Ingredient)
        {
            ingredientDto NewIngredient = new ingredientDto();

            NewIngredient.id                    = Ingredient.id;
            NewIngredient.CDescription          = Ingredient.CDescription;
            NewIngredient.RecommendedDoseMale   = Ingredient.RecommendedDoseMale;
            NewIngredient.RecommendedDoseFemale = Ingredient.RecommendedDoseFemale;
            NewIngredient.UnitCode              = Ingredient.UnitCode;
            return(NewIngredient);
        }
Exemplo n.º 19
0
        public ActionResult Create([Bind(Include = "id_ingredient,name_ingredient")] ingredient ingredient)
        {
            if (ModelState.IsValid)
            {
                db.ingredients.Add(ingredient);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(ingredient));
        }
Exemplo n.º 20
0
            public AddIngredient(ingredient i)
            {
                Label header = new Label
                {
                    Text = "Add Ingredient",
                    Font = Font.BoldSystemFontOfSize(50),
                    HorizontalOptions = LayoutOptions.Center
                };
                Entry e1 = new Entry
                {
                    Placeholder = "Enter New Ingredient"
                };

                Entry e2 = new Entry
                {
                    Placeholder = "Enter New Amount",
                    Keyboard    = Keyboard.Numeric
                };
                Entry e3 = new Entry
                {
                    Placeholder = "Enter New Unit"
                };
                Button button = new Button
                {
                    Text            = "Enter",
                    TextColor       = Color.White,
                    BackgroundColor = Color.FromHex("77D065")
                };

                this.Content = new StackLayout
                {
                    Spacing         = 20,
                    Padding         = 50,
                    VerticalOptions = LayoutOptions.Center,
                    Children        =
                    {
                        header,
                        e1,
                        e2,
                        e3,
                        button
                    }
                };
                button.Clicked += async(sender, e) =>
                {
                    i.name     = e1.Text;
                    i.quantity = Int32.Parse(e2.Text);;
                    i.unit     = e3.Text;
                    ingredients.Add(i);
                    listview.ItemsSource = null;
                    listview.ItemsSource = ingredients;
                    await Navigation.PopModalAsync();
                };
            }
Exemplo n.º 21
0
        private int isExist(ingredient ing, List <IngredientDetail> list)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Ingredient.id.Equals(ing.id))
                {
                    return(i);
                }
            }

            return(-1);
        }
Exemplo n.º 22
0
        public IHttpActionResult Postingredient(ingredient ingredient)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.ingredients.Add(ingredient);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = ingredient.id_ingredient }, ingredient));
        }
Exemplo n.º 23
0
    private void saveIngridients(int recipeId, int totalIngridients)
    {
        RecipeDatabaseEntities rdbEnty = new RecipeDatabaseEntities();
        string name = ""; int Q = 0; string unit = ""; string qty = "";


        for (int i = 1; i <= totalIngridients; i++)
        {
            name = "";
            qty  = "";
            unit = "";
            Q    = 0;


            if (Request.Form["txtIngridients" + i] != null && !string.IsNullOrWhiteSpace(Request.Form["txtIngridients" + i]))
            {
                name = Convert.ToString(Request.Form["txtIngridients" + i]);
            }

            if (Request.Form["txtQuantity" + i] != null && !string.IsNullOrWhiteSpace(Request.Form["txtQuantity" + i]))
            {
                qty = Convert.ToString(Request.Form["txtQuantity" + i]);

                int.TryParse(qty, out Q);
            }

            if (Request.Form["ddlUnit" + i] != null && !string.IsNullOrWhiteSpace(Request.Form["ddlUnit" + i]))
            {
                unit = Convert.ToString(Request.Form["ddlUnit" + i]);
            }

            if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(unit) && Q > 0)
            {
                ingredient iObj = new ingredient();
                iObj.name     = name;
                iObj.MemberId = MemberId;
                rdbEnty.ingredients.AddObject(iObj);
                rdbEnty.SaveChanges();
                int LastInsertedIngredientId = iObj.id;

                recipe_ingredients riObj = new recipe_ingredients();
                riObj.ingredient_id = LastInsertedIngredientId;
                riObj.recipe_id     = recipeId;
                riObj.name          = name;
                riObj.unit          = unit;
                riObj.quantity      = Q;
                riObj.MemberId      = MemberId;
                rdbEnty.recipe_ingredients.AddObject(riObj);
                rdbEnty.SaveChanges();
            }
        }
    }
Exemplo n.º 24
0
        public void GetOrdersTest_AreEqual()
        {
            order order = new order()
            {
                orderid        = 1,
                name           = "Leszek",
                phonenumber    = "888-888-8888",
                pickupdatetime = DateTime.Now,
                startdatetime  = DateTime.Now,
                enddatetime    = DateTime.Now,
                statustypeid   = 1
            };

            List <order> orders = new List <order>();

            orders.Add(order);

            orderingredient orderIngredient = new orderingredient()
            {
                orderid      = 1,
                ingredientid = 1,
                quantity     = 1
            };

            List <orderingredient> orderIngredients = new List <orderingredient>();

            orderIngredients.Add(orderIngredient);

            ingredient cheese = new ingredient()
            {
                ingredientid = 1,
                name         = "Cheese",
                price        = 2
            };

            List <ingredient> ingredients = new List <ingredient>();

            ingredients.Add(cheese);

            Mock <IOrderRepository> mockRepository = new Mock <IOrderRepository>();

            mockRepository.Setup(s => s.GetOrders()).Returns(() => orders);
            mockRepository.Setup(s => s.GetOrderIngredients(It.IsAny <int>())).Returns(() => orderIngredients);
            mockRepository.Setup(s => s.GetIngredients()).Returns(() => ingredients);

            OrderService orderService = new OrderService(mockRepository.Object);

            List <CustomerOrderResult> resultOrders = orderService.GetOrders();

            Assert.AreEqual(1, resultOrders.FirstOrDefault().orderid);
            Assert.AreEqual("Cheese", resultOrders.FirstOrDefault().orderingredientresults.FirstOrDefault().name);
        }
Exemplo n.º 25
0
 public override void bonked()
 {
    if(redCount+blueCount+greenCount <= -15)
     {
         Debug.Log("TEAPOTTTTTTTTTTTT");
     } 
    else if (cookwareValue != ingredient.RGB) //If we've actually got cookware in the cauldron
     {
         Debug.Log(this.gameObject.name + "bonked!");
         recipeCheck(cookwareValue);
         cookwareValue = ingredient.RGB;
     }
 }
Exemplo n.º 26
0
        // GET: ingredients/Delete/5
        public ActionResult Delete(decimal id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ingredient ingredient = db.ingredients.Find(id);

            if (ingredient == null)
            {
                return(HttpNotFound());
            }
            return(View(ingredient));
        }
Exemplo n.º 27
0
        public IHttpActionResult Deleteingredient(decimal id)
        {
            ingredient ingredient = db.ingredients.Find(id);

            if (ingredient == null)
            {
                return(NotFound());
            }

            db.ingredients.Remove(ingredient);
            db.SaveChanges();

            return(Ok(ingredient));
        }
 //remove ingredient to database
 public ingredientDto RemoveIngredient(ingredientDto IngredientDto)
 {
     using (HealthyMenuEntities db = new HealthyMenuEntities())
     {
         try
         {
             ingredient Ingredient = db.ingredients.Remove(Convertion.IngredientConvertion.convert(IngredientDto));
             db.SaveChanges();
             return(Convertion.IngredientConvertion.convert(Ingredient));
         }
         catch
         {
             return(null);
         }
     }
 }
Exemplo n.º 29
0
 public string InsertIngredient(ingredient item)
 {
     try
     {
         //Create database connection
         COMP229S17S2Entities dbConnection = new COMP229S17S2Entities();
         //Add item of ingredients to database
         dbConnection.ingredients.Add(item);
         dbConnection.SaveChanges();
         return("Item " + item.Name + " was saved");
     }
     catch (Exception e)
     {
         return(e.ToString());
     }
 }
Exemplo n.º 30
0
    //void OnTriggerEnter(Collider other)
    void OnTriggerStay(Collider other)
    { 
        var obj = other.gameObject;
        var eatMe = obj.GetComponent<Edible>();
        if (!playerGrabbing(other.gameObject) && eatMe && !isShrink)
        {
            redCount += eatMe.redValue;     //Consume the RGB values
            greenCount += eatMe.greenValue;
            blueCount += eatMe.blueValue;
            if (eatMe.id != ingredient.RGB) //Keep the value of the last cookware item fed to the cauldron
            {
                cookwareValue = eatMe.id;
            }          
            StartCoroutine(shrink(shrinkTime, eatMe));
			GetComponent<AudioSource> ().PlayOneShot (sploosh);
        }
    }
Exemplo n.º 31
0
        private void btnAddOrUpdate_Click(object sender, EventArgs e)
        {
            if(row != null && btnAddOrUpdate.Text.Equals("Update"))
            {
                row.Cells[3].Value = cmbCategory.Text;
                row.Cells[4].Value = cmbStatus.Text;
                row.Cells[1].Value = txtIngredient.Text.ToString();
                row.Cells[2].Value = txtMoisture.Value;

                try
                {
                    ctx.SaveChanges();
                }
                catch(Exception ex)
                {
                    ErrorLog log = new ErrorLog();
                    log.createLogFile(ex);

                    MessageBox.Show("Could Not Update");
                }
            }

            if(btnAddOrUpdate.Text.Equals("Add"))
            {
                ingredient ing = new ingredient();
                ing.category = cmbCategory.Text;
                ing.status= cmbStatus.Text;
                ing.ingredient1 = txtIngredient.Text.ToString();
                ing.moisture = txtMoisture.Value;

                ctx.ingredients.Add(ing);
                try
                {
                    ctx.SaveChanges();
                    clearToolStripMenuItem_Click(null, null);
                    populateDgvIngredient();
                }
                catch (Exception ex)
                {
                    ErrorLog log = new ErrorLog();
                    log.createLogFile(ex);

                    MessageBox.Show("Could Not Update");
                }
            }
        }
Exemplo n.º 32
0
        public ActionResult Edit(int id, ingredient ingredient)
        {
            try
            {
                using (OrderSystemEntities2 db = new OrderSystemEntities2())
                {
                    db.Entry(ingredient).State = EntityState.Modified;
                    db.SaveChanges();

                    return(RedirectToAction("Index"));
                }
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 33
0
        public ActionResult Create(ingredient ingredient)
        {
            try
            {
                using (OrderSystemEntities2 db = new OrderSystemEntities2())
                {
                    db.ingredients.Add(ingredient);
                    db.SaveChanges();
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
        productingredient GetOrCreateIngredientFromLine(DataRow lineInformation)
        {
            string productName      = (string)lineInformation.ItemArray[2];
            string ingredientName   = (string)lineInformation.ItemArray[10];
            int    ingredientAmount = Convert.ToInt32(lineInformation.ItemArray[9]);

            product    product    = database.products.SingleOrDefault(s => s.name == productName);
            ingredient ingredient = database.ingredients.SingleOrDefault(s => s.name == ingredientName);

            if (product == null)
            {
                product = GetMappedProduct(productName);
                if (product == null)
                {
                    product = this.createPizzaProduct(lineInformation);
                }
            }

            if (ingredient == null)
            {
                ingredient = GetMappedIngredient(ingredientName);
                if (ingredient == null)
                {
                    Logger.Instance.LogError(filePath, String.Format("Could not find ingredient named {0} to add to product {1}", ingredientName, productName));
                    CreateMappingForIngredient(ingredientName);

                    return(null);
                }
            }

            productingredient productingredient = database.productingredients.SingleOrDefault(pi => pi.product.name == product.name && pi.ingredient.name == ingredient.name);

            if (productingredient == null)
            {
                productingredient = new productingredient();

                productingredient.product = product;
                productingredient.amount  = ingredientAmount;

                productingredient.ingredient = ingredient;
            }

            return(productingredient);
        }
 //get one ingredients by id from database
 public ingredientDto GetIngredient(int id)
 {
     using (HealthyMenuEntities db = new HealthyMenuEntities())
     {
         try
         {
             ingredient Ingredient = db.ingredients.FirstOrDefault(x => x.id == id);
             if (Ingredient == null)
             {
                 return(null);
             }
             return(Convertion.IngredientConvertion.convert(Ingredient));
         }
         catch
         {
             return(null);
         }
     }
 }
Exemplo n.º 36
0
        public void GetIngredientsTest_AreEqual()
        {
            ingredient cheese = new ingredient()
            {
                ingredientid = 1,
                name         = "Cheese",
                price        = 2
            };

            List <ingredient> ingredients = new List <ingredient>();

            ingredients.Add(cheese);

            Mock <IOrderRepository> mockRepository = new Mock <IOrderRepository>();

            mockRepository.Setup(s => s.GetIngredients()).Returns(() => ingredients);

            OrderService orderService = new OrderService(mockRepository.Object);

            List <ingredient> resultIngredients = orderService.GetIngredients();

            Assert.AreEqual(ingredients, resultIngredients);
        }
Exemplo n.º 37
0
    private void addMoreIngridients(int recipeId)
    {
        RecipeDatabaseEntities rdbEnty = new RecipeDatabaseEntities();
        int    ind = int.Parse(Session["ind"].ToString());
        string name = ""; int Q = 0; string unit = "";

        for (int i = 1; i < ind; i++)
        {
            if (Panel1.Controls[i] is TextBox && Panel1.Controls[i].ID.EndsWith("Q"))
            {
                Q = int.Parse(((TextBox)(Panel1.Controls[ind])).Text);
            }
            else if (Panel1.Controls[i] is TextBox)
            {
                name = ((TextBox)(Panel1.Controls[i])).Text;
            }
            else if (Panel1.Controls[i] is DropDownList)
            {
                unit = ((DropDownList)Panel1.Controls[i]).Text;
                ingredient iObj = new ingredient();
                iObj.name     = name;
                iObj.MemberId = MemberId;
                rdbEnty.ingredients.AddObject(iObj);
                rdbEnty.SaveChanges();
                int LastInsertedIngredientId = iObj.id;

                recipe_ingredients riObj = new recipe_ingredients();
                riObj.ingredient_id = LastInsertedIngredientId;
                riObj.recipe_id     = recipeId;
                riObj.unit          = unit;
                riObj.quantity      = Q;
                riObj.MemberId      = MemberId;
                rdbEnty.recipe_ingredients.AddObject(riObj);
                rdbEnty.SaveChanges();
            }
        }
    }
Exemplo n.º 38
0
            public AddIngredient(ingredient i)
            {
                Label header = new Label
                {
                    Text = "Add Ingredient",
                    Font = Font.BoldSystemFontOfSize(50),
                    HorizontalOptions = LayoutOptions.Center

                };
                Entry e1 = new Entry
                {
                    Placeholder = "Enter New Ingredient"
                };

                Entry e2 = new Entry
                {
                    Placeholder = "Enter New Amount",
                    Keyboard = Keyboard.Numeric

                };
                Entry e3 = new Entry
                {
                    Placeholder = "Enter New Unit"
                };
                Button button = new Button
                {
                    Text = "Enter",
                    TextColor = Color.White,
                    BackgroundColor = Color.FromHex("77D065")
                };
                this.Content = new StackLayout
                {
                    Spacing = 20,
                    Padding = 50,
                    VerticalOptions = LayoutOptions.Center,
                    Children =
                {
                    header,
                    e1,
                    e2,
                    e3,
                    button
                }
                };
                button.Clicked += async (sender, e) =>
                {
                    i.name = e1.Text;
                    i.quantity = Int32.Parse(e2.Text); ;
                    i.unit = e3.Text;
                    ingredients.Add(i);
                    listview.ItemsSource = null;
                    listview.ItemsSource = ingredients;
                    await Navigation.PopModalAsync();
                };
            }
Exemplo n.º 39
0
            public AddIngredient(ingredient i)
            {
                Label header = new Label
                {
                    Text = "Add Ingredient",
                    Font = Font.BoldSystemFontOfSize(50),
                    HorizontalOptions = LayoutOptions.Center

                };
                Entry e1 = new Entry
                {
                    Placeholder = "Enter New Ingredient"
                };

                Entry e2 = new Entry
                {
                    Placeholder = "Enter New Amount",
                    Keyboard = Keyboard.Numeric

                };
                Entry e3 = new Entry
                {
                    Placeholder = "Enter New Unit"
                };
                Button button = new Button
                {
                    Text = "Enter",
                    TextColor = Color.White,
                    BackgroundColor = Color.FromHex("77D065")
                };
                Button button2 = new Button
                {
                    Text = "Scan Ingredient Barcode",
                    TextColor = Color.White,
                    BackgroundColor = Color.FromHex("77D065")
                };
                this.Content = new StackLayout
                {
                    Spacing = 20,
                    Padding = 50,
                    VerticalOptions = LayoutOptions.Center,
                    Children =
                {
                    header,
                    e1,
                    e2,
                    e3,
                    button,
                    button2
                }
                };
                button.Clicked += async (sender, e) =>
                {
                    i.name = e1.Text;
                    i.quantity = Int32.Parse(e2.Text); ;
                    i.unit = e3.Text;
                    ingredients.Add(i);
                    listview.ItemsSource = null;
                    listview.ItemsSource = ingredients;
                    await Navigation.PopModalAsync();
                };
                button2.Clicked += async (sender, e) =>
                {
                    var data1 = await DependencyService.Get<IScanner> ().Scan ();

                    var client = new System.Net.Http.HttpClient ();
                    string url = "http://api.walmartlabs.com/v1/items?apiKey=h5yjnkgcrmtzn3rjaduapusv&upc="+data1;
                    var response = client.GetAsync(new Uri(url));
                    if (response.Result.StatusCode.ToString() == "OK") {
                        var message = response.Result.Content.ReadAsStringAsync().Result;
                        //var result = JsonConvert.DeserializeObject<Items>(message);
                        //List<Item> information = result.data;
                        //var item = information.ToList().First();
                        //var name = item.name;
                        string word = "";
                        string name = "";
                        for(int location = 0 ; location < message.Length - 4 ; location++){
                            word = (message.Substring(location,4));
                            if(word == "name"){
                                int j = location +7;
                                char c = message[j];
                                while(c != '"'){
                                    name += message[j];
                                    j++;
                                    c = message[j];
                                }
                                break;
                            }
                        }
                        await DisplayAlert ("Item Found", name, "OK");
                        //var json = JObject.Parse (message);
                        //var token = json ["name"];
                        //await DisplayAlert ("Scanner", token.ToString(), "OK");
                        //await storeToken(token.ToString());
                        e1.Text = name;
                        //await Navigation.PushModalAsync (new NavigationPage(new HomePage()));
                    }
                    else {
                        await DisplayAlert ("Alert", "Could not find item from UPC code.","OK");
                        await DisplayAlert ("Scanner", data1, "OK");
                        await DisplayAlert ("Response" , response.Result.StatusCode.ToString(), "OK");
                    }

                };
            }
Exemplo n.º 40
0
    /* Testing program
     * General template:
     *      test(boolean function to test, success message, error message)
     */
    public static void runTest()
    {
        e.websiteParsingFunctions = new List<expectedOutcome>();
        e.websiteParsingFunctions.Add(webParseTesting.Instance.foodTester);
        e.websiteParsingFunctions.Add(webParseTesting.Instance.marthaStewartTester);
        e.websiteParsingFunctions.Add(webParseTesting.Instance.foodNetworkTester);
        e.websiteParsingFunctions.Add(webParseTesting.Instance.epicuriousTester);
        e.websiteParsingFunctions.Add(webParseTesting.Instance.delishTester);
        e.websiteParsingFunctions.Add(webParseTesting.Instance.wegmansTester);
        writeMessage("Testing Pantry Button...");
        test(
            delegate{
                return e.pantryButtonTest = testButton(testObjects.e.openPantryButton, delegate
                {
                    return isOpen(testObjects.e.pantryPanel) && isClosed(testObjects.e.homePanel);
                });
            }
        , "Pantry Button opens Pantry", "Pantry button unsuccessful");
        writeMessage("Testing Home Button in Pantry...");
        test(
            delegate
            {
                return e.homeButtonFromPantryTest = testButton(testObjects.e.openHomeButton_FromPantry, delegate
                {
                    return isClosed(testObjects.e.pantryPanel) && isOpen(testObjects.e.homePanel);
                });
            }
        , "Home Button closes Pantry", "Home button from pantry unsuccessful");
        writeMessage("Testing Recipes Button...");
        test(
            delegate
            {
                return e.recipesButtonTest = testButton(testObjects.e.openRecipesButton, delegate
                {
                    return isOpen(testObjects.e.recipesPanel) && isClosed(testObjects.e.homePanel);
                });
            }
        , "Recipes Button opens Recipes", "Recipes button unsuccessful");
        writeMessage("Testing Home Button in Recipes...");
        test(
            delegate
            {
                return e.homeButtonFromRecipesTest = testButton(testObjects.e.openHomeButton_FromRecipes, delegate
                {
                    return isClosed(testObjects.e.recipesPanel) && isOpen(testObjects.e.homePanel);
                });
            }
        , "Home Button closes Recipes", "Home button from Recipes unsuccessful");

        /* Running unit tests */
        writeMessage("Testing Ingredients Manager...");
        ingredient testIngredient = new ingredient("Test Ingredient");
        main.Instance.ingredientsManager.addIngredient(testIngredient);

        foreach (ingredient i in main.Instance.ingredientsManager.ingredients)
        {
            if (i.name == "Test Ingredient")
            {
                e.addIngredientTest = true;
                break;
            }
        }
        // Test has ingredient method to what was found
        if (main.Instance.ingredientsManager.hasIngredient(testIngredient))
        {
            if (e.addIngredientTest)
                writeMessage("Ingredient was added and was successfully found using hasIngredient");
            else
                writeMessage("Ingredient was not added to list but was successfully found using hasIngredient");
        }
        else
        {
            if (e.addIngredientTest)
                writeMessage("Ingredient was added but was not successfully found using hasIngredient");
            else
                writeMessage("Ingredient was not added to list and was not successfully found using hasIngredient");
        }
        // Removing item from defaultly selected ingredient
        main.Instance.ingredientsManager.selectedIngredients.Remove(testIngredient);

        // Test selecting ingredients
        main.Instance.ingredientsManager.selectIngredient(testIngredient);
        if (main.Instance.ingredientsManager.selectedIngredients.Contains(testIngredient))
        {
            writeMessage("Ingredient successfully selected and added to list of selected ingredients");

            // Test deselecting ingredients if selecting ingredients worked
            main.Instance.ingredientsManager.deselectIngredient(testIngredient);
            if (main.Instance.ingredientsManager.selectedIngredients.Remove(testIngredient))
                writeMessage("Ingredient not successfully deselected and not removed from list of selected ingredients");
            else
                writeMessage("Ingredient successfully deselected and removed from list of selected ingredients");
        }
        else
            writeMessage("Ingredient not successfully selected");

        // Test removing ingredient
        e.removeIngredientTest = main.Instance.ingredientsManager.removeIngredient(testIngredient);
        if (e.removeIngredientTest)
            writeMessage("Ingredient successfully removed from ingredients");
        else
            writeMessage("Ingredient was not successfully removed from ingredients");


        runNextWebParsingTests();
	}
Exemplo n.º 41
0
    public void LoadScenery()
    {
        try
        {
            GameObject hider = new GameObject();
            char       dsc   = System.IO.Path.DirectorySeparatorChar;

            using (WWW www = new WWW("file://" + Path + dsc + "assetbundle" + dsc + "mod"))
            {
                if (www.error != null)
                {
                    throw new Exception("Loading had an error:" + www.error);
                }

                AssetBundle bundle = www.assetBundle;
                try
                {
                    XmlDocument doc   = new XmlDocument();
                    string[]    files = System.IO.Directory.GetFiles(Path, "*.xml");
                    doc.Load(files[0]);
                    XmlElement  xelRoot  = doc.DocumentElement;
                    XmlNodeList ModNodes = xelRoot.SelectNodes("/Mod");

                    foreach (XmlNode Mod in ModNodes)
                    {
                        modName        = Mod["ModName"].InnerText;
                        modDiscription = Mod["ModDiscription"].InnerText;
                    }
                    XmlNodeList ObjectNodes = xelRoot.SelectNodes("/Mod/Objects/Object");

                    foreach (XmlNode ParkOBJ in ObjectNodes)
                    {
                        try
                        {
                            ModdedObject MO    = null;
                            GameObject   asset = Instantiate(bundle.LoadAsset(ParkOBJ["OBJName"].InnerText)) as GameObject;
                            asset.name = Identifier + "@" + ParkOBJ["OBJName"].InnerText;
                            switch (ParkOBJ["Type"].InnerText)
                            {
                            case "deco":
                                DecoMod DM = new DecoMod();
                                DM.HeightDelta     = float.Parse(ParkOBJ["heightDelta"].InnerText);
                                DM.GridSubdivision = 1f;
                                DM.SnapCenter      = Convert.ToBoolean(ParkOBJ["snapCenter"].InnerText);
                                DM.category        = ParkOBJ["category"].InnerText;
                                DM.BuildOnGrid     = Convert.ToBoolean(ParkOBJ["grid"].InnerText);
                                DM.gridSubdivision = float.Parse(ParkOBJ["gridSubdivision"].InnerText);
                                MO = DM;
                                break;

                            case "trashbin":
                                MO = new TrashBinMod();
                                break;

                            case "seating":
                                SeatingMod SM = new SeatingMod();
                                SM.hasBackRest = false;
                                MO             = SM;
                                break;

                            case "seatingAuto":
                                SeatingAutoMod SMA = new SeatingAutoMod();
                                SMA.hasBackRest = false;
                                SMA.seatCount   = 2;
                                MO = SMA;
                                break;

                            case "lamp":
                                MO = new LampMod();
                                break;

                            case "fence":
                                FenceMod FM = new FenceMod();
                                FM.FenceFlat = null;
                                FM.FencePost = null;
                                MO           = FM;
                                break;

                            case "FlatRide":
                                FlatRideMod FR = new FlatRideMod();
                                FR.XSize                = (int)float.Parse(ParkOBJ["X"].InnerText);
                                FR.ZSize                = (int)float.Parse(ParkOBJ["Z"].InnerText);
                                FR.Excitement           = float.Parse(ParkOBJ["Excitement"].InnerText);
                                FR.Intensity            = float.Parse(ParkOBJ["Intensity"].InnerText);
                                FR.Nausea               = float.Parse(ParkOBJ["Nausea"].InnerText);
                                FR.closedAngleRetraints = getVector3(ParkOBJ["RestraintAngle"].InnerText);
                                RideAnimationMod RA = new RideAnimationMod();
                                RA.motors    = FlatRideLoader.LoadMotors(ParkOBJ, asset);
                                RA.phases    = FlatRideLoader.LoadPhases(ParkOBJ, asset);
                                FR.Animation = RA;
                                XmlNodeList WaypointsNodes = ParkOBJ.SelectNodes("Waypoints/Waypoint");
                                foreach (XmlNode xndNode in WaypointsNodes)
                                {
                                    Waypoint w = new Waypoint();
                                    w.isOuter          = Convert.ToBoolean(xndNode["isOuter"].InnerText);
                                    w.isRabbitHoleGoal = Convert.ToBoolean(xndNode["isRabbitHoleGoal"].InnerText);
                                    if (xndNode["connectedTo"].InnerText != "")
                                    {
                                        w.connectedTo = xndNode["connectedTo"].InnerText.Split(',').ToList().ConvertAll(s => Int32.Parse(s));
                                    }
                                    w.localPosition = getVector3(xndNode["localPosition"].InnerText);
                                    FR.waypoints.Add(w);
                                }
                                MO = FR;
                                break;

                            case "Shop":
                                ShopMod S = new ShopMod();

                                asset.SetActive(false);
                                XmlNodeList ProductNodes = ParkOBJ.SelectNodes("Shop/Product");
                                foreach (XmlNode ProductNode in ProductNodes)
                                {
                                    ProductMod PM = new ProductMod();
                                    switch (ProductNode["Type"].InnerText)
                                    {
                                    case "consumable":
                                        consumable C = new consumable();
                                        C.ConsumeAnimation = (consumable.consumeanimation)Enum.Parse(typeof(consumable.consumeanimation), ProductNode["ConsumeAnimation"].InnerText);
                                        C.Temprature       = (consumable.temprature)Enum.Parse(typeof(consumable.temprature), ProductNode["Temprature"].InnerText);
                                        C.portions         = Int32.Parse(ProductNode["Portions"].InnerText);
                                        PM = C;
                                        break;

                                    case "wearable":
                                        wearable W = new wearable();
                                        W.BodyLocation = (wearable.bodylocation)Enum.Parse(typeof(wearable.bodylocation), ProductNode["BodyLocation"].InnerText);
                                        PM             = W;
                                        break;

                                    case "ongoing":
                                        ongoing O = new ongoing();
                                        O.duration = Int32.Parse(ProductNode["Duration"].InnerText);
                                        PM         = O;
                                        break;

                                    default:
                                        break;
                                    }
                                    PM.Name = ProductNode["Name"].InnerText;
                                    PM.GO   = Instantiate(bundle.LoadAsset(ProductNode["Model"].InnerText)) as GameObject;
                                    PM.GO.SetActive(false);
                                    PM.Hand  = (ProductMod.hand)Enum.Parse(typeof(ProductMod.hand), ProductNode["Hand"].InnerText);
                                    PM.price = float.Parse(ProductNode["Price"].InnerText);
                                    XmlNodeList IngredientNodes = ProductNode.SelectNodes("Ingredients/Ingredient");
                                    foreach (XmlNode IngredientNode in IngredientNodes)
                                    {
                                        ingredient I = new ingredient();
                                        I.Name      = IngredientNode["Name"].InnerText;
                                        I.price     = float.Parse(IngredientNode["Price"].InnerText);
                                        I.amount    = float.Parse(IngredientNode["Amount"].InnerText);
                                        I.tweakable = Boolean.Parse(IngredientNode["tweakable"].InnerText);
                                        XmlNodeList EffectNodes = IngredientNode.SelectNodes("Effects/effect");
                                        foreach (XmlNode EffectNode in EffectNodes)
                                        {
                                            effect E = new effect();
                                            E.Type   = (effect.Types)Enum.Parse(typeof(effect.Types), EffectNode["Type"].InnerText);
                                            E.amount = float.Parse(EffectNode["Amount"].InnerText);
                                            I.effects.Add(E);
                                        }
                                        PM.ingredients.Add(I);
                                    }
                                    S.products.Add(PM);
                                }
                                MO = S;
                                break;

                            case "PathStyle":
                                Registar.RegisterPath(asset.GetComponent <Renderer>().material.mainTexture, ParkOBJ["inGameName"].InnerText, (Registar.PathType)Enum.Parse(typeof(Registar.PathType), ParkOBJ["PathStyle"].InnerText));
                                break;

                            case "CoasterCar":
                                Debug.Log("Test CoasterCar");
                                CoasterCarMod CC = new CoasterCarMod();
                                CC.CoasterName = ParkOBJ["CoasterName"].InnerText;
                                CC.Name        = ParkOBJ["inGameName"].InnerText;

                                try
                                {
                                    CC.closedAngleRetraints = getVector3(ParkOBJ["RestraintAngle"].InnerText);
                                    CC.FrontCarGO           = Instantiate(bundle.LoadAsset(ParkOBJ["FrontCarGO"].InnerText)) as GameObject;
                                }
                                catch
                                { }
                                MO        = CC;
                                MO.Name   = ParkOBJ["inGameName"].InnerText;
                                MO.Object = asset;

                                break;

                            default:
                                break;
                            }
                            if (MO != null)
                            {
                                MO.Name   = ParkOBJ["inGameName"].InnerText;
                                MO.Object = asset;
                                MO.Price  = float.Parse(ParkOBJ["price"].InnerText);
                                MO.Shader = ParkOBJ["shader"].InnerText;
                                if (ParkOBJ["BoudingBoxes"] != null)
                                {
                                    XmlNodeList BoudingBoxNodes = ParkOBJ.SelectNodes("BoudingBoxes/BoudingBox");
                                    foreach (XmlNode Box in BoudingBoxNodes)
                                    {
                                        BoundingBox BB = MO.Object.AddComponent <BoundingBox>();
                                        BB.isStatic   = false;
                                        BB.bounds.min = getVector3(Box["min"].InnerText);
                                        BB.bounds.max = getVector3(Box["max"].InnerText);
                                        BB.layers     = BoundingVolume.Layers.Buildvolume;
                                        BB.isStatic   = true;
                                    }
                                }
                                MO.Recolorable = Convert.ToBoolean(ParkOBJ["recolorable"].InnerText);
                                if (MO.Recolorable)
                                {
                                    List <Color> colors = new List <Color>();
                                    if (HexToColor(ParkOBJ["Color1"].InnerText) != new Color(0.95f, 0, 0))
                                    {
                                        colors.Add(HexToColor(ParkOBJ["Color1"].InnerText));
                                    }
                                    if (HexToColor(ParkOBJ["Color2"].InnerText) != new Color(0.32f, 1, 0))
                                    {
                                        colors.Add(HexToColor(ParkOBJ["Color2"].InnerText));
                                    }
                                    Debug.Log("Color 3" + HexToColor(ParkOBJ["Color3"].InnerText));
                                    if (ParkOBJ["Color3"].InnerText != "1C0FFF")
                                    {
                                        colors.Add(HexToColor(ParkOBJ["Color3"].InnerText));
                                    }
                                    if (HexToColor(ParkOBJ["Color4"].InnerText) != new Color(1, 0, 1))
                                    {
                                        colors.Add(HexToColor(ParkOBJ["Color4"].InnerText));
                                    }

                                    MO.Colors = colors.ToArray();
                                }
                                Registar.Register(MO).GetComponent <BuildableObject>();
                            }
                        }
                        catch (Exception e)
                        {
                            LogException(e);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogException(e);
                }
                bundle.Unload(false);
                Debug.Log("Bundle Unloaded");
            }
        }
        catch (Exception e)
        {
            LogException(e);
        }
    }
Exemplo n.º 42
0
 void recipeCheck(ingredient cookware)
 {
     AudioSource audio = GetComponentInParent<AudioSource>();
     audio.Play();
     
     switch (cookware)
     { 
         case ingredient.fryPan:
             if (redCount >= 2 && greenCount >= 1)
             {
                 redCount -= 2;
                 greenCount -= 1;
                 Instantiate(friedEgg, (this.transform.position + this.transform.forward * 5), this.transform.rotation);
                 if (!cookEggs)
                 {
                     score += 1;
                     cookEggs = true;
                     eggyPlane.transform.position = eggWin;
                 }
             }
             break;
         case ingredient.juicer:
             if (greenCount >= 1 && blueCount >= 2)
             {
                 greenCount -= 1;
                 blueCount -= 2;
                 Instantiate(orangeJuice, (this.transform.position + this.transform.forward * 5), this.transform.rotation);
                 if (!cookJuice)
                 {
                     score += 1;
                     cookJuice = true;
                     juicePlane.transform.position = juiceWin;
                 }
             }
             break;
         case ingredient.toaster:
             if (redCount >=1 && greenCount >= 1 && blueCount >= 1)
             {
                 redCount -= 1;
                 greenCount -= 1;
                 blueCount -= 2;
                 Instantiate(toast, (this.transform.position + this.transform.forward * 5), this.transform.rotation);
                 if (!cookToast)
                 {
                     score += 1;
                     cookToast = true;
                     toastPlane.transform.position = toastWin;
                 }
             }
             break;
         default:
             Debug.Log("uhhh");
             break;
     }
 }
Exemplo n.º 43
0
            public AddIngredient(ingredient i)
            {
                this.Title = "  Kitchen.Support";
                Button back = new Button
                {
                    Text = "Back",
                    HorizontalOptions = LayoutOptions.Start,
                    VerticalOptions = LayoutOptions.Start
                };
                back.Clicked += (sender, e) =>
                {
                    Navigation.PopModalAsync();
                };

                Label header = new Label
                {
                    Text = "Add Ingredient",
                    Font = Font.BoldSystemFontOfSize(50),
                    HorizontalOptions = LayoutOptions.Center

                };
                Entry e1 = new Entry
                {
                    Placeholder = "Enter New Ingredient search term"
                };
                Button button = new Button
                {
                    Text = "Search",
                    TextColor = Color.White,
                    BackgroundColor = Color.FromHex("77D065")
                };
                Button button2 = new Button
                {
                    Text = "Scan Ingredient Barcode",
                    TextColor = Color.White,
                    BackgroundColor = Color.FromHex("77D065")
                };
                var success = new Label
                {
                    Text = "Ingredient successfully added!",
                    Font = Font.BoldSystemFontOfSize(50)
                };
                var next = new Button
                {
                    Text = "Solid",
                    BackgroundColor = Color.FromHex("77D065")
                };
                next.Clicked += (sender, e) =>
                {
                    Navigation.PopModalAsync();
                };
                this.Content = new StackLayout
                {
                    Spacing = 20,
                    Padding = 50,
                    VerticalOptions = LayoutOptions.Center,
                    Children =
                {
                    back,
                    header,
                    e1,
                    button,
                    button2
                }
                };
                button.Clicked += async (sender, e) =>
                {
                    /*i.searchValue = e1.Text;
                    i.term = e1.Text;
                    ingredients.Add(i);
                    listview.ItemsSource = null;
                    listview.ItemsSource = ingredients;
                    await Navigation.PopModalAsync();*/
                    if (e1.Text == "")
                    {

                    }
                    else
                    {
                        await Navigation.PushModalAsync(new NavigationPage(new SearchForIngredient(e1.Text)));
                        /*this.Content = new StackLayout
                        {
                            Spacing = 20,
                            Padding = 50,
                            VerticalOptions = LayoutOptions.Center,
                            Children =
                            {
                                success,
                                next
                            }
                        };*/
                    }
                    //Navigation.PopModalAsync();
                };
                button2.Clicked += async (sender, e) =>
                {
                    var data1 = await DependencyService.Get<IScanner>().Scan();
                    if (data1 == "null")
                    {
                        await Navigation.PopModalAsync();
                    }
                    else
                    {
                        var client = new System.Net.Http.HttpClient();
                        string url = "http://api.walmartlabs.com/v1/items?apiKey=h5yjnkgcrmtzn3rjaduapusv&upc=" + data1;
                        var response = client.GetAsync(new Uri(url));
                        if (response.Result.StatusCode.ToString() == "OK")
                        {
                            var message = response.Result.Content.ReadAsStringAsync().Result;
                            //var result = JsonConvert.DeserializeObject<Items>(message);
                            //List<Item> information = result.data;
                            //var item = information.ToList().First();
                            //var name = item.name;
                            string word = "";
                            string name = "";
                            for (int location = 0; location < message.Length - 4; location++)
                            {
                                word = (message.Substring(location, 4));
                                if (word == "name")
                                {
                                    int j = location + 7;
                                    char c = message[j];
                                    while (c != '"')
                                    {
                                        name += message[j];
                                        j++;
                                        c = message[j];
                                    }
                                    break;
                                }
                            }
                            //await DisplayAlert("Item Found", name, "OK");
                            //var json = JObject.Parse (message);
                            //var token = json ["name"];
                            //await DisplayAlert ("Scanner", token.ToString(), "OK");
                            //await storeToken(token.ToString());
                            //e1.Text = name;
                            if (name.Contains("Peanut Butter"))
                            {
                                name = "peanut butter";
                            }

                            await Navigation.PushModalAsync(new NavigationPage(new SearchForIngredient(name)));
                            /*this.Content = new StackLayout
                            {
                                Spacing = 20,
                                Padding = 50,
                                VerticalOptions = LayoutOptions.Center,
                                Children =
                                {
                                    success,
                                    next
                                }
                            };*/
                            //await Navigation.PushModalAsync (new NavigationPage(new HomePage()));
                        }
                        else
                        {
                            await DisplayAlert("Alert", "Could not find item from UPC code.", "OK");
                            await DisplayAlert("Scanner", data1, "OK");
                            await DisplayAlert("Response", response.Result.StatusCode.ToString(), "OK");
                        }
                    }

                };
            }
Exemplo n.º 44
0
        public IngredientView()
        {
            this.Title = "  Kitchen.Support";
            instructions = new Label
            {
                Text = "Tap on an ingredient to remove it"
            };
            Button back = new Button
            {
                Text = "Back",
                HorizontalOptions = LayoutOptions.Start,
                VerticalOptions = LayoutOptions.Start
            };
            back.Clicked += (sender, e) =>
            {
                Navigation.PopModalAsync();
            };
            var client = new HttpClient();
            string url = "http://api.kitchen.support/pantry?offset=0&limit=30&api_token=";
            string token = DependencyService.Get<localDataInterface>().load("token");
            url += token;
            var response = client.GetStringAsync(new Uri(url));
            var ye = response.Result;
            List<ingredient> ingredients = parseIngredients(response.Result);
            Label header = new Label
            {
                Text = "Your Pantry",
                Font = Font.BoldSystemFontOfSize(50),
                HorizontalOptions = LayoutOptions.Center
            };
            listview = new ListView
            {
                RowHeight = 30
            };
            if (ingredients.Count == 0)
            {
                instructions.Text = " ";
                ingredient i = new ingredient();
                i.term = "You have no ingredients in your pantry";
                ingredients.Add(i);
                listview.HeightRequest = 120;
            }
            listview.ItemsSource = ingredients;

            listview.ItemTemplate = new DataTemplate(typeof(TextCell));
            listview.ItemTemplate.SetBinding(TextCell.TextProperty, ".term");
            Button button = new Button();
            button.Text = "Add Ingredient";
            listview.ItemSelected += (sender, e) =>
            {
                if (e.SelectedItem == null)
                {
                    return;
                }
                ingredients.Remove((ingredient)e.SelectedItem);
                listview.SelectedItem = null;
                ingredient i = (ingredient)e.SelectedItem;
                client = new HttpClient();
                url = "http://api.kitchen.support/pantry";
                string data = "{\n    \"api_token\" : \"" + DependencyService.Get<localDataInterface>().load("token") + "\",\n    \"ingredient_id\" : \"" + i.id + "\",\n    \"value\" : \"" + "false" + "\"\n}";
                var httpContent = new StringContent(data);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var addResponse = client.PostAsync(new Uri(url), httpContent);
                 ye = addResponse.Result.StatusCode.ToString();
                if (addResponse.Result.StatusCode.ToString() != "OK")
                {

                }
                client = new HttpClient();
                url = "http://api.kitchen.support/pantry?offset=0&limit=30&api_token=";
                token = DependencyService.Get<localDataInterface>().load("token");
                url += token;
                response = client.GetStringAsync(new Uri(url));
                //ingredients = parseIngredients(response.Result);
                IngredientView.listview.ItemsSource = null;
                IngredientView.listview.ItemsSource = ingredients;
            };

            button.Clicked += (sender, e) =>
            {
                ingredient newIngredient = new ingredient();
                Navigation.PushModalAsync(new NavigationPage(new AddIngredient(newIngredient)));

            };
            // Build the page.
            this.Content = new StackLayout
            {
                Spacing = 20,
                Padding = 50,
                VerticalOptions = LayoutOptions.Center,
                Children =
                {
                    back,

                    header,
                    instructions,
                    listview,
                    button
                }
            };
        }
 public bool hasIngredient(ingredient ingredient)
 {
     return ingredients.Contains(ingredient);
 }
 private void newButton(ingredient ing)
 {
     string name = ing.name;
     GameObject button = (GameObject)MonoBehaviour.Instantiate(Resources.Load("myIngredientButton"), Vector3.zero, Quaternion.identity);
     ing.button = button;
     Text txt = button.GetComponentInChildren<Text>();
     txt.text = name;
     ing.checkMark = button.transform.GetChild(2).gameObject;
     ing.trashMark = button.transform.GetChild(3).gameObject;
     ing.checkMark.SetActive(false);
     ing.trashMark.SetActive(false);
     Button b = button.GetComponent<Button>();
     b.name = name;
     b.onClick.AddListener(() =>
     {
         if (trashMode)
         {
             if (trashedIngredients.Contains(ing))
             {
                 trashedIngredients.Remove(ing);
                 ing.trashMark.SetActive(false);
             }
             else
             {
                 trashedIngredients.Add(ing);
                 ing.trashMark.SetActive(true);
             }
         }
         else
         {
             if (selectedIngredients.Contains(ing))
             {
                 deselectIngredient(ing);
             }
             else
             {
                 selectIngredient(ing);
             }
         }
     });
     button.transform.SetParent(myIngredientsGrid.transform);
     rt.sizeDelta = new Vector2(rt.sizeDelta.x, rt.sizeDelta.y + 250);
     button.GetComponent<RectTransform>().localScale = new Vector3(1, 1, 1);
 }
 // Returns whether item was removed or not (I.E. was not in list anyway)
 public bool removeIngredient(ingredient ing)
 {
     bool itemRemoved = ingredients.Remove(ing);
     if (itemRemoved)
     {
         GameObject.Destroy(ing.button);
         saveIngredients();
         rt.sizeDelta = new Vector2(rt.sizeDelta.x, rt.sizeDelta.y - 250);
     }
     return itemRemoved;
 }