Esempio n. 1
0
        public async Task <HttpResponseMessage> AddMenuItem(int id, int menuItemId)
        {
            try
            {
                RestaurantMenuItem res = await _db.RestaurantMenuItems.Where(d => d.Restaurant_id == id && d.MenuItem_id == menuItemId).FirstOrDefaultAsync();

                if (res != null)
                {
                    if (res.Deleted)
                    {
                        res.Deleted = false;
                        _db.SetModified(res);
                        await _db.SaveChangesAsync();
                    }
                }
                else
                {
                    _db.RestaurantMenuItems.Add(new RestaurantMenuItem
                    {
                        Restaurant_id = id,
                        MenuItem_id   = menuItemId
                    });
                    await _db.SaveChangesAsync();
                }

                return(Request.CreateResponse(HttpStatusCode.OK, "Success"));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Failed"));
            }
        }
 //This method will simulate the selection of an object by changing the colour of the control the user selects
 public void SelectItemHighLight(String id)
 {
     foreach (RestaurantMenuItemView viewItem in flpItems.Controls)
     {
         if ((String)viewItem.Tag == id)
         {
             viewItem.BackColor = Color.FromName("ActiveCaption");
             foreach (RestaurantMenuItemView view in flpItems.Controls)
             {
                 if (view.Tag != viewItem.Tag)
                 {
                     if (view.Active == true)
                     {
                         view.resetColor();
                     }
                     else
                     {
                         view.BackColor = Color.FromName("ControlDark");
                     }
                 }
             }
             foreach (RestaurantMenuItem item in OwnerStorage.MenuItems)
             {
                 if (viewItem.Label == item.Name)
                 {
                     selectedItem = item;
                 }
             }
             cbxEnabled.Checked = selectedItem.OutOfStock ? false : true;
             pnlEdit.Enabled    = true;
         }
     }
 }
Esempio n. 3
0
 public RestaurantMenuViewModel(RestaurantMenuItem model)
 {
     Name            = model.Name;
     PictureFileName = model.PictureFile;
     Description     = model.Description;
     Price           = model.Price;
 }
        //Method for deleting the MenuItem
        private void btnDelete_Click(object sender, EventArgs e)
        {
            RestaurantMenuItem tempItem     = selectedItem;
            DialogResult       dialogResult = MessageBox.Show("Are you sure you would like to delete " + tempItem.Name + "?", tempItem.Name, MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                ShowLoading(true);
                AsyncCallback <long> deleteObjectCallback = new AsyncCallback <long>(
                    deletionTime =>
                {
                    //Success. The object has been removed successfully
                    Invoke(new Action(() =>
                    {
                        foreach (RestaurantMenuItemView view in flpItems.Controls)
                        {
                            //The MenuItemView must be removed from the FlowLayoutPanel
                            if (view.Tag.ToString() == tempItem.objectId)
                            {
                                flpItems.Controls.Remove(view);
                            }
                        }
                        OwnerStorage.MenuItems.Remove(tempItem);
                        populateMenu();
                        pnlEdit.Enabled = false;
                        ShowLoading(false);
                        lblStatus.Text = selectedItem.Name + " has been removed";
                    }));
                },
                    error =>
                {
                    //Something went wrong, an error message will be displayed
                    Invoke(new Action(() =>
                    {
                        ShowLoading(false);
                        lblStatus.Text = "Error: " + error.Message;
                    }));
                });

                AsyncCallback <RestaurantMenuItem> saveObjectCallback = new AsyncCallback <RestaurantMenuItem>(
                    savedMenuItem =>
                {
                    //The object has been saved, now it can be removed
                    Backendless.Persistence.Of <RestaurantMenuItem>().Remove(savedMenuItem, deleteObjectCallback);
                },
                    error =>
                {
                    //Something went wrong, an error message will be displayed
                    Invoke(new Action(() =>
                    {
                        ShowLoading(false);
                        lblStatus.Text = "Error: " + error.Message;
                    }));
                }
                    );

                //Backendless demands that an object has to be saved first before it gets deleted
                Backendless.Persistence.Of <RestaurantMenuItem>().Save(tempItem, saveObjectCallback);
            }
        }
        private void OnBindingContextChanged(object sender, EventArgs e)
        {
            base.OnBindingContextChanged();

            var cell = (ViewCell)sender;
            RestaurantMenuItem item = (RestaurantMenuItem)cell.BindingContext;

            var l      = item.Description.Length;
            var offset = (l / 50) * 20;

            cell.Height = 100 + offset;
        }
