public ActionResult DeleteConfirmed(int?id) { using (var database = new MarketplaceDbContext()) { var category = database.Categories .FirstOrDefault(c => c.Id == id); var categoryAds = category.Ads .ToList(); foreach (var ad in categoryAds) { string fullPathPrimary = Request.MapPath("~/Content/UploadedImages/" + ad.primaryImageName); if (System.IO.File.Exists(fullPathPrimary)) { System.IO.File.Delete(fullPathPrimary); } var images = database.Images .Where(a => a.AdId == ad.Id) .ToList(); foreach (var image in images) { string fullPath = Request.MapPath("~/Content/UploadedImages/" + image.FileName); if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } database.Images.Remove(image); database.SaveChanges(); } //Delete comments var comments = database.Comments .Where(a => a.AdId == ad.Id) .ToList(); foreach (var comment in comments) { database.Comments.Remove(comment); database.SaveChanges(); } // Delete Ad from database database.Ads.Remove(ad); database.SaveChanges(); } database.Categories.Remove(category); database.SaveChanges(); TempData["Success"] = "Категорията е премахната успешно."; return(RedirectToAction("Index")); } }
public ActionResult AddProfilePicture([Bind(Exclude = "ProfilePicture")] AddProfilePicture model) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { var userId = User.Identity.GetUserId(); var user = ViewBag.userPicture = database.Users.FirstOrDefault(a => a.Id == userId); if (user.ProfilePicture != null) { string fullPathPrimary = Request.MapPath("~/Content/ProfilePictures/" + user.ProfilePicture); if (System.IO.File.Exists(fullPathPrimary)) { System.IO.File.Delete(fullPathPrimary); } user.ProfilePicture = null; } HttpPostedFileBase imgFile = Request.Files["ProfilePicture"]; var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; //upload Primary image if (imgFile != null && imgFile.ContentLength > 0) { if (validImageTypes.Contains(imgFile.ContentType)) { var id = Guid.NewGuid().ToString(); var fileName = id + Path.GetExtension(imgFile.FileName); var path = Path.Combine(Server.MapPath("~/Content/ProfilePictures/"), fileName); imgFile.SaveAs(path); user.ProfilePicture = fileName; } else { TempData["Danger"] = "Позволените формати за снимка са .gif, .jpeg и .png."; return(RedirectToAction("Index")); } } database.Entry(user).State = EntityState.Modified; database.SaveChanges(); TempData["Success"] = "Успешно сменихте профилната си снимка."; } } else { TempData["Danger"] = "Грешка! Моля опитайте отново."; } return(RedirectToAction("Index")); }
public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } bool isAdmin = this.User.IsInRole("Admin"); if (!isAdmin) { TempData["Danger"] = "Нямате необходимите права."; return(RedirectToAction("List", "Ad")); } using (var database = new MarketplaceDbContext()) { var comment = database.Comments .FirstOrDefault(c => c.Id == id); var path = comment.AdId; if (comment == null) { return(HttpNotFound()); } database.Comments.Remove(comment); database.SaveChanges(); TempData["Success"] = "Успешно изтрихте коментара."; return(RedirectToAction("Details", "Ad", new { id = path })); } }
// GET: Ad/Details/5 public ActionResult Details(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } using (var database = new MarketplaceDbContext()) { // Get the Ad from db var ad = database.Ads .Where(a => a.Id == id) .Include(a => a.Images) .Include(a => a.Author) .Include(a => a.Town) .Include(a => a.Category) .Include(a => a.Comments) .First(); if (ad == null) { return(HttpNotFound()); } if (ad.Approved == 1) { ad.ViewCount = ad.ViewCount + 1; database.SaveChanges(); } return(View(ad)); } }
public void GetAllUsersReturnsRightUserModelEmail() { //Arrange var options = new DbContextOptionsBuilder <MarketplaceDbContext>() .UseInMemoryDatabase("GetAllUsersReturnsRightUserModelEmail") .Options; var dbContext = new MarketplaceDbContext(options); var profile = new MarketplaceProfile(); var configuration = new MapperConfiguration(x => x.AddProfile(profile)); var mapper = new Mapper(configuration); var userStoreMock = new Mock <IUserStore <MarketplaceUser> >(); var userManagerMock = new Mock <UserManager <MarketplaceUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null); var userService = new UserService(dbContext, mapper, userManagerMock.Object); var user1 = new MarketplaceUser() { Id = "eb243391-a7ee-42f6-bb4e-f28c74a68d84", FirstName = "Georgi", LastName = "Horozov", Email = "*****@*****.**" }; dbContext.Users.Add(user1); dbContext.SaveChanges(); //Act var result = userService.GetAllUsers <UserViewModel>(); var actual = result.First().Email; var expected = "*****@*****.**"; //Assert Assert.Equal(expected, actual); }
public void GetAllCategoriesInputTwoCategoriesReturnFirstNameAnIdShouldMatch() { //Arrange var options = new DbContextOptionsBuilder <MarketplaceDbContext>() .UseInMemoryDatabase("GetAllCategoriesInputTwoCategoriesReturnFirstNameShouldMatch") .Options; var dbContext = new MarketplaceDbContext(options); var profile = new MarketplaceProfile(); var configuration = new MapperConfiguration(x => x.AddProfile(profile)); var mapper = new Mapper(configuration); var categoryService = new CategoryService(dbContext, mapper); var category1 = new Category() { Id = "42a27ec6-3abb-4e7b-a224-6fd873564368", Name = "Smartphones" }; var category2 = new Category() { Id = "7821b986-e16a-4a50-99c5-e5d0dc71488d", Name = "Laptops" }; dbContext.Categories.Add(category1); dbContext.Categories.Add(category2); dbContext.SaveChanges(); //Act var result = categoryService.GetAllCategories <IndexCategoryViewModel>(); var actual = result.First().Name; var expected = "Smartphones"; //Assert Assert.Equal(expected, actual); Assert.Equal("42a27ec6-3abb-4e7b-a224-6fd873564368", result.First().CategoryId); }
public async Task EditWithInCorectInputEmptyNameReturnsFalse() { //Arrange var options = new DbContextOptionsBuilder <MarketplaceDbContext>() .UseInMemoryDatabase("EditWithInCorectInputEmptyNameReturnsFalse") .Options; var dbContext = new MarketplaceDbContext(options); var profile = new MarketplaceProfile(); var configuration = new MapperConfiguration(x => x.AddProfile(profile)); var mapper = new Mapper(configuration); var categoryService = new CategoryService(dbContext, mapper); var category = new Category() { Id = "42a27ec6-3abb-4e7b-a224-6fd873564368", Name = "Smartphones" }; dbContext.Categories.Add(category); dbContext.SaveChanges(); var id = "42a27ec6-3abb-4e7b-a224-6fd873564368"; var name = " "; //Act var actual = await categoryService.Edit(id, name); var expected = false; //Assert Assert.Equal(expected, actual); }
public async Task GetCategoryByNameInCorrectinputReturnsNull() { //Arrange var options = new DbContextOptionsBuilder <MarketplaceDbContext>() .UseInMemoryDatabase("GetCategoryByNameInCorrectinputReturnsNull") .Options; var dbContext = new MarketplaceDbContext(options); var profile = new MarketplaceProfile(); var configuration = new MapperConfiguration(x => x.AddProfile(profile)); var mapper = new Mapper(configuration); var categoryService = new CategoryService(dbContext, mapper); var category = new Category() { Id = "42a27ec6-3abb-4e7b-a224-6fd873564368", Name = "Smartphones" }; dbContext.Categories.Add(category); dbContext.SaveChanges(); var categoryName = ""; //Act var actual = await categoryService.GetCategoryByName(categoryName); Category expected = null; //Assert Assert.Equal(expected, actual); }
public async Task GetCategoryByIdWithCorectIdreturnsCategoryType() { //Arrange var options = new DbContextOptionsBuilder <MarketplaceDbContext>() .UseInMemoryDatabase("GetCategoryByIdWithCorectIdreturnsCategory") .Options; var dbContext = new MarketplaceDbContext(options); var profile = new MarketplaceProfile(); var configuration = new MapperConfiguration(x => x.AddProfile(profile)); var mapper = new Mapper(configuration); var categoryService = new CategoryService(dbContext, mapper); var category = new Category() { Id = "42a27ec6-3abb-4e7b-a224-6fd873564368", Name = "Smartphones" }; dbContext.Categories.Add(category); dbContext.SaveChanges(); var categoryId = "42a27ec6-3abb-4e7b-a224-6fd873564368"; //Act var result = await categoryService.GetCategoryById(categoryId); var actual = result.GetType(); var expected = typeof(Category); //Assert Assert.Equal(expected, actual); Assert.Equal("Smartphones", result.Name); }
public ActionResult Edit(Town town) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { database.Entry(town).State = System.Data.Entity.EntityState.Modified; database.SaveChanges(); return(RedirectToAction("Index")); } } return(View(town)); }
public ActionResult Create(Category category) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { database.Categories.Add(category); database.SaveChanges(); return(RedirectToAction("Index")); } } return(View(category)); }
public ActionResult Create(Town town) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { database.Towns.Add(town); database.SaveChanges(); return(RedirectToAction("Index")); } } return(View(town)); }
public ActionResult Edit(AdViewModel model) { // Check if model state is valid if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { // Get Ad from database var ad = database.Ads .FirstOrDefault(a => a.Id == model.Id); if (!IsUserAuthorizedToEdit(ad)) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } // Set Ad properties ad.Title = model.Title; ad.Content = model.Content; ad.Price = model.Price; ad.CategoryId = model.CategoryId; ad.TownId = model.TownId; bool isAdmin = this.User.IsInRole("Admin"); if (isAdmin) { ad.Approved = model.Approved; } // Save Ad state in database database.Entry(ad).State = EntityState.Modified; database.SaveChanges(); // Redirect to the index page TempData["Success"] = "Успешно редактирахте обявата."; return(RedirectToAction("List")); } } // If model state is invalid, retyrn the same view TempData["Danger"] = "Некоректни данни, моля опитайте отново."; return(View(model)); }
public ActionResult Create(Comment model) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { DateTime DateCreated = DateTime.Now; var comment = new Comment(model.Name, model.Content, model.Stars, model.AdId, DateCreated); //Save Ad in DB database.Comments.Add(comment); database.SaveChanges(); } TempData["Success"] = "Успешно добавихте коментар."; return(RedirectToAction("Details", "Ad", new { id = model.AdId })); } TempData["Danger"] = "Некоректни данни, моля опитайте отново."; return(RedirectToAction("Details", "Ad", new { id = model.AdId })); }
public ActionResult Edit(string id, EditUserViewModel viewModel) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { // Get user from database var user = database.Users.FirstOrDefault(u => u.Id == id); // Check if user axist if (user == null) { return(HttpNotFound()); } // If password field is not empty, change password if (!string.IsNullOrEmpty(viewModel.Password)) { var hasher = new PasswordHasher(); var passwordHash = hasher.HashPassword(viewModel.Password); user.PasswordHash = passwordHash; } // Set user properties user.Email = viewModel.User.Email; user.FullName = viewModel.User.FullName; user.UserName = viewModel.User.Email; this.SetUserRoles(viewModel, user, database); // Save changes database.Entry(user).State = EntityState.Modified; database.SaveChanges(); return(RedirectToAction("List")); } } return(View(viewModel)); }
public ActionResult DeleteConfirmed(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } using (var database = new MarketplaceDbContext()) { // Get Ad from database var ad = database.Ads .Where(a => a.Id == id) .Include(a => a.Author) .First(); // Check if Ad exist if (ad == null) { return(HttpNotFound()); } string fullPathPrimary = Request.MapPath("~/Content/UploadedImages/" + ad.primaryImageName); if (System.IO.File.Exists(fullPathPrimary)) { System.IO.File.Delete(fullPathPrimary); } var images = database.Images .Where(a => a.AdId == ad.Id) .ToList(); foreach (var image in images) { string fullPath = Request.MapPath("~/Content/UploadedImages/" + image.FileName); if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } database.Images.Remove(image); database.SaveChanges(); } //Delete comments var comments = database.Comments .Where(a => a.AdId == ad.Id) .ToList(); foreach (var comment in comments) { database.Comments.Remove(comment); database.SaveChanges(); } // Delete Ad from database database.Ads.Remove(ad); database.SaveChanges(); // Redirect to index page TempData["Success"] = "Успешно изтрихте обявата."; return(RedirectToAction("List")); } }
public ActionResult DeleteConfirmed(string id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } using (var database = new MarketplaceDbContext()) { // Get user from database var user = database.Users .Where(u => u.Id.Equals(id)) .First(); // Get user Ads from database var userAds = database.Ads .Where(a => a.Author.Id == user.Id) .ToList(); // Delete user Ads foreach (var ad in userAds) { string fullPathPrimary = Request.MapPath("~/Content/UploadedImages/" + ad.primaryImageName); if (System.IO.File.Exists(fullPathPrimary)) { System.IO.File.Delete(fullPathPrimary); } var images = database.Images .Where(a => a.AdId == ad.Id) .ToList(); foreach (var image in images) { string fullPath = Request.MapPath("~/Content/UploadedImages/" + image.FileName); if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); } database.Images.Remove(image); database.SaveChanges(); } //Delete comments var comments = database.Comments .Where(a => a.AdId == ad.Id) .ToList(); foreach (var comment in comments) { database.Comments.Remove(comment); database.SaveChanges(); } // Delete Ad from database database.Ads.Remove(ad); database.SaveChanges(); } database.Users.Remove(user); database.SaveChanges(); TempData["Success"] = "Потребителят е премахнат успешно."; return(RedirectToAction("List")); } }
public ActionResult Create(AdViewModel model, HttpPostedFileBase primaryImage, IEnumerable <HttpPostedFileBase> uploadImages) { if (ModelState.IsValid) { using (var database = new MarketplaceDbContext()) { // Get author Id var authorId = database.Users .Where(u => u.UserName == this.User.Identity.Name) .First() .Id; DateTime DateCreated = DateTime.Now; int viewCount = 0; string adId = Guid.NewGuid().ToString(); var ad = new Ad(adId, 0, authorId, model.Title, model.Content, model.Price, model.CategoryId, model.TownId, viewCount, DateCreated, null); //Save Ad in DB database.Ads.Add(ad); database.SaveChanges(); //Upload images var validImageTypes = new string[] { "image/gif", "image/jpeg", "image/pjpeg", "image/png" }; //upload Primary image if (primaryImage != null && primaryImage.ContentLength > 0) { if (validImageTypes.Contains(primaryImage.ContentType)) { var id = Guid.NewGuid().ToString(); var fileName = id + Path.GetExtension(primaryImage.FileName); var path = Path.Combine(Server.MapPath("~/Content/UploadedImages"), fileName); primaryImage.SaveAs(path); var image = new Image(id, fileName, true, adId); database.Images.Add(image); database.SaveChanges(); ad.primaryImageName = fileName; database.Entry(ad).State = EntityState.Modified; database.SaveChanges(); } else { TempData["Warning"] = "Позволените формати за снимка са .gif, .jpeg и .png. Обявата Ви е качена без главна снимка и ще бъде видима, след като е одобрена."; return(RedirectToAction("List")); } } //upload other images if (uploadImages != null) { foreach (var otherImage in uploadImages) { if (otherImage != null && otherImage.ContentLength > 0) { if (validImageTypes.Contains(otherImage.ContentType)) { var id = Guid.NewGuid().ToString(); var fileName = id + Path.GetExtension(otherImage.FileName); var path = Path.Combine(Server.MapPath("~/Content/UploadedImages"), fileName); otherImage.SaveAs(path); var image = new Image(id, fileName, false, adId); database.Images.Add(image); database.SaveChanges(); } else { TempData["Warning"] = "Позволените формати за снимка са .gif, .jpeg и .png. Обявата Ви е качена и ще бъде видима, след като е одобрена."; return(RedirectToAction("List")); } } } } } TempData["Success"] = "Успешно добавихте обява. Обявата Ви ще бъде видима, след като е одобрена."; return(RedirectToAction("List")); } TempData["Danger"] = "Некоректни данни, моля опитайте отново."; return(RedirectToAction("List")); }