コード例 #1
0
        public IHttpActionResult Create(CreateRestaurant model)
        {
            IHttpActionResult httpActionResult;
            ErrorsModel       errors = new ErrorsModel();

            if (string.IsNullOrEmpty(model.name))
            {
                errors.Add("Tên nhà hàng là trường bắt buộc");
            }

            if (errors.Errors.Count == 0)
            {
                Restaurants t = new Restaurants();
                t.id      = model.id;
                t.name    = model.name;
                t.address = model.address;
                t.type    = model.type;

                t = _db.Restaurants.Add(t);

                this._db.SaveChanges();

                RestaurantModel viewModel = new RestaurantModel(t);

                httpActionResult = Ok(viewModel);
            }
            else
            {
                httpActionResult = new ErrorActionResult(Request, System.Net.HttpStatusCode.BadRequest, errors);
            }

            return(httpActionResult);
        }
コード例 #2
0
ファイル: SearchUtility.cs プロジェクト: pashkov/Spontaneous
        /// <summary>
        /// Search GeneralDish in DB
        /// </summary>
        /// <param name="searchCount"> Max search results </param>
        /// <param name="searchText"> Search text </param>
        /// <returns></returns>
        public List<GeneralDish> SearchGeneralDish(int searchCount = 20, string searchText = null)
        {
            Stopwatch stop = Stopwatch.StartNew();
            var queryCollection = Query.NE("IsDeleted", true);
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<GeneralDish> basicData =
                                            new MongoEntityRepositoryBase<GeneralDish>(restaurantsDb.DB);

                if (searchText != null)
                {
                    var queryLongDesc = Query.Matches("Dish.Name", BsonRegularExpression.Create(new Regex(searchText, RegexOptions.IgnoreCase)));
                    var queryComName = Query.Matches("Dish.OverrideIngredients[0].ComName.LocalizedList.Value", BsonRegularExpression.Create(new Regex(searchText, RegexOptions.IgnoreCase)));
                    var queryCollectionor = Query.Or(queryLongDesc, queryComName);
                    queryCollection = Query.And(
                        queryCollection,
                        queryCollectionor
                    );

                    log.DebugFormat("SearchGeneralDish query exec={0}, searchText={1}, searchCount={2}.", stop.ElapsedMilliseconds, searchText, searchCount);
                }
                var allGeneralDishes = basicData.FindAs(queryCollection, searchCount);

                //List<Ingredient> ingredientsList = allAllIngredients.OrderBy(i => i.USDA_NDB_No).ToList();
                List<GeneralDish> generalDishList = allGeneralDishes.ToList();

                log.DebugFormat("SearchGeneralDish exec={0}, searchText={1}, searchCount={2}.", stop.ElapsedMilliseconds, searchText, searchCount);
                return generalDishList;
            }
        }
コード例 #3
0
        public IHttpActionResult Update(UpdateRestaurant model, string id)
        {
            IHttpActionResult httpActionResult;
            ErrorsModel       errors = new ErrorsModel();

            Restaurants gv = this._db.Restaurants.FirstOrDefault(x => x.id == id);

            if (gv == null)
            {
                errors.Add("Nhà hàng này không tồn tại hoặc rỗng");

                httpActionResult = new ErrorActionResult(Request, System.Net.HttpStatusCode.NotFound, errors);
            }
            else
            {
                gv.name    = model.name ?? model.name;
                gv.address = model.address ?? model.address;
                gv.type    = model.type ?? model.type;

                this._db.Entry(gv).State = System.Data.Entity.EntityState.Modified;

                this._db.SaveChanges();

                httpActionResult = Ok(new RestaurantModel(gv));
            }

            return(httpActionResult);
        }
コード例 #4
0
        // Taking in phone number to draw data for the exact restaurant. user rating, note, and liked is to fill constructor.
        //rest is filled from the data pulled from the API call.
        public IActionResult AddRestaurant(string location, string id, string name, string zip, int userRating, string note)
        {
            string user = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            bool   liked;

            if (userRating >= 3)
            {
                liked = true;
            }
            else
            {
                liked = false;
            }
            if (note == null)
            {
                note = "N/A";
            }
            Restaurants save = new Restaurants(user, id, name, userRating, note, zip, liked);

            //Exclude a restaurant that already exist in restaurants table
            for (int i = 0; i < _context.Restaurants.ToList().Count; i++)
            {
                if (_context.Restaurants.ToList()[i].PlaceId == id && _context.Restaurants.ToList()[i].UserId == user)
                {
                    return(RedirectToAction("Discover", new { location }));
                }
            }

            //Save those changes
            _context.Restaurants.Add(save);
            _context.SaveChanges();

            return(RedirectToAction("Discover", new { location }));
        }
コード例 #5
0
        public ActionResult Details(int id)
        {
            Restaurants thisRestaurants = _db.Restaurants.FirstOrDefault(restaurants => restaurants.RestaurantsId == id);

            Console.WriteLine(thisRestaurants);
            return(View(thisRestaurants));
        }
コード例 #6
0
        public IActionResult EditRestaurant(int id, int userRating, string notes)
        {
            Restaurants updated = _context.Restaurants.Find(id);

            updated.UserRating = userRating;
            if (userRating >= 3)
            {
                updated.Liked = true;
            }
            else
            {
                updated.Liked = false;
            }
            if (notes == null)
            {
                updated.Notes = "N/A";
            }
            else
            {
                updated.Notes = notes;
            }

            _context.Entry(updated).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            _context.Update(updated);
            _context.SaveChanges();

            return(RedirectToAction("Favorites"));
        }