Esempio n. 6
0
        public ActionResult Add(RestaurantMenuViewModel model, HttpPostedFileBase menuimage)
        {
            try
            {
                //Explicitly Validate Model for menu image
                if (menuimage == null || menuimage.ContentLength < 1 || (menuimage.ContentType != "image/jpeg" && menuimage.ContentType != "image/png"))
                {
                    ModelState.AddModelError("addstatus", "A Menu Item needs to have a valid Image, Only JPEG and PNG images are supported");
                }
                if (ModelState.IsValid)
                {
                    // Attempt to add the offer
                    var restauranttable = new RestaurantMenuItem
                    {
                        Name        = model.Name,
                        Description = model.Description,
                        Price       = model.Price,
                        PictureFile = new ImagesController().PutImage(menuimage, null).ToString("n")
                    };

                    var itemid = Repository.Add(restauranttable);
                    if (itemid > 0)
                    {
                        TempData[TempDataStringResuorce.ActionResultNotification] = new ActionResultNotification
                        {
                            Message = String.Format("Menu Item \"{0}\" with Id:{1} was successfully Added", model.Name, itemid),
                            Result  = true,
                            State   = ActionResultNotification.MessageState.Information
                        };
                        return(RedirectToAction("Index"));
                    }
                }
                // If we got this far, something failed, redisplay form
                TempData[TempDataStringResuorce.ActionResultNotification] = new ActionResultNotification
                {
                    Message = ModelState.ContainsKey("addstatus") ? ModelState["addstatus"].Errors[0].ErrorMessage : "There was an Error in adding the new Menu item, please try again",
                    Result  = false,
                    State   = ActionResultNotification.MessageState.Warning
                };
                return(View(model));
            }
            catch (Exception e)
            {
                TempData[TempDataStringResuorce.ActionResultNotification] = new ActionResultNotification
                {
                    Message = e.Message,
                    Result  = false,
                    State   = ActionResultNotification.MessageState.Error
                };
                return(View(model));
            }
        }
 public AddEditMenuItem(RestaurantMenuItem item)
 {
     InitializeComponent();
     this.transferedItem = item;
     //Determines if this form should be used to create a new Menu Item or modify an existing one
     if (transferedItem != null)
     {
         lblTitle.Text       = "Editing Menu Item";
         tbxDescription.Text = item.Ingredients;
         tbxName.Text        = item.Name;
         cbxType.Text        = item.Type;
         nudPrice.Text       = item.Price.ToString("N2");
     }
 }
Esempio n. 8
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var t  = new RestaurantMenuItem();
            var tc = new RestaurantMenuItemRepository();

            if (ItemId > 0)
            {
                t                = tc.GetItem(ItemId, ModuleId);
                t.Name           = txtName.Text.Trim();
                t.Description    = txtDescription.Text.Trim();
                t.IsDailySpecial = chkDailySpecial.Checked;
                t.IsVegetarian   = chkVegetarian.Checked;
                t.Price          = Convert.ToDecimal(txtPrice.Text);
                t.PictureFileId  = fpPicture.FileID;
            }
            else
            {
                t = new RestaurantMenuItem()
                {
                    AddedByUserId  = UserId,
                    DateAdded      = DateTime.Now,
                    Name           = txtName.Text.Trim(),
                    Description    = txtDescription.Text.Trim(),
                    IsDailySpecial = chkDailySpecial.Checked,
                    IsVegetarian   = chkVegetarian.Checked,
                    Price          = Convert.ToDecimal(txtPrice.Text),
                    PictureFileId  = fpPicture.FileID,
                };
            }

            t.DateModified     = DateTime.Now;
            t.ModifiedByUserId = UserId;
            t.ModuleId         = ModuleId;

            if (t.MenuItemId > 0)
            {
                tc.UpdateItem(t);
            }
            else
            {
                tc.CreateItem(t);
            }
            Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }
Esempio n. 9
0
        public async Task <HttpResponseMessage> RemoveMenuItem(int id, int menuItemId)
        {
            try
            {
                RestaurantMenuItem res = await _db.RestaurantMenuItems.Where(d => d.Restaurant_id == id && d.MenuItem_id == menuItemId).FirstOrDefaultAsync();

                if (res == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Menu item does not exist for restaurant"));
                }

                res.Deleted = true;

                _db.SetModified(res);
                await _db.SaveChangesAsync();

                return(Request.CreateResponse(HttpStatusCode.OK, "Success"));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Failed"));
            }
        }
