Exemplo n.º 1
0
        // GET: User/Edit
        public ActionResult Edit(string id)
        {
            // Validate 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 == id)
                           .First();

                // Check if user exists
                if (user == null)
                {
                    return(HttpNotFound());
                }

                // Create a view model
                var viewModel = new EditUserViewModel();
                viewModel.User  = user;
                viewModel.Roles = GetUserRoles(user, database);

                // Pass the model to the view
                return(View(viewModel));
            }
        }
Exemplo n.º 2
0
        // 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));
            }
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        private List <Role> GetUserRoles(ApplicationUser user, MarketplaceDbContext db)
        {
            // Create user manager
            var userManager = Request
                              .GetOwinContext()
                              .GetUserManager <ApplicationUserManager>();

            // Get all applicatio roles
            var roles = db.Roles
                        .Select(r => r.Name)
                        .OrderBy(r => r)
                        .ToList();

            // For each application role, check if the user has it
            var userRoles = new List <Role>();

            foreach (var roleName in roles)
            {
                var role = new Role {
                    Name = roleName
                };

                if (userManager.IsInRole(user.Id, roleName))
                {
                    role.IsSelected = true;
                }

                userRoles.Add(role);
            }

            // Return a list with all roles
            return(userRoles);
        }
Exemplo n.º 5
0
        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);
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
0
        // GET: Ad/Delete/5
        public ActionResult Delete(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();

                if (!IsUserAuthorizedToEdit(ad))
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
                }

                // Check if Ad exist
                if (ad == null)
                {
                    return(HttpNotFound());
                }

                // Pass Ad to view
                return(View(ad));
            }
        }
Exemplo n.º 9
0
        private void CreateUser(MarketplaceDbContext context, string email, string fullName, string password)
        {
            // Create user manager
            var userManager = new UserManager <ApplicationUser>(
                new UserStore <ApplicationUser>(context));

            // Set user manager password validator
            userManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 1,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
                RequireNonLetterOrDigit = false,
            };

            // Create user object
            var admin = new ApplicationUser
            {
                UserName    = email,
                FullName    = fullName,
                DateCreated = DateTime.Now,
                Email       = email,
            };

            // create user
            var result = userManager.Create(admin, password);

            // validate result
            if (!result.Succeeded)
            {
                throw new Exception(string.Join(";", result.Errors));
            }
        }
Exemplo n.º 10
0
        public ActionResult Index()
        {
            using (var database = new MarketplaceDbContext())
            {
                var ads = database.Ads
                          .Where(a => a.Approved == 1)
                          .OrderByDescending(x => x.Id)
                          .Take(6)
                          .Include(a => a.Town)
                          .Include(a => a.Category)
                          .ToList();



                var categories = database.Categories
                                 .Include(c => c.Ads)
                                 .OrderBy(c => c.Name)
                                 .ToList();

                var model = new AdCategoryModel {
                    ads = ads, categories = categories
                };

                return(View(model));
            }
        }
Exemplo n.º 11
0
        public async Task GetAllWishProductsCountReturnsZero()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MarketplaceDbContext>()
                          .UseInMemoryDatabase("GetAllWishProductsCountReturnsZero")
                          .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 user = new MarketplaceUser()
            {
                Id = "eb243391-a7ee-42f6-bb4e-f28c74a68d84"
            };

            dbContext.Users.Add(user);
            await dbContext.SaveChangesAsync();

            //Act
            var actual   = userService.GetAllWishProductsCount(user);
            var expected = 0;

            //Assert
            Assert.Equal(expected, actual);
        }