コード例 #7
0
        public Restaurant PickRandom()
        {
            Random rand   = new Random();
            int    toSkip = rand.Next(0, this.Restaurants.Count());

            return(Restaurants.Skip(toSkip).Take(1).First());
        }
コード例 #8
0
        public void Equals_ReturnsTrueIfDescriptionsAreTheSame_Item()
        {
            Restaurants firstItem  = new Restaurants("Bob", 1);
            Restaurants secondItem = new Restaurants("Bob", 1);

            Assert.AreEqual(firstItem, secondItem);
        }
コード例 #9
0
        public async Task <string> SaveRestaurantDetails()
        {
            String fileBase64 = null;
            string root       = HttpContext.Current.Server.MapPath("~/App_Data");
            var    provider   = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // get file and convert to base64
                foreach (MultipartFileData file in provider.FileData)
                {
                    var    path  = file.LocalFileName;
                    Byte[] bytes = File.ReadAllBytes(path);
                    fileBase64 = Convert.ToBase64String(bytes);

                    File.Delete(path);
                }

                Restaurants restaurant = SaveRestaurantOperations(fileBase64, provider);

                return(JsonConvert.SerializeObject(restaurant));
            }
            catch (Exception ex)
            {
                _logger.Log("SaveRestaurantDetails_Exception", ex.Message);
                return(JsonConvert.SerializeObject(null));
            }
        }
コード例 #10
0
        public static async Task RunAsync()
        {
            client.BaseAddress = new Uri("http://localhost:49790/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {
                var restaurant = new Restaurants {
                    Name = "", Location = "", ItemType = "", ImagePath = ""
                };
                var url = await Post(restaurant);

                //Get
                restaurant = await Get(url.PathAndQuery);

                Console.WriteLine($"RESTAURANT", restaurant);
                //Update
                restaurant.ItemType = "Chicken wings, Burgers";
                await Put(restaurant.Id, restaurant);

                Console.WriteLine($"");
                //Delete
                var status = await Delete(restaurant.Id);

                Console.WriteLine($"Deleted (HTTP Status = {(int)status})");
            }
            catch (Exception error)
            {
                throw new Exception("Error" + error.Message);
            }
        }
コード例 #11
0
        public static void Initialize(MrDeliveryContext context)
        {
            if (context.Restaurants.Any())
            {
                return;
            }
            var resturants = new Restaurants[]
            {
                new Restaurants()
                {
                    Name      = "McDonald",
                    Location  = "Bryanston",
                    ItemType  = "Chicken, Chicken Wings, Burgers, Breakfast, Salad",
                    ImagePath = "http://catalogbaseurltobereplaced/images/products/1.png"
                },
                new Restaurants()
                {
                    Name      = "Spurs",
                    Location  = "Bryanston",
                    ItemType  = "American, Chicken Wings, Burgers, Seafood",
                    ImagePath = "http://catalogbaseurltobereplaced/images/products/1.png"
                }
            };

            foreach (var item in resturants)
            {
                context.Restaurants.Add(item);
            }
            context.SaveChanges();
        }
コード例 #12
0
        public void PartialUpdateRestaurant_NonExistingID_Fail()
        {
            Restaurants.Add(new Restaurant {
                Id = 1, CreatedBy = 101, UpdatedBy = 101, Cuisine = Cuisines[0], Name = "Restaurant one"
            });
            Restaurants.Add(new Restaurant {
                Id = 2, CreatedBy = 102, UpdatedBy = 102, Cuisine = Cuisines[1], Name = "Restaurant Two"
            });
            var restToUpdate = new UpdateRestaurantRequestModel
            {
                UserId       = 103,
                RestaurantId = 200,
                Name         = "New Name"
            };
            var expectedResponse = new UpdateRestaurantResponseModel {
                WasSucessfull = false
            };

            var updateRestTran = new PartialUpdateRestaurantTransaction(Repo, Log, restToUpdate);

            //act
            updateRestTran.Execute();
            var actualResponse = updateRestTran.Response;

            //assert
            Assert.AreEqual(expectedResponse.WasSucessfull, actualResponse.WasSucessfull, "Invalid execution status");
        }
コード例 #13
0
 public GestionRestaurant(Restaurants restaurant)
 {
     InitializeComponent();
     this.restaurant = restaurant;
     modifView = new ModifViewModel(restaurant);
     this.DataContext = modifView;
 }
コード例 #14
0
 public void LoadRestaurants()
 {
     Restaurants.Add(new Restaurant(1, "Ilden", "Roskilde", 50));
     Restaurants.Add(new Restaurant(2, "Jensen's Bøfhus", "Holbæk", 60));
     Restaurants.Add(new Restaurant(3, "Karma Sushi", "København", 70));
     Restaurants.Add(new Restaurant(4, "Siang Jiang", "Slagelse", 50));
 }
