예제 #1
0
        public void RestaurantController_ModifierRestaurantAvecRestoValide_CreerRestaurantEtRenvoiVueIndex()
        {
            using (IDal dal = new DalEnDur())
            {
                RestaurantController controller = new RestaurantController(dal);
                Resto resto = new Resto {
                    Id = 1, Nom = "Resto mate", Telephone = "0102030405"
                };
                controller.ValideLeModele(resto);

                RedirectToRouteResult resultat = (RedirectToRouteResult)controller.ModifierRestaurant(resto);

                Assert.AreEqual("Index", resultat.RouteValues["action"]);
                Resto restoTrouve = dal.ObtientTousLesRestaurants().First();
                Assert.AreEqual("Resto mate", restoTrouve.Nom);
            }
        }
 public ActionResult CreerRestaurant(Resto resto)
 {
     using (IDal dal = new Dal())
     {
         if (dal.RestaurantExiste(resto.Nom))
         {
             ModelState.AddModelError("Nom", "Ce nom de restaurant existe déjà");
             return(View(resto));
         }
         if (!ModelState.IsValid)
         {
             return(View(resto));
         }
         dal.CreerRestaurant(resto.Nom, resto.Telephone);
         return(RedirectToAction("Index"));
     }
 }
예제 #3
0
        public async Task <IEnumerable <Resultat> > ObtenirLesResultats(int idSondage)
        {
            var restaurants = await RestoDbContext.Restos.ToListAsync();

            var     resultats = new List <Resultat>();
            Sondage sondage   = await RestoDbContext.Sondages.FirstAsync(s => s.Id == idSondage);

            foreach (IGrouping <int, Vote> grouping in sondage.Votes.GroupBy(v => v.Resto.Id))
            {
                int   idRestaurant = grouping.Key;
                Resto resto        = restaurants.First(r => r.Id == idRestaurant);
                int   nmbreVotes   = grouping.Count();
                resultats.Add(new Resultat {
                    Nom = resto.Nom, Telephone = resto.Telephone, NombreDeVotes = nmbreVotes
                });
            }
            return(resultats);
        }
예제 #4
0
        public async Task <IHttpActionResult> Get(int id)
        {
            OrderSlot orderSlot = await DbManager.OrderSlots.FirstOrDefaultAsync(o => o.OrderSlotId == 57);

            var userName = User.Identity.GetUserName();
            var user     = await UserManager.FindByNameAsync(userName);


            if (user == null)
            {
                return(BadRequest());
            }

            // Check and creates the list of available slottimes
            // TODO: Current strategy is to create this list on request. See for optimization to schedule this list creation one time a day (off ressources-
            Resto resto = await DbManager.Restos.FirstOrDefaultAsync(r => r.Id == id);

            if (resto == null)
            {
                return(BadRequest());
            }
            await new OrderHelper().CreateOrderSlotListForDay(id, DateTime.Today, DbManager);


            // Collect the available slot times.
            List <OrderSlot> availableOrderSlots = new List <OrderSlot>();

            availableOrderSlots = resto.OrderIntakeSlots
                                  .Where(r => r.OrderSlotTime != null).ToList();

            List <OrderSlotAPI> slotTimeAPI = new List <OrderSlotAPI>();

            foreach (var item in resto.OrderIntakeSlots
                     .Where(r => r.Order == null)                           // Check this slot time is free
                     .Where(r => r.OrderSlotTime.CompareTo(DateTime.Now) > 0))
            {
                slotTimeAPI.Add(new OrderSlotAPI {
                    OrderSlotId   = item.OrderSlotId,
                    OrderSlotTime = item.OrderSlotTime,
                    SlotGroup     = item.SlotGroup
                });
            }
            return(Ok(slotTimeAPI));
        }
        public async Task <IHttpActionResult> PostRestaurant(Resto restaurant)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Resto restoExiste = db.Restaurants.SingleOrDefault(x => x.Name == restaurant.Name && x.Address == restaurant.Address);

            if (restoExiste != null)
            {
                return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            }

            db.Restaurants.Add(restaurant);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = restaurant.Id }, restaurant));
        }
예제 #6
0
 public ActionResult ModifierRestaurant(int?id)
 {
     if (id.HasValue)
     {
         using (IDal dal = new Dal())
         {
             Resto restaurant = dal.ObtientTousLesRestaurants().FirstOrDefault(r => r.Id == id.Value);
             if (restaurant == null)
             {
                 return(View("Error"));
             }
             return(View(restaurant));
         }
     }
     else
     {
         return(View("Error"));
     }
 }