Exemplo n.º 12
0
        public async Task SeedAsync(MarketplaceDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (await dbContext.Categories.AnyAsync())
            {
                return;
            }

            //TODO: Export into constants
            await dbContext.Categories.AddAsync(new Category { Name = "Auto", FontAwesomeIcon = "fas fa-car-alt", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Sport/Books/Hobby", FontAwesomeIcon = "fas fa-running", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Animals", FontAwesomeIcon = "fas fa-paw", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Electronics", FontAwesomeIcon = "fas fa-desktop", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Services", FontAwesomeIcon = "fas fa-hammer", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Real Estate", FontAwesomeIcon = "fas fa-home", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "House & Garden", FontAwesomeIcon = "fas fa-couch", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Work", FontAwesomeIcon = "fas fa-suitcase-rolling", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Tourism", FontAwesomeIcon = "fas fa-mountain", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Baby", FontAwesomeIcon = "fas fa-baby-carriage", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Fashion", FontAwesomeIcon = "fas fa-tshirt", CreatedOn = DateTime.UtcNow });

            await dbContext.Categories.AddAsync(new Category { Name = "Machines/Tools", FontAwesomeIcon = "fas fa-tools", CreatedOn = DateTime.UtcNow });
        }
Exemplo n.º 13
0
        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);
        }
Exemplo n.º 14
0
        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"));
        }
Exemplo n.º 15
0
        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 }));
            }
        }
Exemplo n.º 16
0
        public async Task SeedAsync(MarketplaceDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger(typeof(MarketplaceDbContextSeeder));

            var seeders = new List <ISeeder>
            {
                new RolesSeeder(),
                new CategoriesSeeder(),
                new SubcategoriesSeeder(),
                new ConditionsSeeder(),
                new PromotionsSeeder()
            };

            foreach (var seeder in seeders)
            {
                await seeder.SeedAsync(dbContext, serviceProvider);

                await dbContext.SaveChangesAsync();

                logger.LogInformation($"Seeder {seeder.GetType().Name} done.");
            }
        }
Exemplo n.º 17
0
        public async Task SeedAsync(MarketplaceDbContext dbContext, IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            var userManager = serviceProvider.GetRequiredService <UserManager <User> >();

            await SeedRoleAsync(roleManager, userManager, GlobalConstants.AdministratorRoleName);
        }
Exemplo n.º 18
0
 public ShoppingCartService(MarketplaceDbContext context, IMapper mapper, UserManager <MarketplaceUser> userManager, IUserService userService)
 {
     this.context     = context;
     this.mapper      = mapper;
     this.userManager = userManager;
     this.userService = userService;
 }
Exemplo n.º 19
0
        public async Task CreateIfUserDoesNotHasCartThrowExeption()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MarketplaceDbContext>()
                          .UseInMemoryDatabase("CreateIfUserDoesNotHasCartThrowExeption")
                          .Options;
            var dbContext     = new MarketplaceDbContext(options);
            var profile       = new MarketplaceProfile();
            var configuration = new MapperConfiguration(x => x.AddProfile(profile));
            var mapper        = new Mapper(configuration);
            var orderService  = new OrderService(dbContext, mapper);

            var user = new MarketplaceUser()
            {
                Id        = "8ca6c061-52de-4f0a-8885-a7501b6dae79",
                FirstName = "Ivan",
                LastName  = "Ivanov",
                Email     = "*****@*****.**"
            };

            dbContext.Users.Add(user);
            await dbContext.SaveChangesAsync();

            var phone           = "0883288905";
            var shippingAddress = "ul.Stara Planina 23";
            //Act
            //Assert
            await Assert.ThrowsAsync <NullReferenceException>(() => orderService.Create(user, phone, shippingAddress));
        }
Exemplo n.º 20
0
 public WishProductService(MarketplaceDbContext context, IMapper mapper, IProductService productService, IUserService userService)
 {
     this.context        = context;
     this.mapper         = mapper;
     this.productService = productService;
     this.userService    = userService;
 }
Exemplo n.º 21
0
        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"));
            }
        }
Exemplo n.º 22
0
 // GET: Category/List
 public ActionResult List()
 {
     using (var database = new MarketplaceDbContext())
     {
         var categories = database.Categories
                          .ToList();
         return(View(categories));
     }
 }
Exemplo n.º 23
0
 // GET: Town/List
 public ActionResult List()
 {
     using (var database = new MarketplaceDbContext())
     {
         var towns = database.Towns
                     .ToList();
         return(View(towns));
     }
 }