コード例 #15
0
        public IHttpActionResult InsertMaintaince(MainatainceTransferModel data)
        {
            try
            {
                using (Restaurants context = new Restaurants())
                {
                    data.Master.ForEach(x =>
                    {
                        x.B_Sync   = true;
                        x.SyncDate = DateTime.Now;
                    });
                    context.MNTNC_REQ.AddRange(data.Master);
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                return(Ok(new AjaxResponse <object>()
                {
                    Success = false, ErrorMessage = ex.GetLastException()
                }));
            }

            return(Ok(new AjaxResponse <object>()
            {
                Success = true, SuccessMessage = "Successfully"
            }));
        }
コード例 #16
0
ファイル: Restaurant.cs プロジェクト: loshvitalik/DeliveryLab
 public Restaurant(string name, User owner)
 {
     Id      = Restaurants.Any() ? Restaurants.Last().Id + 1 : 0;
     Name    = name;
     OwnerId = owner.Id;
     Rating  = 0;
 }
コード例 #17
0
        private static void DeleteDuplicateUserIncomes(UserIncomeModel data)
        {
            using (var tranasactionScope = new TransactionScope())
            {
                using (var context = new Restaurants())
                {
                    var branch = data.Master.Select(x => x.Branch_No).FirstOrDefault();
                    //var date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    var allEntities = context.User_Income
                                      .Where(x => x.Branch_No == branch)
                                      .ToList();

                    var similarEntities = data.Master.Intersect(allEntities,
                                                                new LambdaComparer <User_Income>(
                                                                    (x, y) => x.Branch_No == y.Branch_No && x.Income_Date == y.Income_Date &&
                                                                    x.User_ID == y.User_ID)).ToList();
                    foreach (var entity in similarEntities)
                    {
                        data.Master.Remove(entity);
                    }
                    EFBatchOperation.For(context, context.User_Income).InsertAll(data.Master);
                    tranasactionScope.Complete();
                }
            }
        }
コード例 #18
0
        public async Task <IActionResult> AddFile(IFormFileCollection uploads, string id)
        {
            if (uploads != null)
            {
                foreach (var uploadedFile in uploads)
                {
                    if (!Directory.Exists(_appEnvironment.WebRootPath + "/Fotos/" + id))
                    {
                        Directory.CreateDirectory(_appEnvironment.WebRootPath + "/Fotos/" + id);
                    }
                    string path = "/Fotos/" + id + "/" + Path.GetRandomFileName() + uploadedFile.FileName;


                    // сохраняем файл в папку Files в каталоге wwwroot
                    using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
                    {
                        await uploadedFile.CopyToAsync(fileStream);
                    }
                    Restaurants restaurant = await _context.RestaurantsList.FirstOrDefaultAsync(u => u.ID == id);

                    Pictures pic = new Pictures {
                        Name = uploadedFile.FileName, PathToImg = path, RestaurantID = id
                    };
                    _context.TablesImages.Add(pic);
                    restaurant.pictures.Add(pic);
                }
                _context.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
コード例 #19
0
 public IHttpActionResult TestDb()
 {
     using (var context = new Restaurants())
     {
         try
         {
             var x = context.Areas.Count();
             return(Ok(new AjaxResponse <object>()
             {
                 Success = true, SuccessMessage = "connected"
             }));
         }
         catch (Exception ex)
         {
             if (ex.InnerException != null)
             {
                 return(Ok(new AjaxResponse <object>()
                 {
                     Success = false, ErrorMessage = ex.InnerException.Message
                 }));
             }
             return(Ok(new AjaxResponse <object>()
             {
                 Success = false, ErrorMessage = ex.Message
             }));
         }
     }
 }
コード例 #20
0
        public void CompleteUpdateRestaurant_ValidIDUpdateCuisine_Succeed()
        {
            Restaurants.Add(new Restaurant {
                Id = 1, CreatedBy = 101, UpdatedBy = 101, Cuisine = Cuisines[0], Name = "Restaurant one"
            });
            Restaurants.Add(new Restaurant {
                Id = 2, CreatedBy = 102, UpdatedBy = 102, Cuisine = Cuisines[1], Name = "Restaurant Two"
            });
            var expectedID          = 2;
            var expectedName        = "Restaurant Two";
            var expectedCuisine     = Cuisines[2].Id;
            var expectedCreatedById = 102;
            var expectedUpdatedById = 103;
            var restToUpdate        = new UpdateRestaurantRequestModel
            {
                UserId       = 103,
                RestaurantId = expectedID,
                Name         = expectedName,
                CuisineId    = expectedCuisine
            };
            var updateRestTran = new CompleteUpdateRestaurantTransaction(Repo, Log, restToUpdate);

            var expectedResponse = new UpdateRestaurantResponseModel {
                WasSucessfull = true
            };

            //act
            updateRestTran.Execute();
            var actualResponse = updateRestTran.Response;

            //assert
            Assert.AreEqual(expectedResponse.WasSucessfull, actualResponse.WasSucessfull, "Invalid execution status");

            ValidateRestUpdate(expectedID, expectedName, expectedCuisine, expectedCreatedById, expectedUpdatedById, restToUpdate);
        }
コード例 #21
0
        public ActionResult <List <Restaurants> > postRestaurants(Restaurants restaurant)
        {
            var restaurants = db.Restaurant.Add(restaurant);

            db.SaveChanges();
            return(Ok());
        }
コード例 #22
0
        public void EnsureSeedDataExists()
        {
            if (Restaurants.Any())
            {
                return;
            }

            var sampleRestaurants = new List <Restaurant>
            {
                new Restaurant {
                    Name = "Scott's Pizza", Location = "Maryland", Cuisine = CuisineType.Italian
                },
                new Restaurant {
                    Name = "Joe's Mexican Restaurant", Location = "Texas", Cuisine = CuisineType.Mexican
                },
                new Restaurant {
                    Name = "Jeffrey's Lounge", Location = "Manitoba", Cuisine = CuisineType.Comfort
                },
                new Restaurant {
                    Name = "Clay Oven", Location = "Manitoba", Cuisine = CuisineType.Indian
                }
            };

            Restaurants.AddRange(sampleRestaurants);
            SaveChanges();
        }
コード例 #23
0
        public ActionResult NewRestaurant(string name, int cuisineId)
        {
            Restaurants newRestaurant = new Restaurants(name, cuisineId);

            newRestaurant.Save();
            return(RedirectToAction("Index"));
        }
コード例 #24
0
        public async Task <IActionResult> PutRestaurants([FromRoute] int id, [FromBody] Restaurants restaurants)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != restaurants.Id)
            {
                return(BadRequest());
            }

            _context.Entry(restaurants).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RestaurantsExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #25
0
        public async Task <IHttpActionResult> PutRestaurants(string name, Restaurants restaurants)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (name != restaurants.RestaurantName)
            {
                return(BadRequest());
            }

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

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                string id = null;
                if (!RestaurantsExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
コード例 #26
0
        public DefaultMenuRestaurant GetDefaultMenuRestaurantByName(string restName)
        {
            log.DebugFormat("[GetDefaultMenuRestaurantByName] restName={0}.", restName);
            var queryCollection = Query.NE("IsDeleted", true);
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<DefaultMenuRestaurant> basicData =
                                            new MongoEntityRepositoryBase<DefaultMenuRestaurant>(restaurantsDb.DB);

                if (restName != null)
                {
                    var queryName = Query.Matches("Name", BsonRegularExpression.Create(new Regex(restName, RegexOptions.IgnoreCase)));
                    queryCollection = Query.And(
                        queryCollection,
                        queryName
                    );

                    log.DebugFormat("GetDefaultMenuRestaurantByName restName={0}.", restName);
                }
                var foundDefaultMenuRests = basicData.FindAs(queryCollection);

                //List<Ingredient> ingredientsList = allAllIngredients.OrderBy(i => i.USDA_NDB_No).ToList();
                List<DefaultMenuRestaurant> defaultMenuRestsList = foundDefaultMenuRests.ToList();
                if (defaultMenuRestsList != null && defaultMenuRestsList.Count > 0) return defaultMenuRestsList[0];
                return null;
            }
        }
コード例 #27
0
        protected override void Seed(ASPNetDay4Practice.Models.DataContext context)
        {
            var resturant = new Restaurants[]
            {
                new Restaurants {
                    Name = "Lubys", Address = "1234 Somewhere", PriceRange = "$$"
                },
                new Restaurants {
                    Name = "Olive Garden", Address = "453 Nowhere Dr", PriceRange = "$$"
                },
                new Restaurants {
                    Name = "Strip House", Address = "Downtown St", PriceRange = "$$$$"
                }
            };

            context.Restaurant.AddOrUpdate(r => r.Name, resturant);


            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
コード例 #28
0
        public ActionResult AddToUserList(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Restaurants restaurants = db.restaurants.Find(id);

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

            UserManager <ApplicationUser> UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
            ApplicationUser currentUser = UserManager.FindById(User.Identity.GetUserId());

            UserList newlist = new UserList();

            newlist.Title          = restaurants.Title;
            newlist.Description    = restaurants.Description;
            newlist.Link           = restaurants.Link;
            newlist.Location       = restaurants.Location;
            newlist.ListCategoryId = 1;  //have to use # be sure to confirm the numbers in List Categories.
            newlist.UserName       = currentUser;
            db.UserLists.Add(newlist);

            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
コード例 #29
0
        public OrdersDataGenerator()
        {
            Regions      = GetRegionFaker(GetRegions()).Generate(5);
            Temperatures = GetTemperatureFaker(GetTemperatures()).Generate(4);
            Addresses    = GetAddressFaker(GetCities(), GetStreets(), GetZipCodes(), Regions.Select(x => x.RegionId)).Generate(20);
            Restaurants  = GetRestaurantFaker(GetRestaurants(), Addresses.Select(x => x.AddressId)).Generate(10);
            Menus        = GetMenuFaker(GetMenus(), Restaurants.Select(x => x.RestaurantId)).Generate(3);
            MenuItems    = GetMenuItemFaker(GetMenuItems(), Temperatures.Select(x => x.TemperatureId),
                                            Menus.Select(x => x.MenuId)).Generate(20);
            Customers      = GetCustomerFaker(GetFirstNames(), GetLastNames(), Addresses.Select(x => x.AddressId)).Generate(5);
            Ingredients    = GetIngredientFaker(GetIngredients(), Temperatures.Select(x => x.TemperatureId)).Generate(15);
            InventoryItems = GetInventoryItemFaker(Ingredients.Select(x => x.IngredientId),
                                                   Restaurants.Select(x => x.RestaurantId)).Generate(20);
            MenuItemIngredients = GetMenuItemIngredientFaker(MenuItems.Select(x => x.MenuItemId),
                                                             Ingredients.Select(x => x.IngredientId)).Generate(50);

            var shelves = new List <ShelfEntity>();

            for (int i = 0; i < 3; i++)
            {
                shelves.AddRange(GetShelfFaker(Temperatures.Select(x => x.TemperatureId),
                                               Restaurants.Select(x => x.RestaurantId)).Generate(1));
            }
            shelves.AddRange(GetShelfFaker(Temperatures.Select(x => x.TemperatureId),
                                           Restaurants.Select(x => x.RestaurantId), true).Generate(1));

            Shelves = shelves;

            Couriers = GetCourierFaker(GetFirstNames(), GetLastNames(), Addresses.Select(x => x.AddressId)).Generate(20);
            Orders   = GetOrderFaker(Customers.Select(x => x.CustomerId),
                                     Restaurants.Select(x => x.RestaurantId), Addresses.Select(x => x.AddressId),
                                     Couriers.Select(x => x.CourierId)).Generate(10);
            OrderItems = GetOrderItemFaker(MenuItems.Select(x => x.MenuItemId),
                                           Orders.Select(x => x.OrderId), Shelves.Select(x => x.ShelfId)).Generate(20);
        }
コード例 #30
0
        public ActionResult DeleteConfirmed(int id)
        {
            Restaurants restaurants = crud.GetById(id);

            crud.RemoveRestaurant(restaurants);
            return(RedirectToAction("Index"));
        }
コード例 #31
0
        public static void DeleteAccount(User userToDelete)
        {
            if (userToDelete.Group == Type.Restaurant)
            {
                foreach (var r in Restaurants.Where(r => r.OwnerId == userToDelete.Id).ToArray())
                {
                    foreach (var d in Dishes.Where(d => d.RestId == r.Id).ToArray())
                    {
                        Dishes.Remove(d);
                    }
                    Restaurants.Remove(r);
                }
            }

            if (userToDelete.Id == CurrentUser.Id)
            {
                LogOut();
            }
            Users.Remove(Users.First(u => u.Id == userToDelete.Id));
            foreach (var i in Orders.Items.Where(i => i.UserId == userToDelete.Id))
            {
                Orders.Items.Remove(i);
            }
            SaveSystem.SaveAll();
        }
コード例 #32
0
ファイル: MenuHandler.cs プロジェクト: jirkaceska/C_sharp
        private void Search(string str)
        {
            selectedDay        = (FlagDayOfWeek) ~0;
            selectedRestaurant = (Restaurants) ~0;

            Display((dayMenu) => dayMenu.Contains(str));
        }
コード例 #33
0
 public RestaurantModel(Restaurants t)
 {
     this.id      = t.id;
     this.name    = t.name;
     this.address = t.address;
     this.type    = t.type;
 }
コード例 #34
0
 public ModifViewModel(Restaurants restaurant)
 {
     this.id = restaurant.Id.ToString();
     this.str_nom = restaurant.Nom;
     this.str_rue = restaurant.Rue;
     this.str_ville = restaurant.Ville;
     this.active = restaurant.Active;
     this.str_cp = restaurant.CP;
 }
コード例 #35
0
 public void UpdateDefaultMenuRestaurant(DefaultMenuRestaurant rest)
 {
     log.DebugFormat("[UpdateDefaultMenuRestaurant] CuisineMap={0}.", rest.Name);
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<DefaultMenuRestaurant> basicData =
                       new MongoEntityRepositoryBase<DefaultMenuRestaurant>(restaurantsDb.DB);
         basicData.Update(rest);
     }
 }
コード例 #36
0
 public static void DeleteUserMealProfile(string id)
 {
     log.DebugFormat("[DeleteUserMealProfile] id={0}.", id);
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<UserMealProfile> basicData =
                       new MongoEntityRepositoryBase<UserMealProfile>(restaurantsDb.DB);
         basicData.Delete(ObjectId.Parse(id));
     }
 }
コード例 #37
0
 public void DeleteOperatorMap(string id)
 {
     log.InfoFormat("[DeleteOperatorMap] id={0}.", id);
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<OperatorMap> basicData =
                       new MongoEntityRepositoryBase<OperatorMap>(restaurantsDb.DB);
         basicData.Delete(ObjectId.Parse(id));
     }
 }
コード例 #38
0
        public string AddNewOperatorMap(OperatorMap map)
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<OperatorMap> basicData =
                    new MongoEntityRepositoryBase<OperatorMap>(restaurantsDb.DB);

                basicData.Add(map);
                return map.Id.ToString();
            }
        }