예제 #7
0
        public async Task <ActionResult> CreateMenu(int?Id)
        {
            Resto resto = await DbManager.Restos.FindAsync(Id);

            if (resto != null)
            {
                MenuViewModel menuView = new MenuViewModel()
                {
                    restoName = resto.Name,
                    restoId   = resto.Id,
                    resto     = resto
                };
                return(View(menuView));
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
        }
예제 #8
0
 public void SetBackGroundResult(string key, object result)
 {
     if (!CommonService.CheckInternetConnection(Activity))
     {
         Toast.MakeText(Activity, "Please check your internet connection", ToastLength.Short).Show(); return;
     }
     if (result == null)
     {
         return;
     }
     if (key == "GetRestoByID")
     {
         List <Resto> restoList = (List <Resto>)result;
         if (restoList.Count > 0)
         {
             m_resto = restoList[0];
             loadRestoInfo();
         }
     }
     if (key == "GetMenuByRestoID")
     {
         m_restoMenuAll = (List <MenuResto>)result;
         foreach (MenuResto menu in m_restoMenuAll)
         {
             if (menu.menu_foodtype == "MAKANAN")
             {
                 m_restoMenuMakanan.Add(menu);
             }
             if (menu.menu_foodtype == "MINUMAN")
             {
                 m_restoMenuMinuman.Add(menu);
             }
             if (menu.menu_foodtype == "SPESIAL")
             {
                 m_restoMenuSpesial.Add(menu);
             }
         }
         m_menuGridSpesial.Adapter = new MenuRestoAdapter(Activity, m_restoMenuSpesial);
         m_menuGridMinuman.Adapter = new MenuRestoAdapter(Activity, m_restoMenuMinuman);
         m_menuGridMakanan.Adapter = new MenuRestoAdapter(Activity, m_restoMenuMakanan);
     }
 }
예제 #9
0
 public ActionResult CreerRestaurant(Resto resto)
 {
     //teste par le nom si restaurant existe déjà
     if (dal.RestaurantExiste(resto.Nom))
     {
         //Renvoi message d'erreur
         ModelState.AddModelError("Nom", "Ce nom de restaurant existe déjà");
         return(View(resto));
     }
     //teste si numéro de tel est valide, si non msg erreur
     if (!ModelState.IsValid)
     {
         return(View(resto));
     }
     //Création du restaurant
     dal.CreerRestaurant(resto.Nom, resto.Telephone);
     //Redirection vers une action (d'un controlleur avec paramètre si besoin)
     //renvoi sur la vue Index
     return(RedirectToAction("Index"));
 }
예제 #10
0
        public async Task <ActionResult> PickASlotTimeStep0(int RestoId)
        {
            // Check and creates the list of available slottimes
            // TODO: Current strategy is to create this list on request. See for optimization to schedule this list creation one time a day (off ressources-
            await new OrderHelper().CreateOrderSlotListForDay(RestoId, DateTime.Today, DbManager);
            Resto resto = await DbManager.Restos.FirstOrDefaultAsync(r => r.Id == RestoId);

            // Collect the available slot times.
            List <OrderSlot> availableOrderSlots = new List <OrderSlot>();

            availableOrderSlots = resto.OrderIntakeSlots.Where(r => r.OrderSlotTime != null).ToList();

            PickASlotTimeView pickSlotTimeView = new PickASlotTimeView();

            foreach (var item in resto.OrderIntakeSlots.Where(r => r.OrderSlotTime.CompareTo(DateTime.Now) > 0))
            {
                pickSlotTimeView.Add(item);
            }
            return(View(pickSlotTimeView));
        }
예제 #11
0
        public ActionResult IndexExemple()
        {
            // Afficher une vue :
            //
            // return View();
            // return View("Index");
            // return View("Bonjour");
            // return View("~/Views/Test/Essai.cshtml");

            // ViewData, dictionnaire fourre-tout où nous pouvons mettre des objets en les associant à des clés.
            //
            ViewData["message"] = "Bonjour depuis le contrôleur !";
            ViewData["date"]    = DateTime.Now;
            ViewData["resto"]   = new Resto {
                Nom = "Choucroute party", Telephone = "01 60 14 80 55"
            };

            //dynamic resto = new Resto();
            //resto.Nom = "Resto dynam-hic";
            //resto.Adresse = "compile, mais ne fonctionnera pas";

            // ViewBag, Objet de type dynamic
            //
            ViewBag.message = "ReBonjour depuis le contrôleur !";
            ViewBag.date    = DateTime.Now;
            ViewBag.resto   = new Resto {
                Nom = "Pizza party", Telephone = "01 60 14 55 80"
            };

            //
            // return View();
            //

            // En passant un objet
            //
            Resto r = new Resto {
                Nom = "La bonne fourchette", Telephone = "1234"
            };

            return(View(r));
        }
예제 #12
0
        public async Task <ActionResult> Create(CreateRestoViewModel createViewModel)
        {
            if (ModelState.IsValid)
            {
                if (createViewModel.Image == null)
                {
                    ViewBag.Message = "Introduisez une image";
                    return(View());
                }

                ApplicationUser user = await UserManager.FindByIdAsync(createViewModel.UserId);

                Resto resto = await CreateRestaurant(createViewModel.Name, createViewModel.PhoneNumber, user, null, createViewModel.Address, createViewModel.Image, createViewModel.Description);

                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
예제 #13
0
 public ActionResult AjouterRestaurant(Resto restau)
 {
     if (restau != null)
     {
         if (!ModelState.IsValid)
         {
             return(View("AjouterRestaurant"));
         }
         else
         {
             Dal dal = new Dal();
             if (dal.RestaurantExiste(restau.Name))
             {
                 ModelState.AddModelError("Name", "Ce nom de restaurant existe déjà");
                 return(View("AjouterRestaurant"));
             }
             dal.CreerNewRestaurant(restau.Name, restau.Telephone);
         }
     }
     return(RedirectToAction("Index"));
 }
예제 #14
0
        public async Task <ActionResult> AddChefToRestaurant(AddChefToRestaurantViewModel model)
        {
            var   selectedIds = model.getSelectedIds();
            Resto restoFound  = await DbManager.Restos.FirstOrDefaultAsync(resto => resto.Name == model.RestoName);


            if (restoFound != null)
            {
                var selectedUsers = from x in DbManager.Users
                                    where selectedIds.Contains(x.Id)
                                    select x;
                if (model.chefOrNotAdmin)
                {
                    restoFound.Chefs.Clear();
                }
                else
                {
                    restoFound.Administrators.Clear();
                }

                foreach (var user in selectedUsers)
                {
                    if (model.chefOrNotAdmin)
                    {
                        restoFound.Chefs.Add(user);
                    }
                    else
                    {
                        restoFound.Administrators.Add(user);
                    }
                }
                await DbManager.SaveChangesAsync();

                return(RedirectToAction("Edit", new { id = restoFound.Id }));
            }
            else
            {
                return(View("Error"));
            }
        }
예제 #15
0
        public ActionResult ModifierRestaurant(Resto restau)
        {
            if (restau != null)
            {
                if (!ModelState.IsValid)
                {
                    return(View("ModifierRestaurant"));
                }
                else
                {
                    Dal dal = new Dal();

                    /* if (dal.RestaurantExiste(restau.Name))
                     * {
                     *   ModelState.AddModelError("Name", "Ce nom de restaurant existe déjà");
                     *   return View("ModifierRestaurant");
                     * }*/
                    dal.ModifierRestaurant(restau.Id, restau.Name, restau.Telephone);
                }
            }
            return(RedirectToAction("Index"));
        }
        public ActionResult ModifierRestaurant(Resto resto)
        {
            // Vérification par rapport au résultat
            //
            //if (string.IsNullOrWhiteSpace(resto.Nom))
            //{
            //    ViewBag.MessageErreur = "Le nom du restaurant doit être rempli";
            //    return View(resto);
            //}

            // On regarde la propriété IsVAlid de l'objet ModelState qui contient l'état du modlèle et la validation des données associée.
            //if (!ModelState.IsValid)
            //{
            //    //ViewBag.MessageErreur = ModelState["Nom"].Errors[0].ErrorMessage;
            //    return View(resto);
            //}
            using (IDal dal = new Dal())
            {
                dal.ModifierRestaurant(resto.Id, resto.Nom, resto.Telephone);
                return(RedirectToAction("Index"));
            }
        }
예제 #17
0
        public async Task <ActionResult> AddChefToRestaurant(int RestoId, bool ChefOrNotAdmin)
        {
            ICollection <ApplicationUser> UserList = await UserManager.Users.ToListAsync();

            Resto restofound = await DbManager.Restos.FirstOrDefaultAsync(resto => resto.Id == RestoId);

            if (UserList != null && restofound != null)
            {
                var model = new AddChefToRestaurantViewModel()
                {
                    RestoName      = restofound.Name,
                    chefOrNotAdmin = ChefOrNotAdmin
                };

                foreach (var user in UserList)
                {
                    var userViewModel = new SelectUserRestoViewModel()
                    {
                        Id       = user.Id,
                        UserName = user.UserName,
                        Email    = user.Email,
                        Selected = true
                    };
                    if (restofound.Chefs.FirstOrDefault(m => m.Id == user.Id) == null && ChefOrNotAdmin)
                    {
                        userViewModel.Selected = false;
                    }
                    if (restofound.Administrators.FirstOrDefault(m => m.Id == user.Id) == null && !ChefOrNotAdmin)
                    {
                        userViewModel.Selected = false;
                    }
                    model.User.Add(userViewModel);
                }
                return(View(model));
            }
            return(View("Error"));
        }
예제 #18
0
 public IActionResult ModifierRestaurant(int?id)
 {
     if (id.HasValue)
     {
         //using (IDal dal = new Dal())
         //{
         //    Resto restaurant = dal.ObtientTousLesRestaurants().FirstOrDefault(r => r.Id == id.Value);
         //    if (restaurant == null)
         //        return View("Error");
         //    return View(restaurant);
         //}
         Resto restaurant = dal.ObtientTousLesRestaurants().FirstOrDefault(r => r.Id == id.Value);
         if (restaurant == null)
         {
             return(View("Error"));
         }
         return(View(restaurant));
     }
     else
     {
         return(StatusCode(404));
     }
     //return View("Error");
 }
예제 #19
0
        // Verify the payment has been executed.
        public async Task <ActionResult> CreatePaymentAccount(int Id)
        {
            Resto resto = await DbManager.Restos.FirstOrDefaultAsync(r => r.Id == Id);

            if (resto != null)
            {
                string Uri            = ConfigurationManager.AppSettings["BlueSnapGatewayBaseURL"] + "/vendors";
                var    httpWebRequest = (HttpWebRequest)WebRequest.Create(Uri);
                httpWebRequest.ContentType = "application/Json";
                httpWebRequest.Method      = "POST";

                // Configure basic Authentication
                string username = ConfigurationManager.AppSettings["BlueSnapUserName"];
                string password = ConfigurationManager.AppSettings["BlueSnapPassword"];

                string svcCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));

                httpWebRequest.Headers.Add("Authorization", "Basic " + svcCredentials);


                // Creates JSon for creating a new vendor
                string json = new BlueSnapPayment().BlueSnapAddVendorJson(resto);



                if (ConfigurationManager.AppSettings["ConsolDebug"] == "on")
                {
                    System.Diagnostics.Debug.WriteLine("Payment request sent to SaferPay (JSon):");
                    System.Diagnostics.Debug.WriteLine(json);
                }
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    await streamWriter.WriteAsync(json);

                    await streamWriter.FlushAsync();

                    streamWriter.Close();
                }

                // Send request to SaferPay server
                WebResponse httpWebResponse;
                try
                {
                    httpWebResponse = await httpWebRequest.GetResponseAsync();

                    string location = httpWebResponse.Headers["Location"]; // get the headers with the location ID in the request
                    if (location != null)
                    {
                        // the ID of the vendor created is respecting the following format: https://sandbox.bluesnap.com/services/2/vendors/19575974
                        // Collect the last num digits of the string;
                        var result = Regex.Match(location, @"\d+$").Value;
                        if (result.Length < 6)
                        {// Received ID sound not to be in a good format.
                            System.Diagnostics.Debug.WriteLine("Payment - Vendor ID received is not in a good format");
                            return(RedirectToAction(
                                       "Notification",
                                       "Home",
                                       new
                            {
                                Message = "Erreur lors de la création du compte de payement. Format d'ID retourné incorrecte",
                                Url = this.Url.Action("Index", "Restaurant", null)
                            }));
                        }
                        resto.Payment_BlueSnapPayoutVendorId = result;
                        System.Diagnostics.Debug.WriteLine("Payment - Vendor created on ID " + result);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Payment - Vendor could not be created");
                    }
                    return(RedirectToAction(
                               "Notification",
                               "Home",
                               new
                    {
                        Message = "Le compte de payement du restaurant a été créé avec success",
                        Url = this.Url.Action("Index", "Restaurant", null)
                    }));
                }
                catch (WebException we)
                {
                    // The rpayment request has been refused by SaferPay for technical reasons.
                    httpWebResponse = we.Response as HttpWebResponse;
                    SaferPayErrorMessage errorMessage;
                    using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                    {
                        var result = await streamReader.ReadToEndAsync();

                        errorMessage = JsonConvert.DeserializeObject <SaferPayErrorMessage>(result);
                        if (ConfigurationManager.AppSettings["ConsolDebug"] == "on")
                        {
                            System.Diagnostics.Debug.WriteLine("Payment request response from SaferPay (JSon) - ERROR Message:");
                            System.Diagnostics.Debug.WriteLine(errorMessage);
                        }
                    }
                }
            }
            return(RedirectToAction(
                       "Notification",
                       "Home",
                       new
            {
                Message = "Erreur lors de la création du compte de payement. Erreur de communication vers le serveur hôte",
                Url = this.Url.Action("Index", "Restaurant", null)
            }));
        }