Exemplo n.º 24
0
        public ActionResult AddProfilePicture()
        {
            var userId = User.Identity.GetUserId();

            using (var database = new MarketplaceDbContext())
            {
                ViewBag.userPicture = database.Users.Where(a => a.Id == userId).First().ProfilePicture;
            }
            return(View());
        }
Exemplo n.º 25
0
        public async Task DeleteMessageByIdWithInCorrectMessageIdInputReturnFalse()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MarketplaceDbContext>()
                          .UseInMemoryDatabase("DeleteMessageByIdWithInCorrectMessageIdInputReturnFalse")
                          .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 messageService  = new MessageService(dbContext, mapper, userManagerMock.Object);

            var user = new MarketplaceUser()
            {
                Id = "cd89dcbc-bb80-4246-b9b8-ad21753111cc", Email = "*****@*****.**"
            };
            var user1 = new MarketplaceUser()
            {
                Id = "cd89dcbc-bb80-4246-b9b8-ad2175311123", Email = "*****@*****.**"
            };

            dbContext.Users.Add(user);
            await dbContext.SaveChangesAsync();

            var message = new Message()
            {
                MarketplaceUserId = user1.Id,
                Phone             = "0883377905",
                Name           = "Ivan",
                IssuedOn       = DateTime.UtcNow,
                MessageContent = "This is test message!",
                Email          = "*****@*****.**",
                MarkAsRead     = false,
            };

            dbContext.Messages.Add(message);
            await dbContext.SaveChangesAsync();

            user.Messages.Add(message);
            await dbContext.SaveChangesAsync();

            var userId    = "cd89dcbc-bb80-4246-b9b8-ad21753111cc";
            var messageId = "1"; //incorect messageId

            //Act
            var actual = await messageService.DeleteMessageById(userId, messageId);

            var expected = false;

            //Assert
            Assert.Equal(expected, actual);
        }
Exemplo n.º 26
0
 public ActionResult ListCategories()
 {
     using (var database = new MarketplaceDbContext())
     {
         var categories = database.Categories
                          .Include(c => c.Ads)
                          .OrderBy(c => c.Name)
                          .ToList();
         return(View(categories));
     }
 }
Exemplo n.º 27
0
        public async Task CreateWithInCorrectInputIdReturnFalse()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MarketplaceDbContext>()
                          .UseInMemoryDatabase("CreateWithInCorrectInputIdReturnFalse")
                          .Options;
            var dbContext     = new MarketplaceDbContext(options);
            var profile       = new MarketplaceProfile();
            var configuration = new MapperConfiguration(x => x.AddProfile(profile));
            var mapper        = new Mapper(configuration);

            var user = new MarketplaceUser()
            {
                Id = "cd89dcbc-bb80-4246-b9b8-ad21753111cc", Email = "*****@*****.**"
            };
            var user1 = new MarketplaceUser()
            {
                Id = "cd89dcbc-bb80-4246-b9b8-ad2175311111", Email = "*****@*****.**"
            };
            var listUsers = new List <MarketplaceUser>();

            listUsers.Add(user);
            listUsers.Add(user1);
            dbContext.Users.Add(user);
            dbContext.Users.Add(user1);
            await dbContext.SaveChangesAsync();

            var role = "Administrator";

            var userStoreMock   = new Mock <IUserStore <MarketplaceUser> >();
            var userManagerMock = new Mock <UserManager <MarketplaceUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null);

            userManagerMock.Setup(x => x.GetUsersInRoleAsync(role))
            .Returns(Task.FromResult <IList <MarketplaceUser> >(listUsers.ToList()));

            userManagerMock.Setup(x => x.IsInRoleAsync(user, role))
            .Returns(Task.FromResult(true));

            var messageService = new MessageService(dbContext, mapper, userManagerMock.Object);

            var userId  = "";
            var name    = "Ivan";
            var email   = "*****@*****.**";
            var phone   = "0883477980";
            var message = "This is test message!";

            //Act
            var actual = await messageService.Create(userId, name, email, phone, message);

            var expected = false;

            //Assert
            Assert.Equal(expected, actual);
        }