コード例 #39
0
 public DefaultMenuRestaurant GetDefaultMenuRestaurantById(string id)
 {
     log.DebugFormat("[GetDefaultMenuRestaurantById] id={0}.", id);
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<DefaultMenuRestaurant> basicData =
                       new MongoEntityRepositoryBase<DefaultMenuRestaurant>(restaurantsDb.DB);
         var defaultRest = basicData.GetSingle(ObjectId.Parse(id));
         return defaultRest;
     }
 }
コード例 #40
0
//=====================================================================================
        public string AddNewDefaultMenuRestaurant(DefaultMenuRestaurant rest)
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<DefaultMenuRestaurant> basicData =
                    new MongoEntityRepositoryBase<DefaultMenuRestaurant>(restaurantsDb.DB);

                basicData.Add(rest);
                return rest.Id.ToString();
            }
        }
コード例 #41
0
ファイル: UserUtilities.cs プロジェクト: pashkov/Spontaneous
 public List<SpontaneousUserModel> GetAllUsersData(bool withMenu = true)
 {
     log.DebugFormat("[GetAllUsersData].");
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<SpontaneousUserModel> basicData =
                       new MongoEntityRepositoryBase<SpontaneousUserModel>(restaurantsDb.DB);
         var allRestaurants = basicData.GetAll();
         List<SpontaneousUserModel> selected = allRestaurants.ToList();
         return selected;
     }
 }