Esempio n. 10
0
        //Controller for RestaurantMenuItem which determines if the user wishes to add or edit a MenuItem to the restaurant
        private void AddOrEdit(RestaurantMenuItem temp)
        {
            AddEditMenuItem newForm = new AddEditMenuItem(temp);

            if (newForm.ShowDialog() == DialogResult.OK)
            {
                ShowLoading(true);
                AsyncCallback <RestaurantMenuItem> callback = new AsyncCallback <RestaurantMenuItem>(
                    result =>
                {
                    Invoke(new Action(() =>
                    {
                        //Means an existing item was edited
                        if (temp != null)
                        {
                            OwnerStorage.MenuItems.Insert(OwnerStorage.MenuItems.IndexOf(temp), newForm.transferedItem);
                            OwnerStorage.MenuItems.Remove(temp);

                            foreach (RestaurantMenuItemView item in flpItems.Controls)
                            {
                                if (item.Tag.Equals(temp.objectId))
                                {
                                    item.Name  = newForm.transferedItem.Name;
                                    item.Type  = newForm.transferedItem.Type;
                                    item.Price = newForm.transferedItem.Price;
                                }
                            }
                            populateMenu();
                            SortRefresh();
                            SelectItemHighLight(selectedItem.objectId);
                        }
                        //Means a new item is created
                        else
                        {
                            RestaurantMenuItemView newView = new RestaurantMenuItemView();
                            newView.Label  = result.Name;
                            newView.Active = true;
                            newView.Type   = result.Type;
                            newView.Tag    = result.objectId;
                            newView.Price  = result.Price;

                            OwnerStorage.MenuItems.Add(result);

                            newView.lblName.MouseClick += new MouseEventHandler(MenuLabel_Click);
                            newView.MouseClick         += new MouseEventHandler(MenuItem_Click);
                            flpItems.Controls.Add(newView);
                        }
                        ShowLoading(false);
                    }));
                },
                    fault =>
                {
                    Invoke(new Action(() =>
                    {
                        MessageBox.Show(this, "Error: " + fault.Message);
                        ShowLoading(false);
                    }));
                });

                //Runs the save callback. It automatically updates objects, so no need to create multiple callbacks
                Backendless.Data.Of <RestaurantMenuItem>().Save(newForm.transferedItem, callback);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// The StoreRestaurantUser method.
        /// Contains logic to store a restaurant user to the database.
        /// <para>
        /// @author: Jennifer Nguyen
        /// @updated: 03/13/2018
        /// </para>
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="passwordSalt"></param>
        /// <param name="securityQuestions"></param>
        /// <param name="securityAnswerSalts"></param>
        /// <param name="claims"></param>
        /// <param name="userProfile"></param>
        /// <param name="restaurantProfile"></param>
        /// <param name="businessHours"></param>
        /// <param name="foodPreferences"></param>
        /// <returns>ResponseDto with bool data</returns>
        public ResponseDto <bool> StoreRestaurantUser(UserAccount userAccount, PasswordSalt passwordSalt, UserClaims userClaims, UserProfile userProfile, RestaurantProfile restaurantProfile, IList <SecurityQuestion> securityQuestions, IList <SecurityAnswerSalt> securityAnswerSalts, IList <FoodPreference> foodPreferences, IList <BusinessHour> businessHours)
        {
            using (var dbContextTransaction = context.Database.BeginTransaction())
            {
                try
                {
                    // Add UserAccount
                    context.UserAccounts.AddOrUpdate(userAccount);
                    context.SaveChanges();

                    // Get Id from UserAccount
                    var userId = (from account in context.UserAccounts
                                  where account.Username == userAccount.Username
                                  select account.Id).SingleOrDefault();

                    // Set UserId to dependencies
                    passwordSalt.Id      = userId;
                    userClaims.Id        = userId;
                    userProfile.Id       = userId;
                    restaurantProfile.Id = userId;

                    // Add FoodPreferences
                    foreach (var foodPreference in foodPreferences)
                    {
                        foodPreference.UserId = userId;
                        context.FoodPreferences.Add(foodPreference);
                        context.SaveChanges();
                    }

                    // Add SecurityQuestions
                    foreach (var securityQuestion in securityQuestions)
                    {
                        securityQuestion.UserId = userId;
                        context.SecurityQuestions.Add(securityQuestion);
                        context.SaveChanges();
                    }

                    // Get SecurityQuestions in database
                    var queryable = (from question in context.SecurityQuestions
                                     where question.UserId == userId
                                     select question).ToList();

                    // Add SecurityAnswerSalts
                    for (var i = 0; i < securityQuestions.Count; i++)
                    {
                        // Get SecurityQuestionId for each securityAnswerSalt
                        var securityQuestionId = (from query in queryable
                                                  where query.Question == securityQuestions[i].Question
                                                  select query.Id).SingleOrDefault();

                        // Set SecurityQuestionId for SecurityAnswerSalt
                        securityAnswerSalts[i].Id = securityQuestionId;
                        // Add SecurityAnswerSalt
                        context.SecurityAnswerSalts.Add(securityAnswerSalts[i]);
                        context.SaveChanges();
                    }

                    // Add PasswordSalt
                    context.PasswordSalts.AddOrUpdate(passwordSalt);

                    // Add UserClaims
                    context.UserClaims.Add(userClaims);

                    // Add UserProfile
                    context.UserProfiles.Add(userProfile);

                    // Add RestaurantProfile
                    context.RestaurantProfiles.Add(restaurantProfile);
                    context.SaveChanges();

                    // Add BusinessHours
                    foreach (var businessHour in businessHours)
                    {
                        businessHour.RestaurantId = userId;
                        context.BusinessHours.Add(businessHour);
                        context.SaveChanges();
                    }

                    // Add First Menu
                    // Find the corresponding profile
                    var dbRestaurantProfile = (from profile in context.RestaurantProfiles
                                               where profile.Id == userId
                                               select profile).SingleOrDefault();
                    var newMenu = new RestaurantMenu("Your First Menu", false, 0);

                    newMenu.RestaurantProfile = dbRestaurantProfile;
                    context.RestaurantMenus.Add(newMenu);
                    context.Entry(dbRestaurantProfile).State = System.Data.Entity.EntityState.Unchanged;
                    context.SaveChanges();

                    // Add First Menu Item
                    // Find the corresponding menu
                    var dbRestaurantMenu = (from menu in context.RestaurantMenus
                                            where menu.RestaurantId == restaurantProfile.Id
                                            select menu).SingleOrDefault();
                    var newMenuItem = new RestaurantMenuItem(itemName: "Your First Menu Item", itemPrice: 0, itemPicture: ConfigurationManager.AppSettings["DefaultURLMenuItemPath"], tag: "tag", description: "", isActive: false, flag: 0);
                    newMenuItem.RestaurantMenu = dbRestaurantMenu;
                    context.RestaurantMenuItems.Add(newMenuItem);
                    context.Entry(dbRestaurantMenu).State = System.Data.Entity.EntityState.Unchanged;
                    context.SaveChanges();

                    // Commit transaction to database
                    dbContextTransaction.Commit();

                    // Return a true ResponseDto
                    return(new ResponseDto <bool>()
                    {
                        Data = true
                    });
                }
                catch (Exception)
                {
                    // Rolls back the changes saved in the transaction
                    dbContextTransaction.Rollback();
                    // Return a false ResponseDto
                    return(new ResponseDto <bool>()
                    {
                        Data = false,
                        Error = GeneralErrorMessages.GENERAL_ERROR
                    });
                }
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbxName.Text == "") //Validation that makes sure the Name field is not empty
            {
                MessageBox.Show(this, "The Item Name can not be left blank", "Naming Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            if (tbxDescription.Text == "")     //Validation that makes sure the description field is not empty
            {
                MessageBox.Show(this, "The Description can not be empty", tbxName.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            if (nudPrice.Text == "")         //Validation that makes sure the price field is not empty
            {
                MessageBox.Show(this, "The Price can not be empty", tbxName.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            if (tbxDescription.TextLength < 10)         //Validation that makes sure the description is no less than 10 characters long
            {
                MessageBox.Show(this, "The Description must contain at least 10 characters", tbxName.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            if (cbxType.Text == "")             //Validation that makes sure that a type has been selected
            {
                MessageBox.Show(this, "Make sure to select a category for Dish/Item Type", tbxName.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //Determines if a Menu Item with the same name exists
                bool flag = false;
                foreach (RestaurantMenuItem item in OwnerStorage.MenuItems)
                {
                    if (item.Name == tbxName.Text)
                    {
                        flag = true;
                    }
                }
                if (flag == true && transferedItem == null)
                {
                    MessageBox.Show(this, "A Dish/Item with the same name (" + tbxName.Text + ") already exists", tbxName.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //MenuItem object gets created
                    RestaurantMenuItem newItem = new RestaurantMenuItem();
                    newItem.Name         = tbxName.Text;
                    newItem.Ingredients  = tbxDescription.Text;
                    newItem.Type         = cbxType.Text;
                    newItem.RestaurantId = OwnerStorage.ThisRestaurant.objectId;
                    newItem.Price        = Convert.ToDouble(nudPrice.Text);
                    newItem.OutOfStock   = false;
                    if (transferedItem != null)
                    {
                        newItem.objectId = transferedItem.objectId;
                    }

                    //Since the Backendless creation happens on the parent form, we only have to assign it to the public property and then close this form
                    transferedItem = newItem;


                    OwnerStorage.FileWriter.WriteLineToFile("User Added a new Menu Item", true);
                    OwnerStorage.FileWriter.WriteLineToFile("Name:  " + newItem.Name, false);

                    DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }
        /// <summary>
        /// Returns restaurant profile dto inside response dto
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        ///
        // move context up to here
        public ResponseDto <RestaurantProfileDto> GetRestaurantProfileById(int?id)
        {
            using (context)
            {
                var dbUserProfile = (from profile in context.UserProfiles
                                     where profile.Id == id
                                     select profile).SingleOrDefault();

                var userProfileDomain = new UserProfile(dbUserProfile.Id, dbUserProfile.DisplayName, dbUserProfile.DisplayPicture);
                // Find restaurant associated with the ID
                var dbRestaurantProfile = (from restaurantProfile in context.RestaurantProfiles
                                           where restaurantProfile.Id == dbUserProfile.Id
                                           select restaurantProfile).SingleOrDefault();

                var restaurantProfileDomain = new RestaurantProfile(dbRestaurantProfile.PhoneNumber, dbRestaurantProfile.Address, dbRestaurantProfile.Details);

                // Find restaurant's business hours
                var businessHourDtos = (from businessHour in context.BusinessHours
                                        where businessHour.RestaurantId == dbRestaurantProfile.Id
                                        select new RestaurantBusinessHourDto()
                {
                    Id = businessHour.Id,
                    Day = businessHour.Day,
                    OpenDateTime = businessHour.OpenTime,
                    CloseDateTime = businessHour.CloseTime,
                    TimeZone = businessHour.TimeZone
                }).ToList();

                IList <RestaurantMenuWithItems> restaurantMenusList = new List <RestaurantMenuWithItems>();

                var dbRestaurantMenus = dbRestaurantProfile.RestaurantMenu;

                if (dbRestaurantMenus.Count > 0)
                {
                    foreach (var menu in dbRestaurantMenus)
                    {
                        // Create the menu domain
                        var menuDomain = new RestaurantMenu(menu.Id, menu.MenuName, menu.IsActive, menu.Flag);

                        // Create the list for the menu items
                        var menuItemDomains = new List <RestaurantMenuItem>();
                        // Then, find all menu items associated with each menu and turn that into a list
                        var dbMenuItems = (from menuItems in context.RestaurantMenuItems
                                           where menuItems.MenuId == menu.Id
                                           select menuItems).ToList();

                        foreach (var item in dbMenuItems)
                        {
                            var menuItemDomain = new RestaurantMenuItem(item.Id, item.ItemName, item.ItemPrice, item.ItemPicture, item.Tag, item.Description, item.IsActive, item.Flag);
                            menuItemDomains.Add(menuItemDomain);
                            // Map menu items to menus in a dictionary
                        }
                        var restaurantMenuWithItems = new RestaurantMenuWithItems(menuDomain, menuItemDomains);
                        restaurantMenusList.Add(restaurantMenuWithItems);
                    }
                }

                else
                {
                    restaurantMenusList = new List <RestaurantMenuWithItems>();
                }

                ResponseDto <RestaurantProfileDto> responseDto = new ResponseDto <RestaurantProfileDto>
                {
                    Data  = new RestaurantProfileDto(userProfileDomain, restaurantProfileDomain, businessHourDtos, restaurantMenusList),
                    Error = null
                };
                return(responseDto);
            }
        }