Exemplo n.º 28
0
        public async Task GetUserRolesWithInCorrectIdThrowsNull()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MarketplaceDbContext>()
                          .UseInMemoryDatabase("GetUserRolesWithInCorrectIdThrowsNull")
                          .Options;
            var dbContext     = new MarketplaceDbContext(options);
            var profile       = new MarketplaceProfile();
            var configuration = new MapperConfiguration(x => x.AddProfile(profile));
            var mapper        = new Mapper(configuration);

            var usersList = new List <MarketplaceUser>()
            {
                new MarketplaceUser()
                {
                    Id = "eb243391-a7ee-42f6-bb4e-f28c74a68d84", FirstName = "Ivan", Email = "*****@*****.**"
                },
                new MarketplaceUser()
                {
                    Id = "eb243391-a7ee-42f6-bb4e-f28c74a68d83", FirstName = "Gosho", Email = "*****@*****.**"
                },
            };

            dbContext.Users.Add(usersList[0]);
            dbContext.Users.Add(usersList[1]);
            await dbContext.SaveChangesAsync();

            var roleName  = "user";
            var listRoles = new List <string>()
            {
                "user", "admin"
            };

            var userStoreMock   = new Mock <IUserStore <MarketplaceUser> >();
            var userManagerMock = new Mock <UserManager <MarketplaceUser> >(userStoreMock.Object, null, null, null, null, null, null, null, null);

            userManagerMock.Setup(x => x.GetUsersInRoleAsync(roleName))
            .Returns(Task.FromResult <IList <MarketplaceUser> >(usersList.ToList()));

            userManagerMock.Setup(x => x.GetRolesAsync(usersList[0]))
            .Returns(Task.FromResult <IList <string> >(listRoles));

            var userService = new UserService(dbContext, mapper, userManagerMock.Object);

            var id = "";
            //Act
            var result = await userService.GetUserRoles(id);

            var actual   = result.ToList();
            var expected = new List <string>();

            //Assert
            Assert.Equal(expected, actual);
        }
Exemplo n.º 29
0
        private void CreateRole(MarketplaceDbContext context, string roleName)
        {
            var roleManager = new RoleManager <IdentityRole>(
                new RoleStore <IdentityRole>(context));

            var result = roleManager.Create(new IdentityRole(roleName));

            if (!result.Succeeded)
            {
                throw new Exception(string.Join(";", result.Errors));
            }
        }
Exemplo n.º 30
0
        public async Task GetUserMessagesCorrectIdMarkAsReadSetToTrueReturnZeroMessages()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <MarketplaceDbContext>()
                          .UseInMemoryDatabase("GetUserMessagesCorrectIdMarkAsReadSetToTrueReturnZeroMessages")
                          .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 messageService  = new MessageService(dbContext, mapper, userManagerMock.Object);

            var user = new MarketplaceUser()
            {
                Id = "cd89dcbc-bb80-4246-b9b8-ad21753111cc", Email = "*****@*****.**"
            };
            var user1 = new MarketplaceUser()
            {
                Id = "cd89dcbc-bb80-4246-b9b8-ad2175311123", Email = "*****@*****.**"
            };

            dbContext.Users.Add(user);
            await dbContext.SaveChangesAsync();

            var message = new Message()
            {
                MarketplaceUserId = user1.Id,
                Phone             = "0883377905",
                Name           = "Ivan",
                IssuedOn       = DateTime.UtcNow,
                MessageContent = "This is test message!",
                Email          = "*****@*****.**",
                MarkAsRead     = true,
            };

            dbContext.Messages.Add(message);
            await dbContext.SaveChangesAsync();

            user.Messages.Add(message);
            await dbContext.SaveChangesAsync();

            var userId = "cd89dcbc-bb80-4246-b9b8-ad21753111cc";
            //Act
            var result   = messageService.GetUserMessages <AdminMessageViewModel>(userId);
            var actual   = result.Count();
            var expected = 0;

            //Assert
            Assert.Equal(expected, actual);
        }