コード例 #42
0
 public static List<UserMealProfile> GetAllUserMealProfiles()
 {
     log.DebugFormat("[GetAllUserMealProfiles].");
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<UserMealProfile> basicData =
                       new MongoEntityRepositoryBase<UserMealProfile>(restaurantsDb.DB);
         var allRestaurants = basicData.GetAll();
         List<UserMealProfile> selected = allRestaurants.ToList();
         return selected;
     }
 }
コード例 #43
0
        public static string AddUserMealProfileToDB(UserMealProfile userMealProfile)
        {
            log.DebugFormat("[AddUserMealProfileToDB] restaurant={0}.", userMealProfile.ToString());
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<UserMealProfile> basicData =
                              new MongoEntityRepositoryBase<UserMealProfile>(restaurantsDb.DB);

                userMealProfile.CreatedAt = DateTime.UtcNow;
                basicData.Add(userMealProfile);
                return userMealProfile.Id.ToString();
            }
        }
コード例 #44
0
ファイル: UserUtilities.cs プロジェクト: pashkov/Spontaneous
        public ProfileBase GetProfileBase(string userName)
        {
            log.DebugFormat("[GetProfileBase].");
            using (Restaurants restaurantsDb = new Restaurants())
            {
                var collection = restaurantsDb.DB.GetCollection<ProfileBase>(typeof(ProfileBase).Name);
                var entity = collection.FindOneAs<ProfileBase>(Query.And(
                    Query.NE("IsDeleted", true),
                    Query.EQ("UserName", BsonValue.Create(userName)))
                );

                return entity;
            }
        }