예제 #20
0
        // GET: Order

        public async Task <ActionResult> Index(int RestoId)
        {
            Resto resto = await DbManager.Restos.FirstOrDefaultAsync(r => r.Id == RestoId);

            if (User.Identity.IsAuthenticated && resto != null)
            {
                string          UserId = User.Identity.GetUserId();
                ApplicationUser user   = await UserManager.FindByIdAsync(UserId);

                if (user == null)
                {
                    return(RedirectToAction("LogOff", "Account"));
                }
                Order order = await DbManager.Orders.FirstOrDefaultAsync(r => r.OrderOwner.Id == user.Id);

                if (order == null)
                {
                    // This user has no order started so far.
                    // Starting new order process from start
                    order = new Order
                    {
                        IsOrderCompleted = false,
                        OrderOpenTime    = DateTime.Now,
                        OrderOwner       = user
                    };
                    DbManager.Orders.Add(order);
                    await DbManager.SaveChangesAsync();

                    ICollection <ItemView> itemsView = await CreateItemsViewFromOrderAndRestoId(order, RestoId);

                    return(View(new OrderViewModels {
                        ListOfProposedItems = itemsView,
                        RestoId = RestoId,
                        Resto_Description = resto.Description,
                        Resto_Name = resto.Name,
                        OrderId = order.Id
                    }));
                }
                else
                {
                    if (order.IsOrderCompleted)
                    {
                        // This user has already an ongoing order
                        // Redirect on the edition of this order
                        return(RedirectToAction("ViewOngoinOrder", new { OrderId = order.Id }));
                    }
                    else
                    {
                        // This user has started an order previously but did not add anything in it.
                        // in case of an order has been created but not startd (no article in the list) then the order is recreated with a fresh new one;
                        if (order.OrderSlot == null)
                        {
                            order.IsOrderCompleted = false;
                            order.OrderOpenTime    = DateTime.Now;
                            order.OrderOwner       = user;


                            await DbManager.SaveChangesAsync();

                            ICollection <ItemView> itemsView = await CreateItemsViewFromOrderAndRestoId(order, RestoId);

                            return(View(new OrderViewModels
                            {
                                ListOfProposedItems = itemsView,
                                RestoId = resto.Id,
                                Resto_Description = resto.Description,
                                Resto_Name = resto.Name,
                                OrderId = order.Id
                            }));
                        }
                        else
                        {
                            // This user has started an order. Items are already in the basket.
                            // If the restaurant is the same of the order ... Continue progressing in the order
                            if (order.OrderSlot.Resto.Id == RestoId)
                            {
                                ICollection <ItemView> itemsView = await CreateItemsViewFromOrderAndRestoId(order, RestoId);

                                return(View(new OrderViewModels
                                {
                                    ListOfProposedItems = itemsView,
                                    RestoId = RestoId,
                                    Resto_Description = resto.Description,
                                    Resto_Name = resto.Name,
                                    OrderId = order.Id
                                }));
                            }
                            else
                            // Otherwise propose to the user to cancel ongoin order to start  a new one.
                            {
                                return(RedirectToAction("DeleteExestingOrder", new { OrderId = order.Id }));
                            }
                        }
                    }
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
        }
예제 #21
0
        //public async Task<ActionResult> Edit([Bind(Include = "Id,Name, Description,PhoneNumber,Address,SelectedSlotTimeId_1_Start,SelectedSlotTimeId_2_Start,SelectedSlotTimeId_1_Stop,SelectedSlotTimeId_2_Stop")] EditRestoViewModel editResto)
        public async Task <ActionResult> Edit(EditRestoViewModel editResto)

        {
            var resto = await DbManager.Restos.FirstAsync(r => r.Id == editResto.Id);

            if (resto == null)
            {
                return(HttpNotFound());
            }

            if (ModelState.IsValid)
            {
                Resto ModifiedResto = await DbManager.Restos.FindAsync(editResto.Id);

                if (ModifiedResto != null)
                {
                    try
                    {
                        ModifiedResto.Owner_DateOfBirth = DateTime.Parse(editResto.PaymentInfo_dob);
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", "Something failed.");
                        editResto.AdministratorsList = resto.Administrators.ToList();
                        editResto.menu      = resto.Menu;
                        editResto.ChefsList = resto.Chefs.ToList();
                        return(View(editResto));
                    }

                    ModifiedResto.Name                      = editResto.Name;
                    ModifiedResto.PhoneNumber               = editResto.PhoneNumber;
                    ModifiedResto.Address                   = editResto.Address;
                    ModifiedResto.Shop_Email                = editResto.PaymentInfo_Email;
                    ModifiedResto.Description               = editResto.Description;
                    ModifiedResto.Payment_BankAccountId     = editResto.PaymentInfo_bankAccountId;
                    ModifiedResto.Payment_BankAdress        = editResto.PaymentInfo_bankAddress;
                    ModifiedResto.Payment_BankCity          = editResto.PaymentInfo_bankCity;
                    ModifiedResto.Payment_BankId            = "";
                    ModifiedResto.Payment_BankName          = editResto.PaymentInfo_bankName;
                    ModifiedResto.Payment_BankZip           = editResto.PaymentInfo_bankZip;
                    ModifiedResto.Payment_IBAN              = editResto.PaymentInfo_bankAccountId;
                    ModifiedResto.Payment_NameOnAccount     = editResto.PaymentInfo_lastName;
                    ModifiedResto.Payment_SwiftBIC          = "";
                    ModifiedResto.Owner_Address             = editResto.PaymentInfo_address;
                    ModifiedResto.Owner_City                = editResto.PaymentInfo_city;
                    ModifiedResto.Payment_commissionPercent = int.Parse(editResto.PaymentInfo_commissionPercent);

                    ModifiedResto.Owner_email                 = editResto.PaymentInfo_Email;
                    ModifiedResto.Owner_FirstName             = editResto.PaymentInfo_firstName;
                    ModifiedResto.Owner_LastName              = editResto.PaymentInfo_lastName;
                    ModifiedResto.Owner_PassportNumber        = editResto.PaymentInfo_driverLicenseNumber;
                    ModifiedResto.Owner_PersonalIDNumber      = editResto.PaymentInfo_personalIdentificationNumber;
                    ModifiedResto.Owner_ZipCode               = editResto.PaymentInfo_zip;
                    ModifiedResto.Payment_SwiftBIC            = editResto.PaymentInfo_bankswiftBic;
                    ModifiedResto.Payment_minimalPayoutAmount = int.Parse(editResto.PaymentInfo_minimalPayoutAmount);

                    if (editResto.Image != null)
                    {
                        ModifiedResto.Image = new ImageHelper().ProcessFileToImage(editResto.Image);
                    }
                    await DbManager.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }

            ModelState.AddModelError("", "Something failed.");
            editResto.AdministratorsList = resto.Administrators.ToList();
            editResto.menu      = resto.Menu;
            editResto.ChefsList = resto.Chefs.ToList();
            return(View(editResto));
        }
예제 #22
0
        public static bool ValidarCPF(string Cpf)
        {
            int[] Multiplicador1 = new int[9] {
                10, 9, 8, 7, 6, 5, 4, 3, 2
            };
            int[] Multiplicador2 = new int[10] {
                11, 10, 9, 8, 7, 6, 5, 4, 3, 2
            };
            string TempCpf;
            string Digito;
            int    Soma;
            int    Resto;

            Cpf = Cpf.Trim();
            Cpf = Cpf.Replace(".", "").Replace("-", "");

            if (Cpf.Length != 11)
            {
                return(false);
            }

            TempCpf = Cpf.Substring(0, 9);
            Soma    = 0;

            for (int i = 0; i < 9; i++)
            {
                Soma += int.Parse(TempCpf[i].ToString()) * Multiplicador1[i];
            }

            Resto = Soma % 11;
            if (Resto < 2)
            {
                Resto = 0;
            }
            else
            {
                Resto = 11 - Resto;
            }

            Digito = Resto.ToString();

            TempCpf = TempCpf + Digito;

            Soma = 0;
            for (int i = 0; i < 10; i++)
            {
                Soma += int.Parse(TempCpf[i].ToString()) * Multiplicador2[i];
            }

            Resto = Soma % 11;
            if (Resto < 2)
            {
                Resto = 0;
            }
            else
            {
                Resto = 11 - Resto;
            }

            Digito = Digito + Resto.ToString();

            return(Cpf.EndsWith(Digito));
        }
예제 #23
0
        public async Task <ActionResult> CreateItemPost(CreateItemViewModel itemViewModel)
        {
            if (ModelState.IsValid)
            {
                Menu menu = await DbManager.Menus.FirstAsync(m => m.MenuId == itemViewModel.MenuId);

                if (menu != null)
                {
                    if (itemViewModel.Image != null)
                    {
                        Item item = new Item()
                        {
                            IsAvailable     = itemViewModel.IsAvailable,
                            Name            = itemViewModel.Name,
                            Description     = itemViewModel.Description ?? "",
                            Image           = new ImageHelper().ProcessFileToImage(itemViewModel.Image),
                            TypeOfFood      = itemViewModel.SelectedTypeOfFood,
                            AvailableSizes  = new List <SizedMeal>(),
                            HasSize         = itemViewModel.HasSize,
                            CanBeHotNotCold = itemViewModel.CanBeHotNotCold,
                            CanHaveSauce    = itemViewModel.CanHaveSauce,
                            CanHaveMeat     = itemViewModel.CanHaveMeat
                        };

                        if (item.TypeOfFood == TypeOfFood.Frites)
                        {
                            item.CanBeSalt = true;
                        }

                        // Check for input validation
                        decimal      UnitPrice;
                        NumberStyles style = NumberStyles.AllowLeadingWhite |
                                             NumberStyles.AllowTrailingWhite |
                                             NumberStyles.AllowDecimalPoint;
                        CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

                        //Item Price Validation / processing for size and not sized food.

                        if (itemViewModel.HasSize == false)
                        {
                            // "one size" case processing
                            if (decimal.TryParse(itemViewModel.UnitPrice, style, culture, out UnitPrice))
                            {
                                if (UnitPrice < 0 || UnitPrice >= 100)
                                {
                                    ModelState.AddModelError("UnitPrice", "Introduisez un prix valide entre 0 et 100 EUR");
                                    return(View(itemViewModel));
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("UnitPrice", "Introduisez un nombre valide");
                                return(View(itemViewModel));
                            }
                            // Data has been validated.
                            item.UnitPrice = UnitPrice;
                        }
                        else
                        {
                            // "Multiple size" case processing.
                            if (itemViewModel.SelectedSizedMeals.Count(r => r.Selected == true) == 0)
                            {
                                ModelState.AddModelError("SelectedSizedMeals", "Vous devez choisir au moins une taille");
                                return(View(itemViewModel));
                            }
                            foreach (var s_item in itemViewModel.SelectedSizedMeals)
                            {
                                if (s_item.Selected)
                                {
                                    if (decimal.TryParse(s_item.PriceText, style, culture, out UnitPrice))
                                    {
                                        if (UnitPrice < 0 || UnitPrice >= 100)
                                        {
                                            ModelState.AddModelError("MultiplePrice", "Introduisez un prix valide entre 0 et 100 EUR");
                                            return(View(itemViewModel));
                                        }
                                    }
                                    else
                                    {
                                        ModelState.AddModelError("MultiplePrice", "Introduisez un nombre valide");
                                        return(View(itemViewModel));
                                    }
                                    // Data has been validated.
                                    item.AvailableSizes.Add(new SizedMeal {
                                        Price = UnitPrice, MealSize = s_item.SizedMeal.MealSize
                                    });
                                }
                            }
                        }

                        if (item.Image == null)
                        {
                            ViewBag.Message = "Le format de l'image n'est pas correct";
                            return(View(itemViewModel));
                        }
                        else
                        {
                            ViewBag.Message = "File uploaded successfully";
                        }

                        menu.ItemList.Add(item);
                        await DbManager.SaveChangesAsync();

                        ViewBag.Message = "File uploaded successfully";
                        Resto resto = await DbManager.Restos.FirstOrDefaultAsync(m => m.Menu.MenuId == itemViewModel.MenuId);

                        if (resto != null)
                        {
                            return(RedirectToAction("Edit", "Restaurant", new { id = resto.Id }));
                        }
                        else
                        {
                            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                        }
                    }
                    else
                    {
                        ViewBag.Message = "Introduisez une image";
                    }
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
            }
            return(View(itemViewModel));
        }
예제 #24
0
        protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
        {
            if (!CommonService.CheckInternetConnection(activity.Context))
            {
                return(null);
            }
            key = @params[0].ToString();
            URL    url   = new URL(sqlquery_url);
            string query = "";

            if (key == "GetAll")
            {
                query = Resto.GetAllSQL();
            }
            if (key == "GetAllSearch")
            {
                query = Resto.GetAllSearchSQL(@params[1].ToString());
            }
            if (key == "GetRestoByID")
            {
                query = Resto.GetRestoByID(@params[1].ToString());
            }
            if (key == "GetAllCategory")
            {
                query = RestoCategoty.GetAllCategory();
            }
            if (key == "GetAllByCategory")
            {
                query = Resto.GetAllByCategory(@params[1].ToString());
            }
            if (key == "GetAllTopTen")
            {
                query = Resto.GetAllTopTenSQL();
            }
            string            data    = URLEncoder.Encode("query", "UTF-8") + "=" + URLEncoder.Encode(query, "UTF-8");
            HttpURLConnection urlConn = (HttpURLConnection)url.OpenConnection();

            urlConn.RequestMethod = "POST";
            urlConn.DoInput       = true;
            urlConn.DoOutput      = true;
            try
            {
                Stream         oStream = urlConn.OutputStream;
                BufferedWriter bw      = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8"));
                bw.Write(data);
                bw.Flush();
                bw.Close();
                oStream.Close();
                Stream                    iStream       = urlConn.InputStream;
                BufferedReader            br            = new BufferedReader(new InputStreamReader(iStream));
                System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
                string                    line          = "";
                while ((line = br.ReadLine()) != null)
                {
                    stringBuilder.Append(line + "\n");
                }
                urlConn.Disconnect();
                string result = stringBuilder.ToString().Trim();
                if (key == "GetAllCategory")
                {
                    m_result = RestoCategoty.GetListByServerResponse(result);
                }
                else
                {
                    m_result = Resto.GetListByServerResponse(result);
                }
                return(result);
            }
            catch (Java.IO.IOException ex)
            {
                //   Toast.MakeText(activity.GetContext(), ex.Message, ToastLength.Short);
            }
            return(null);
        }
        /// <summary>
        /// Verifica se o CNPJ é válido.
        /// </summary>
        /// <param name="cnpj">Dado a ser verificado.</param>
        /// <returns>TRUE se o CNPJ é válido ou FALSE caso seja inválido.</returns>
        public static bool Verificar(string cnpj)
        {
            //Limpa a formatação da String
            cnpj = cnpj.Trim();
            cnpj = cnpj.Replace(".", "").Replace("-", "").Replace("/", "");

            //Verifica se existem caracteres diferentes de números
            if (long.TryParse(cnpj, out long somenteNumero) == false)
            {
                return(false);
            }

            //Se o CNPJ não tem 14 digitos ele é inválido
            if (cnpj.Length != 14)
            {
                return(false);
            }

            //Cnpj válidos, porém não utilizados.
            if (cnpj == "00000000000000" ||
                cnpj == "11111111111111" ||
                cnpj == "22222222222222" ||
                cnpj == "33333333333333" ||
                cnpj == "44444444444444" ||
                cnpj == "55555555555555" ||
                cnpj == "66666666666666" ||
                cnpj == "77777777777777" ||
                cnpj == "88888888888888" ||
                cnpj == "99999999999999")
            {
                return(false);
            }

            int[] Multiplicador1 = new int[12] {
                5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2
            };
            int[] Multiplicador2 = new int[13] {
                6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2
            };
            int    Soma, Resto;
            string DigitoVerificador, DigitosCnpj;

            //Gera uma string sem os dígitos verificadores
            DigitosCnpj = cnpj.Substring(0, 12);

            Soma = 0;
            for (int i = 0; i < 12; i++)
            {
                Soma += int.Parse(DigitosCnpj[i].ToString()) * Multiplicador1[i];
            }

            Resto = (Soma % 11);
            if (Resto < 2)
            {
                Resto = 0;
            }
            else
            {
                Resto = 11 - Resto;
            }

            DigitoVerificador = Resto.ToString();

            DigitosCnpj = DigitosCnpj + DigitoVerificador;
            Soma        = 0;
            for (int i = 0; i < 13; i++)
            {
                Soma += int.Parse(DigitosCnpj[i].ToString()) * Multiplicador2[i];
            }

            Resto = (Soma % 11);
            if (Resto < 2)
            {
                Resto = 0;
            }
            else
            {
                Resto = 11 - Resto;
            }

            DigitoVerificador += Resto.ToString();

            //Compara se DigitoVerificador é igual ao foi recebido como parâmetro pelo método e retorna um booleano
            return(cnpj.EndsWith(DigitoVerificador));
        }
예제 #26
0
 public async Task DeleteResto(Resto resto)
 {
     _unitOfWork.Restos.Remove(resto);
     await _unitOfWork.CommitAsync();
 }
예제 #27
0
        public async Task <Resto> CreateResto(Resto resto)
        {
            await _unitOfWork.Restos.AddAsync(resto);

            return(resto);
        }
예제 #28
0
        /// <summary>
        /// Verifica se o CPF é válido.
        /// </summary>
        /// <param name="cpf">Dado a ser verificado.</param>
        /// <returns>TRUE se o CPF é válido ou FALSE caso ele seja inválido.</returns>
        public static bool Verificar(string cpf)
        {
            //Limpa a formatação da String
            cpf.Trim();
            cpf = cpf.Replace(".", "").Replace("-", "");

            if (long.TryParse(cpf, out long somenteNumero) == false)
            {
                return(false);
            }

            //Se o CPF não tem 11 digitos ele é inválido
            if (cpf.Length != 11)
            {
                return(false);
            }

            //Cpf válidos, porém não utilizados.
            if (cpf == "00000000000000" ||
                cpf == "11111111111111" ||
                cpf == "22222222222222" ||
                cpf == "33333333333333" ||
                cpf == "44444444444444" ||
                cpf == "55555555555555" ||
                cpf == "66666666666666" ||
                cpf == "77777777777777" ||
                cpf == "88888888888888" ||
                cpf == "99999999999999")
            {
                return(false);
            }

            int[] Multiplicador1 = new int[9] {
                10, 9, 8, 7, 6, 5, 4, 3, 2
            };

            int[] Multiplicador2 = new int[10] {
                11, 10, 9, 8, 7, 6, 5, 4, 3, 2
            };

            string DigitosCpf, DigitoVerificador;
            int    Soma = 0, Resto;

            //Gera uma string sem os dígitos verificadores
            DigitosCpf = cpf.Substring(0, 9);

            for (int i = 0; i < 9; i++)
            {
                Soma += int.Parse(DigitosCpf[i].ToString()) * Multiplicador1[i];
            }

            Resto = Soma % 11;

            if (Resto < 2)
            {
                Resto = 0;
            }
            else
            {
                Resto = 11 - Resto;
            }

            DigitoVerificador = Resto.ToString();

            DigitosCpf += DigitoVerificador;

            Soma = 0;

            for (int i = 0; i < 10; i++)
            {
                Soma += int.Parse(DigitosCpf[i].ToString()) * Multiplicador2[i];
            }

            Resto = Soma % 11;

            if (Resto < 2)
            {
                Resto = 0;
            }
            else
            {
                Resto = 11 - Resto;
            }

            DigitoVerificador += Resto.ToString();

            //Compara se DigitoVerificador é igual ao foi recebido como parâmetro pelo método e retorna um booleano
            return(cpf.EndsWith(DigitoVerificador));
        }
예제 #29
0
        public async Task <IHttpActionResult> Get(int id)
        {
            Resto resto = await db.Restos.FirstOrDefaultAsync(v => v.Id == id);

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

            var userName = User.Identity.GetUserName();
            var user     = await UserManager.FindByNameAsync(userName);

            if (user == null)
            {
                return(BadRequest("User Authentication failed"));
            }

            ListRestoAPIModel restoAPI = new ListRestoAPIModel
            {
                ResponseHeader = new ResponseHeaderAPIModel {
                    SpecVersion = ConfigurationManager.AppSettings["CurrentAPIVersion"]
                },
                Restos = new List <RestoAPIModel>
                {
                    new RestoAPIModel
                    {
                        Address     = resto.Address,
                        Description = resto.Description,
                        Id          = resto.Id,
                        Image       = resto.Image,
                        Name        = resto.Name,
                        PhoneNumber = resto.PhoneNumber,
                        Menu        = new MenuAPIModel
                        {
                            MenuId   = resto.Menu.MenuId,
                            Name     = resto.Menu.Name,
                            ItemList = new List <ItemAPIModel>()
                        }
                    }
                }
            };

            foreach (var item in resto.Menu.ItemList)
            {
                if (item.DeletedOn == null)
                {
                    ItemAPIModel newItem = new ItemAPIModel
                    {
                        Name            = item.Name,
                        Brand           = item.Brand,
                        UnitPrice       = item.UnitPrice,
                        Description     = item.Description,
                        HasSize         = item.HasSize,
                        ItemId          = item.ItemId,
                        CanBeHotNotCold = item.CanBeHotNotCold,
                        CanBeSalt       = item.CanBeSalt,
                        CanHaveMeat     = item.CanHaveMeat,
                        CanHaveSauce    = item.CanHaveSauce,
                        TypeOfFood      = item.TypeOfFood,
                        AvailableSizes  = new List <SizedMeal>()
                    };
                    foreach (var itemsize in item.AvailableSizes)
                    {
                        newItem.AvailableSizes.Add(new SizedMeal
                        {
                            MealSize = itemsize.MealSize,
                            Id       = itemsize.Id,
                            Price    = itemsize.Price
                        });
                    }
                    restoAPI.Restos[0].Menu.ItemList.Add(newItem);
                }
            }
            return(Ok(restoAPI));
        }