コード例 #45
0
 private void btnModifier_Click(object sender, RoutedEventArgs e)
 {
     int id = Convert.ToInt32(this.labelID.Content.ToString());
     Restaurants restaurant = new Restaurants()
     {
         Id = id,
         Nom = this.txtBlockNom.Text,
         Cuisine = this.txtBlockCuisine.Text,
         Rue = this.txtBlockRue.Text,
         Ville = this.txtBlockVille.Text,
         CP = this.txtBlockCP.Text,
         Active = (bool)this.labelActive.Content
     };
     GestionRestaurant gestionrRestautant = new GestionRestaurant(restaurant);
     gestionrRestautant.ShowDialog();
 }
コード例 #46
0
ファイル: UserUtilities.cs プロジェクト: pashkov/Spontaneous
        public List<MongoDB.Web.Providers.MongoDBProfileProvider> GetAllProfiles()
        {
            log.DebugFormat("[GetProfileBase].");
            using (Restaurants restaurantsDb = new Restaurants())
            {
                var collection = restaurantsDb.DB.GetCollection<MongoDB.Web.Providers.MongoDBProfileProvider>(typeof(MongoDB.Web.Providers.MongoDBProfileProvider).Name);

                var query = Query.And(
                Query.NE("IsDeleted", true)
                );

                var all = collection.FindAs<MongoDB.Web.Providers.MongoDBProfileProvider>(query);
                List<MongoDB.Web.Providers.MongoDBProfileProvider> list = all.ToList();

                return list;
            }
        }
コード例 #47
0
ファイル: SearchUtility.cs プロジェクト: vaduha/Spontaneous
        /// <summary>
        ///     Naive implementation of search.
        ///     Without full text search fetures. 
        ///     Based on location and IgnoreCase
        /// </summary>
        /// <param name="searchText"></param>
        /// <param name="userLocation"></param>
        /// <returns></returns>
        internal List<BaseSearchableEnabledItem> Search(Location userLocation, int searchCount = 20, string searchText = null, double maxDistance = 0.5)
        {
            Stopwatch stop = Stopwatch.StartNew();
            var queryCollection = Query.NE("IsDeleted", true);
            using (Restaurants recipesDb = new Restaurants())
            {
                //MongoEntityRepositoryBase<RestaurantBasicData> mongoRepository =
                //    new MongoEntityRepositoryBase<RestaurantBasicData>(recipesDb.DB);

                if (searchText != null)
                {
                    var queryDesc = Query.Matches("Description", BsonRegularExpression.Create(new Regex(searchText, RegexOptions.IgnoreCase)));
                    var queryName = Query.Matches("Name", BsonRegularExpression.Create(new Regex(searchText, RegexOptions.IgnoreCase)));

                    var queryDescDishesDesc = Query.Matches("Menu.MenuParts.Dishes.Description", BsonRegularExpression.Create(new Regex(searchText, RegexOptions.IgnoreCase)));
                    var queryDescDishesName = Query.Matches("Menu.MenuParts.Dishes.Name", BsonRegularExpression.Create(new Regex(searchText, RegexOptions.IgnoreCase)));

                    queryCollection = Query.And(
                        queryCollection,
                        queryCollection = Query.Or(queryDesc, queryName, queryDescDishesDesc, queryDescDishesName)
                    );

                    //queryCollection = Query.And(
                    //    queryCollection,
                    //    Query.Or(queryDesc, queryName)
                    //);
                }

                var collection = recipesDb.DB.GetCollection<RestaurantBasicData>(typeof(RestaurantBasicData).Name);
                collection.EnsureIndex(IndexKeys.GeoSpatial("ItemLocation.RawLocation"));
                var options = GeoNearOptions.SetMaxDistance(maxDistance).SetSpherical(true);//.SetSpherical(true)
                var geoResults = new MongoDB.Driver.GeoNearResult<RestaurantBasicData>();
                if (searchCount <= 0)
                {
                    geoResults = collection.GeoNearAs<RestaurantBasicData>(queryCollection, userLocation.Longitude, userLocation.Latitude, 250, options);
                }
                else
                {
                    geoResults = collection.GeoNearAs<RestaurantBasicData>(queryCollection, userLocation.Longitude, userLocation.Latitude, searchCount, options);
                }
                log.DebugFormat("Search exec={0}", stop.ElapsedMilliseconds);

                return FillGeoSearchItems(geoResults, userLocation);
            }
        }
コード例 #48
0
 public static void Update(RestaurantBasicData restaurant)
 {
     log.DebugFormat("[UpdateRestaurant(RestaurantBasicData)] RestaurantBasicData={0}.", restaurant.ToString());
     restaurant.UpdatedAt = DateTime.UtcNow;
     if (restaurant.Image == null)
     {
         RestaurantBasicData previousRest = GetRestaurantBasic.GetById(restaurant.Id.ToString());
         if (previousRest.Image != null)
         {
             restaurant.Image = previousRest.Image;
         }
     }
     using (Restaurants restaurantsDb = new Restaurants())
     {
         MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                         new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);
         basicData.Update(restaurant);
     }
 }
コード例 #49
0
        public static UserMealProfile GetLastUserMealProfileByUserId(string id)
        {
            log.DebugFormat("[GetUserMealProfileById] id={0}.", id);
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<UserMealProfile> basicData =
                              new MongoEntityRepositoryBase<UserMealProfile>(restaurantsDb.DB);

                var queryCollection = Query.NE("IsDeleted", true);
                var queryUserId = Query.EQ("UserName", id);
                queryCollection = Query.And(
                    queryCollection,
                    queryUserId
                );
                var allUserMealProfiles = basicData.FindAs(queryCollection, 0).OrderByDescending(r => r.CreatedAt).ToList();
                var userMealProfile = allUserMealProfiles.FirstOrDefault();
                //var userMealProfile = basicData.FindAs(queryCollection, 0).OrderByDescending(r => r.CreatedAt).ToList().FirstOrDefault();
                return userMealProfile;
            }
        }
コード例 #50
0
        public List<RestaurantBasicData> FindAllRestaurantsWithCusine()
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                            new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                var queryCollection = Query.NE("IsDeleted", true);
                var queryCuisine = Query.NE("Cuisines", BsonValue.Create(BsonNull.Value));
                queryCollection = Query.And(
                    queryCollection,
                    queryCuisine
                );

                var allRests = basicData.FindAs(queryCollection, 0).OrderBy(r => r.Name).Reverse();
                List<RestaurantBasicData> restaurantsList = allRests.ToList();
                int restsCount = restaurantsList != null ? restaurantsList.Count : 0;
                log.InfoFormat("[FindAllRestauantsWithCusine] count of restaurants with cuisine=[0].", restsCount);
                return restaurantsList;
            }
        }
コード例 #51
0
        public List<RestaurantBasicData> FindAllRestaurantsByOperator(string operatorName, bool emptyMenu=false)
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                            new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                var queryCollection = Query.NE("IsDeleted", true);
                var queryName = Query.Matches("Name", BsonRegularExpression.Create(new Regex(operatorName, RegexOptions.IgnoreCase)));
                //var queryAddres = Query.Matches("Address.City", BsonRegularExpression.Create(new Regex(city, RegexOptions.IgnoreCase)));
                //var queryDescription = Query.Matches("Description", BsonRegularExpression.Create(new Regex(city, RegexOptions.IgnoreCase)));

                IMongoQuery queryMenu = Query.Null;
                if (emptyMenu) queryMenu = Query.NotExists("Menu.MenuParts.3");

                if (queryMenu == null)
                {
                    queryCollection = Query.And(
                        queryCollection,
                        queryName
                    );
                }
                else
                {
                    queryCollection = Query.And(
                           queryCollection,
                           queryName,
                           queryMenu
                       );
                }

                var allRests = basicData.FindAs(queryCollection, 0).OrderBy(r => r.Name).Reverse();
                List<RestaurantBasicData> restaurantsList = allRests.ToList();
                int restsCount = restaurantsList != null ? restaurantsList.Count : 0;
                log.InfoFormat("[FindAllRestaurantsByOperator] count={0}.", restsCount);
                return restaurantsList;
            }
        }
コード例 #52
0
        /// <summary>
        /// Function should find all restaurants which empty menu
        /// </summary>
        /// <returns></returns>
        public List<RestaurantBasicData> GetAllRestaurantsWithSearchResult()
        {
            try
            {
                log.InfoFormat("[GetAllRestaurantsWithSearchResult].");
                var queryCollection = Query.NE("IsDeleted", true);
                using (Restaurants restaurantsDb = new Restaurants())
                {
                    MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                  new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                    var queryNotNull = Query.NE("SearchResults", BsonValue.Create(BsonNull.Value));
                    queryCollection = Query.And(
                        queryCollection,
                        queryNotNull
                    );

                    var allResults = basicData.FindAs(queryCollection, 0);
                    List<RestaurantBasicData> restList = allResults.ToList();
                    return restList;
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("[GetAllRestaurantsWithSearchResult] Exception={0}.", e);
                return null;
            }
        }
コード例 #53
0
        public void AddGeneralDishToDBTest_ShouldSaveDishInDBAndUpdateMongoIdProperty()
        {
            GeneralDish generalDish = new GeneralDish()
            {
                Dish = new Dish()
            };

            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<GeneralDish> basicData =
                                            new MongoEntityRepositoryBase<GeneralDish>(restaurantsDb.DB);

                basicData.Add(generalDish);
                Object savedId = generalDish.Id;
                basicData.Delete(savedId);
            }

            Assert.IsNotNull(generalDish.Id);
        }
コード例 #54
0
 private Stream GetImageStream(ImageData imageData)
 {
     using (Restaurants rests = new Restaurants())
     {
         var file = rests.DB.GridFS.FindOne(Query.EQ("_id", imageData.Id));
         return file.OpenRead();
     }
 }
コード例 #55
0
        /// <summary>
        /// Find all restaurants with specified source property
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public List<RestaurantBasicData> GetRestaurantsBySource(string source)
        {
            try
            {
                log.InfoFormat("[GetRestaurantsBySource] source={0}.", source);
                var queryCollection = Query.NE("IsDeleted", true);
                using (Restaurants restaurantsDb = new Restaurants())
                {
                    MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                  new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                    var queryRestName = Query.EQ("Source", BsonRegularExpression.Create(new Regex(source, RegexOptions.IgnoreCase)));
                    queryCollection = Query.And(
                        queryCollection,
                        queryRestName
                    );

                    var allResults = basicData.FindAs(queryCollection, 0);
                    List<RestaurantBasicData> restList = allResults.ToList();
                    return restList;
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("[GetRestaurantsBySource] Exception={0}.", e);
                return null;
            }
        }
コード例 #56
0
        /// <summary>
        /// Function should find all restaurants which names contains "default menu"
        /// </summary>
        /// <returns></returns>
        public List<RestaurantBasicData> GetllAllRestaurantsBasicDataWithDefaultMenu()
        {
            log.InfoFormat("[GetllAllRestaurantsBasicDataWithDefaultMenu].");
            var queryCollection = Query.NE("IsDeleted", true);
            using (Restaurants recipesDb = new Restaurants())
            {
                MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                            new MongoEntityRepositoryBase<RestaurantBasicData>(recipesDb.DB);

                var queryRestName = Query.Matches("Name", BsonRegularExpression.Create(new Regex("default menu", RegexOptions.IgnoreCase)));
                queryCollection = Query.And(
                    queryCollection,
                    queryRestName
                );

                var allResults = basicData.FindAs(queryCollection, 0);
                List<RestaurantBasicData> restList = allResults.ToList();
                if (restList != null && restList.Count > 0) return restList;
                return null;
            }
        }
コード例 #57
0
        /// <summary>
        /// Function should find all restaurants which empty menu
        /// </summary>
        /// <returns></returns>
        public List<RestaurantBasicData> GetAllRestaurantsWithEmptyMenu()
        {
            try
            {
                log.InfoFormat("[GetAllRestaurantsWithEmptyMenu].");
                var queryCollection = Query.NE("IsDeleted", true);
                using (Restaurants restaurantsDb = new Restaurants())
                {
                    MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                  new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                    var queryEmptyMenu = Query.NotExists("Menu.MenuParts.1");
                    queryCollection = Query.And(
                        queryCollection,
                        queryEmptyMenu
                    );

                    var allResults = basicData.FindAs(queryCollection, 0);
                    List<RestaurantBasicData> restList = allResults.ToList();
                    return restList;
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("[GetAllRestaurantsWithEmptyMenu] Exception={0}.", e);
                return null;
            }
        }
コード例 #58
0
        public List<BaseSearchableEnabledItem> FindNearestRestaurantsByOperator(string operatorName, Location location, double maxDistance)
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                //MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                //                            new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                var queryCollection = Query.NE("IsDeleted", true);
                var queryName = Query.Matches("Name", BsonRegularExpression.Create(new Regex(operatorName, RegexOptions.IgnoreCase)));
                //var queryAddres = Query.Matches("Address.City", BsonRegularExpression.Create(new Regex(city, RegexOptions.IgnoreCase)));
                //var queryDescription = Query.Matches("Description", BsonRegularExpression.Create(new Regex(city, RegexOptions.IgnoreCase)));

                var queryMenu = Query.Exists("Menu.MenuParts.3");
                queryCollection = Query.And(
                    queryCollection,
                    queryName,
                    queryMenu
                );

                var collection = restaurantsDb.DB.GetCollection<RestaurantBasicData>(typeof(RestaurantBasicData).Name);
                collection.EnsureIndex(IndexKeys.GeoSpatial("ItemLocation.RawLocation"));
                collection.EnsureIndex(IndexKeys.Ascending("IsDeleted"));
                var options = GeoNearOptions.SetMaxDistance(maxDistance).SetSpherical(true);
                GeoNearResult<RestaurantBasicData> geoResults;
                geoResults = collection.GeoNearAs<RestaurantBasicData>(queryCollection, location.Longitude, location.Latitude, 20, options);
                var restaurantsList = FillGeoSearchItems(geoResults, location);

                //var allRests = basicData.FindAs(queryCollection, 0).OrderBy(r => r.Name).Reverse();
                //List<RestaurantBasicData> restaurantsList = allRests.ToList();

                int restsCount = restaurantsList != null ? restaurantsList.Count : 0;

                log.InfoFormat("[FindAllRestaurantsByOperator] count={0}.", restsCount);
                return restaurantsList;
            }
        }
コード例 #59
0
        public List<RestaurantBasicData> FindAllSwedenFinlandRestaurants()
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                            new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                var queryCollection = Query.NE("IsDeleted", true);
                var queryLatitude = Query.GT("ItemLocation.Latitude", 55);//Longitude
                queryCollection = Query.And(
                    queryCollection,
                    queryLatitude
                );

                var allRests = basicData.FindAs(queryCollection, 0).OrderBy(r => r.Name).Reverse();
                List<RestaurantBasicData> restaurantsList = allRests.ToList();
                int restsCount = restaurantsList != null ? restaurantsList.Count : 0;
                log.InfoFormat("[FindAllSwedenFinlandRestaurants] count of restaurants of Sweden and Finland=[0].", restsCount);
                return restaurantsList;
            }
        }
コード例 #60
0
        public List<RestaurantBasicData> FindAllRestaurantsWithoutCusineAndEmptyMenu()
        {
            using (Restaurants restaurantsDb = new Restaurants())
            {
                MongoEntityRepositoryBase<RestaurantBasicData> basicData =
                                            new MongoEntityRepositoryBase<RestaurantBasicData>(restaurantsDb.DB);

                var queryCollection = Query.NE("IsDeleted", true);
                var queryCuisine = Query.EQ("Cuisines", BsonValue.Create(BsonNull.Value));
                var queryEmptyMenu = Query.NotExists("Menu.MenuParts.1");
                queryCollection = Query.And(
                    queryCollection,
                    queryCuisine,
                    queryEmptyMenu
                );

                var allRests = basicData.FindAs(queryCollection, 0).OrderBy(r => r.Name).Reverse();
                List<RestaurantBasicData> restaurantsList = allRests.ToList();
                int restsCount = restaurantsList != null ? restaurantsList.Count : 0;
                log.InfoFormat("[FindAllRestaurantsWithoutCusineAndEmptyMenu] count of restaurants with null cuisine and empty menu={0}.", restsCount);
                return restaurantsList;
            }
        }