Example #1
0
        // Create Products
        public ActionResult Create()
        {
            CategoriesService categoriesService = new CategoriesService();
            var categories = categoriesService.GetCategories();

            return(PartialView(categories));
        }
        public async Task GetProgramByIdAsyncShouldThrowExceptionIfProgramIsNull()
        {
            var options = new DbContextOptionsBuilder <MyCalisthenicAppDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                          .Options;

            var dbContext = new MyCalisthenicAppDbContext(options);

            IHttpContextAccessor httpContextAccessor = new HttpContextAccessor();

            var usersService = new UsersService(httpContextAccessor, dbContext, null);

            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MyCalisthenicAppProfile());
            });

            var mapper = mockMapper.CreateMapper();

            var categoriesService = new CategoriesService(dbContext, mapper);

            var programsService = new ProgramsService(dbContext, mapper, usersService, categoriesService);

            var exception = await Assert.ThrowsAsync <ArgumentNullException>(async() => await programsService.GetProgramByIdAsync(ProgramId));

            Assert.IsType <ArgumentNullException>(exception);
        }
Example #3
0
    private void BindGrid()
    {
        String productType = Request.Params["Pid"] == null ? null : Request.Params["Pid"].Trim();
        String catType     = Request.Params["CategoryType"] == null ? null : Request.Params["CategoryType"].Trim();

        if (!StringUtil.isNullOrEmpty(productType))
        {
            dt = CategoriesService.getProductByPTypeId(productType, 1);
            if (!CommonUtil.DT.isEmptyOrNull(dt))
            {
                PType = productType;
            }
        }
        else if (!StringUtil.isNullOrEmpty(catType))
        {
            dt = CategoriesService.getProductByCatType(catType, 1);
        }
        CommonUtil.DtNullCheck(dt);
        if (null != dt && dt.Rows.Count > 0)
        {
            fillCategory(dt);
            fillCategoryNamePanal();
            fillBrandPanal();
        }
        String pType = getProductType();
    }
Example #4
0
        public async Task ProcessAddItemEventAsyncThrowsWhenCategoryNotProvided()
        {
            // arrange
            var fakeCategoriesRepository = new FakeCategoriesRepository();

            fakeCategoriesRepository.CategoryDocuments.Add(new CategoryDocument {
                Id = "fakecategoryid", Name = "fakename", UserId = "fakeuserid"
            });
            var service = new CategoriesService(
                fakeCategoriesRepository,
                new Mock <IImageSearchService>().Object,
                new Mock <ISynonymService>().Object,
                new Mock <IEventGridPublisherService>().Object);

            var eventToProcess = new EventGridEvent
            {
                Subject   = "fakeuserid/fakeitemid",
                EventType = AudioEvents.AudioCreated,
                Data      = new AudioCreatedEventData
                {
                    TranscriptPreview = "faketranscript"
                }
            };

            // act and assert
            await Assert.ThrowsExceptionAsync <InvalidOperationException>(
                () => service.ProcessAddItemEventAsync(eventToProcess, "fakeuserid")).ConfigureAwait(false);
        }
        public void GetByNameShouldReturnCorrectCategory()
        {
            var mockRepo = new Mock <IDeletableEntityRepository <Category> >();

            mockRepo.Setup(x => x.All())
            .Returns(new List <Category>()
            {
                new Category
                {
                    Name        = "Test",
                    Description = "Test",
                    ImageUrl    = "Test",
                },
                new Category
                {
                    Name        = "Test2",
                    Description = "Test2",
                    ImageUrl    = "Test2",
                },
            }.AsQueryable());
            var service = new CategoriesService(mockRepo.Object);
            var result  = service.GetByName <CategoryViewModel>("Test2");

            Assert.Equal("Test2", result.Title);
        }
Example #6
0
        public List <CategoryTree> GetCategoryTree(int tenandId = 0)
        {
            CategoriesService Category = new CategoriesService();
            var result = Category.Reposity.GetAllList();

            if (tenandId > 0)
            {
                result = result.Where(o => o.TenantId == tenandId).ToList();
            }
            List <Categories> lists = new List <Categories>();

            CreateTree(lists, result);
            var elist = Mapper.Map <List <Dto.CategoryTree> >(lists);

            foreach (var item in elist)
            {
                string prev = "";
                if (item.Level > 0)
                {
                    prev = "└";
                    for (int i = 0; i < item.Level; i++)
                    {
                        prev += "─";
                    }
                }
                item.PrevStr = prev;
            }
            Category.Dispose();
            return(elist);
        }
Example #7
0
        public void GetByName_Should_ReturnOneCorrectCategory()
        {
            var dbContext = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

            var categoriesRepository = new EfDeletableEntityRepository <Category>(new ApplicationDbContext(dbContext));

            var service = new CategoriesService(categoriesRepository);

            for (int i = 1; i < 9; i++)
            {
                categoriesRepository.AddAsync(new Category {
                    Id = i, Name = "Test" + i.ToString()
                });
            }

            categoriesRepository.SaveChangesAsync();

            // TODO: no need to mock the database, use moq when testng controllers
            var category  = service.GetByName <MyCategory>("Test4");
            var category2 = service.GetByName <MyCategory>("Test5");

            Assert.Equal("Test4", category.Name);
            Assert.NotEqual("Test4", category2.Name);
            Assert.Equal(4, category.Id);
        }
Example #8
0
        private void InitTestServices()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());

            ApplicationDbContext dbContext = new ApplicationDbContext(options.Options);

            this.imageRepository = new EfDeletableEntityRepository <Image>(dbContext);

            this.imageCategoryRepository = new EfDeletableEntityRepository <ImageCategory>(dbContext);

            this.voteRepository = new EfRepository <Vote>(dbContext);

            this.categoriesRepository = new EfDeletableEntityRepository <Category>(dbContext);
            var loggerCategory = Mock.Of <ILogger <CategoriesService> >();

            this.categoriesService = new CategoriesService(
                loggerCategory,
                this.categoriesRepository,
                this.voteRepository,
                this.imageRepository,
                this.imageCategoryRepository);

            this.CreateImageService(dbContext);
        }
        public async Task CheckGettingCategoryByNameAndByIdAsync()
        {
            ApplicationDbContext db = GetDb();

            var repository = new EfDeletableEntityRepository <Category>(db);
            var service    = new CategoriesService(repository);

            var firstCategory = new Category()
            {
                Id   = Guid.NewGuid().ToString(),
                Name = "Test Category",
            };

            await db.Categories.AddAsync(firstCategory);

            await db.SaveChangesAsync();

            var categoryByName = await service.GetByNameAsync("Test Category");

            var categoryById = await service.GetByIdAsync(firstCategory.Id);

            var categoryIdByName = await service.GetIdByNameAsync("Test Category");

            var expectedCategory = repository
                                   .All()
                                   .FirstOrDefault(c => c.Id == firstCategory.Id);

            Assert.True(categoryByName.Equals(expectedCategory));
            Assert.True(categoryById.Equals(expectedCategory));
            Assert.True(categoryIdByName.Equals(expectedCategory.Id));
        }
Example #10
0
        public void Test()
        {
            //所有的业务逻辑都是通过调用数据仓储服务Reposity,写在Controller里,如下示例:
            //定义一个数据仓储服务,它将继承数据仓储Reposity的所有增删查改方法
            CategoriesService Categ = new CategoriesService();
            //新建对象,通常是定义一个DTO对象,然后将其映射成真实的模型
            Categories obj = new Categories();

            obj.CategoryIndex = "News";
            obj.CategoryName  = "News";
            obj.Childs        = 0;
            obj.Layout        = "Articles";
            obj.TenantId      = 1;
            //调用数据仓储服务Reposity的Insert方法
            Categ.Reposity.Insert(obj);
            //调用数据仓储服务Reposity的同步方法GetAllList
            var result = Categ.Reposity.GetAllList();

            //调用数据仓储服务Reposity的异步方法GetAllListAsync
            Task.Run(async() =>
            {
                var lists = await Categ.Reposity.GetAllListAsync();
            });

            ArticlesService Article = new ArticlesService();
            //调用Service自身的函数
            var articleList = Article.GetArticleWithCate(1, 10, (A => A.CategoryId == 1));

            //Mapper.Initialize(x => x.CreateMap<Articles, Dto.Articles>());
            //var lists = Mapper.Map<ResultDto<List<Dto.Articles>>>(result);
        }
        public async Task CheckGettingAllAndAllAsSelectListItemAsync()
        {
            ApplicationDbContext db = GetDb();

            var repository = new EfDeletableEntityRepository <Category>(db);
            var service    = new CategoriesService(repository);

            var firstCategory = new Category()
            {
                Id = Guid.NewGuid().ToString()
            };
            var secondCategory = new Category()
            {
                Id = Guid.NewGuid().ToString()
            };
            var thirdCategory = new Category()
            {
                Id = Guid.NewGuid().ToString()
            };

            await db.Categories.AddAsync(firstCategory);

            await db.Categories.AddAsync(secondCategory);

            await db.Categories.AddAsync(thirdCategory);

            await db.SaveChangesAsync();

            var categoriesAsSelectedItems = await service.GetAllAsSelectListItemAsync();

            var allCategories = await service.GetAllAsync <TestCategoryModel>();

            Assert.Equal(3, categoriesAsSelectedItems.Count());
            Assert.Equal(3, allCategories.Count());
        }
Example #12
0
        public void ShouldReturnAllCategoriesFromCategoryRepository()
        {
            // Arrange
            var mockedCategory   = new Mock <Category>();
            var mockedCategories = new List <Category>
            {
                mockedCategory.Object,
                mockedCategory.Object
            };
            var mockedUnitOfWork         = new Mock <IUnitOfWork>();
            var mockedCategoryRepository = new Mock <IGenericRepository <Category> >();

            mockedCategoryRepository.Setup(gr => gr.GetAll()).Returns(mockedCategories);
            var mockedProductRepository = new Mock <IGenericRepository <Product> >();

            var categoriesService = new CategoriesService(mockedUnitOfWork.Object,
                                                          mockedCategoryRepository.Object,
                                                          mockedProductRepository.Object);

            // Act
            var result = categoriesService.GetCategories();

            // Assert
            Assert.AreSame(mockedCategories, result);
        }
Example #13
0
        public static void Main(ApplicationDbContext db)
        {
            var repo = new DbRepository <JokeCategory>(db);
            var categoriesService = new CategoriesService(repo);

            var configuration   = Configuration.Default.WithDefaultLoader();
            var browsingContext = BrowsingContext.New(configuration);
            var jokes           = new List <Joke>();

            for (int i = 1; i <= 100; i++)
            {
                var url         = string.Format("http://vicove.com/vic-{0}", i);
                var document    = browsingContext.OpenAsync(url).Result;
                var jokeContent = document.QuerySelector("#content_box .post-content").TextContent.Trim();

                if (!string.IsNullOrWhiteSpace(jokeContent))
                {
                    var categoryName = document.QuerySelector("#content_box .thecategory a").TextContent.Trim();
                    var category     = categoriesService.EnsureCategory(categoryName);
                    var joke         = new Joke {
                        Category = category, Content = jokeContent
                    };
                    jokes.Add(joke);
                }
            }

            db.Jokes.AddOrUpdate(jokes.ToArray());
            db.SaveChanges();
        }
Example #14
0
        public void TestGetAllAsSelectList()
        {
            var list = new List <Category>()
            {
                new Category()
                {
                    Id = 1, Name = "Математика"
                }, new Category()
                {
                    Id = 2, Name = "Информатика"
                }
            };
            var mockRepo = new Mock <IDeletableEntityRepository <Category> >();

            mockRepo.Setup(x => x.AllAsNoTracking()).Returns(list.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Category>())).Callback(
                (Category category) => list.Add(category));

            var service = new CategoriesService(mockRepo.Object);

            SelectList expectedList = new SelectList(list, "Id", "Name");

            SelectList actual = service.GetAllAsSelectList();

            Assert.Equal(expectedList.Items, actual.Items);
        }
Example #15
0
        public async Task DeleteMethodShouldChangeIsDeletedAndDeletedOn(string name)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Categories.AddAsync(new Category
            {
                Name      = name,
                CreatedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var categoriesService = new CategoriesService(db, null, dateTimeProvider.Object);
            await categoriesService.DeleteAsync(1);

            var actual = await db.Categories.FirstOrDefaultAsync();

            actual.IsDeleted.Should().BeTrue();
            actual.DeletedOn.Should().BeSameDateAs(dateTimeProvider.Object.Now());
        }
        public void ShouldCallGetAllMethodWithExpressionOfProductRepositoryOnce()
        {
            // Arrange
            var mockedUnitOfWork         = new Mock <IUnitOfWork>();
            var mockedCategoryRepository = new Mock <IGenericRepository <Category> >();
            var mockedProductRepository  = new Mock <IGenericRepository <Product> >();

            mockedProductRepository.Setup(gr => gr.GetAll(It.IsAny <Expression <Func <Product, bool> > >(),
                                                          It.IsAny <Expression <Func <Product, string> > >(),
                                                          It.IsAny <Expression <Func <Product, Category> > >()))
            .Returns(new List <Category>())
            .Verifiable();

            var categoriesService = new CategoriesService(mockedUnitOfWork.Object,
                                                          mockedCategoryRepository.Object,
                                                          mockedProductRepository.Object);

            // Act
            categoriesService.GetCategoriesByRoomSpecialFiltered("room");

            // Assert
            mockedProductRepository.Verify(gr => gr.GetAll(It.IsAny <Expression <Func <Product, bool> > >(),
                                                           It.IsAny <Expression <Func <Product, string> > >(),
                                                           It.IsAny <Expression <Func <Product, Category> > >()), Times.Once);
        }
Example #17
0
        public async Task GetByIdMethodShouldReturnNullWhenCategoryIsDeleted()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Category, Category>();
            });

            var mapper = config.CreateMapper();

            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Categories.AddAsync(new Category
            {
                Name      = "Test",
                CreatedOn = dateTimeProvider.Object.Now(),
                IsDeleted = true,
                DeletedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var categoriesService = new CategoriesService(db, mapper, dateTimeProvider.Object);
            var actual            = await categoriesService.GetByIdAsync <Category>(1);

            actual.Should().BeNull();
        }
Example #18
0
        public async Task GetByNameShouldReturnCategory()
        {
            var dbContext   = ApplicationDbContextInMemoryFactory.InitializeContext();
            var repository  = new EfDeletableEntityRepository <Category>(dbContext);
            var service     = new CategoriesService(repository);
            var userManager = MockUserManager.GetUserManager();

            // Create
            dbContext.Categories.Add(new Category {
                Name = "Cat1"
            });
            dbContext.Categories.Add(new Category {
                Name = "Test"
            });
            dbContext.Categories.Add(new Category {
                Name = "NONE"
            });
            dbContext.SaveChanges();

            Assert.Equal(1, 1);

            /*
             * Automapper can't map to original type. No way to test this.
             */

            // var foundCategoryCat1 = await service.GetByName<CategoryServiceModel>("Cat1");
            // var foundCategoryTest = await service.GetByName<CategoryServiceModel>("Test");
            // var foundCategoryNONE = await service.GetByName<CategoryServiceModel>("NONE");
            //
            // Assert.Equal("Cat1", foundCategoryCat1.Name);
            // Assert.Equal("Test", foundCategoryTest.Name);
            // Assert.Equal("NONE", foundCategoryNONE.Name);
        }
Example #19
0
        public async Task CreateMethodShouldAddRightCategoryInDatabase()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            var categoriesService = new CategoriesService(db, null, dateTimeProvider.Object);
            await categoriesService.CreateAsync("Test");

            var expected = new Category
            {
                Id        = 1,
                Name      = "Test",
                CreatedOn = dateTimeProvider.Object.Now(),
                IsDeleted = false
            };

            var actual = await db.Categories.FirstOrDefaultAsync();

            actual.Should().BeEquivalentTo(expected);
        }
Example #20
0
        public JsonResult InsertOrUpdate(Categories input)
        {
            ResultDto <int> result = new ResultDto <int>();

            try
            {
                List <Categories> AllCate = new List <Categories>();
                using (CategoriesService Category = new CategoriesService())
                {
                    AllCate = Category.Reposity.GetAllList(o => o.TenantId == TenantId);
                }
                using (CategoriesService Category = new CategoriesService())
                {
                    input.TenantId = TenantId;
                    input.Level    = CsmLevel(input.ParentId, AllCate);
                    Category.Reposity.InsertOrUpdate(input);
                    result.code  = 100;
                    result.datas = input.Id;
                }
            }
            catch (Exception ex)
            {
                result.code    = 500;
                result.message = ex.Message;
            }
            return(Json(result));
        }
Example #21
0
        public async Task EditMethodShouldChangeCategoryNameAndModifiedOn(string creationName, string editedName)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Categories.AddAsync(new Category
            {
                Name      = creationName,
                CreatedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var categoriesService = new CategoriesService(db, null, dateTimeProvider.Object);
            await categoriesService.EditAsync(1, editedName);

            var expected = new Category
            {
                Name       = editedName,
                ModifiedOn = dateTimeProvider.Object.Now()
            };

            var actual = await db.Categories.FirstOrDefaultAsync();

            actual.Name.Should().BeSameAs(expected.Name);
            actual.ModifiedOn.Should().Be(expected.ModifiedOn);
        }
Example #22
0
 public void fillCategoryNamePanal()
 {
     if (!StringUtil.isNullOrEmpty(this.dt.Rows[0]["CategoryTypeID"] + ""))
     {
         DataTable dt = CategoriesService.getDistictProductByCatType(this.dt.Rows[0]["CategoryTypeID"] + "");
         CommonUtil.DtNullCheck(dt);
         if (dt.Rows.Count > 0)
         {
             datalist_categoryname.DataSource = dt;
             dt.Columns.Add("url", typeof(string));
             for (int i = 0; i < dt.Rows.Count; i++)
             {
                 dt.Rows[i]["url"] = removeAND(dt.Rows[i]["CategoryTypeUrlName"] + "", dt.Rows[i]["SKUProductType"] + "");
             }
             datalist_categoryname.DataSource = dt;
             datalist_categoryname.DataBind();
             MainCatHeader.InnerHtml = (String)dt.Rows[0]["SKUCategoryType"];
             String pType = getProductType();
         }
         else
         {
             lblmessage.Visible = true;
             lblmessage.Text    = "Data is not available.";
         }
     }
 }
        public async Task GetAllWorkCorrectly()
        {
            var categories = new List <Category>();

            for (int i = 0; i < 5; i++)
            {
                var category = new Category()
                {
                    Name = "Test" + i.ToString(),
                };
                categories.Add(category);
            }

            await this.dbContext.Categories.AddRangeAsync(categories);

            await this.dbContext.SaveChangesAsync();

            var service = new CategoriesService(this.categoryRepository);
            var result  = service.GetAll <AnnouncementCategoriesView>();

            Assert.Equal(5, result.Count());
            var twoObj = service.GetAll <AnnouncementCategoriesView>(2);

            Assert.Equal(2, twoObj.Count());
        }
Example #24
0
        public async Task ProcessAddItemEventAsyncDoesNotAddItemWhenUserIdDoesNotMatch()
        {
            // arrange
            var fakeCategoriesRepository = new FakeCategoriesRepository();

            fakeCategoriesRepository.CategoryDocuments.Add(
                new CategoryDocument {
                Id = "fakecategoryid", Name = "fakename", UserId = "fakeuserid1"
            });
            var service = new CategoriesService(
                fakeCategoriesRepository,
                new Mock <IImageSearchService>().Object,
                new Mock <ISynonymService>().Object,
                new Mock <IEventGridPublisherService>().Object);

            var eventToProcess = new EventGridEvent
            {
                Subject   = "fakeuserid2/fakeitemid",
                EventType = AudioEvents.AudioCreated,
                Data      = new AudioCreatedEventData
                {
                    Category          = "fakecategoryid",
                    TranscriptPreview = "newpreview"
                }
            };

            // act
            await service.ProcessAddItemEventAsync(eventToProcess, "fakeuserid2").ConfigureAwait(false);

            // assert
            var itemsCollection = fakeCategoriesRepository.CategoryDocuments.Single().Items;

            Assert.AreEqual(0, itemsCollection.Count);
        }
        public async Task DeleteWorkCorrectlyWithNotCorectId()
        {
            var categories = new List <Category>();

            for (int i = 0; i < 5; i++)
            {
                var category = new Category()
                {
                    Name = "Test" + i.ToString(),
                };
                categories.Add(category);
            }

            await this.dbContext.Categories.AddRangeAsync(categories);

            await this.dbContext.SaveChangesAsync();

            var service = new CategoriesService(this.categoryRepository);
            var result  = service.GetAll <AnnouncementCategoriesView>();

            Assert.Equal(5, result.Count());
            var isDelete = service.Delete("11");

            Assert.False(isDelete);
        }
        public void GetAllHLandmarkCategotiesAsKeyValuePairsTest()
        {
            var categoriesList = new List <Category>();
            var mockRepo       = new Mock <IDeletableEntityRepository <Category> >();

            mockRepo.Setup(x => x.AllAsNoTracking()).Returns(categoriesList.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Category>()));
            var      service       = new CategoriesService(mockRepo.Object);
            Category categoryInput = new Category
            {
                Id   = 1,
                Name = "hike-Category",
                Type = "Hike",
            };
            Category categoryInput2 = new Category
            {
                Id   = 2,
                Name = "landmark-Category",
                Type = "Landmark",
            };

            categoriesList.Add(categoryInput);
            categoriesList.Add(categoryInput2);

            var expected = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("2", "landmark-Category"),
            };

            var actual = service.GetAllLandmarkCategotiesAsKeyValuePairs();

            Assert.Equal(expected, actual);
        }
Example #27
0
        public void TestGetCategoryNameById()
        {
            string expectedValue = "Математика";

            var list = new List <Category>()
            {
                new Category()
                {
                    Id = 1, Name = expectedValue
                }, new Category()
                {
                    Id = 2, Name = "Информатика"
                }
            };
            var mockRepo = new Mock <IDeletableEntityRepository <Category> >();

            mockRepo.Setup(x => x.AllAsNoTracking()).Returns(list.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Category>())).Callback(
                (Category category) => list.Add(category));

            var service = new CategoriesService(mockRepo.Object);

            string actual = service.GetCategoryNameById(1);

            Assert.Equal(expectedValue, actual);
        }
Example #28
0
        public static void Main()
        {
            db = new ApplicationDbContext();
            var repo = new DbRepository <JokeCategory>(db);

            categoriesService = new CategoriesService(repo);

            var configuration   = Configuration.Default.WithDefaultLoader();
            var browsingContext = BrowsingContext.New(configuration);

            for (int i = 1; i <= 10000; i++)
            {
                var url         = $"http://vicove.com/vic-{i}";
                var document    = browsingContext.OpenAsync(url).Result;
                var jokeContent = document.QuerySelector("#content_box .post-content").TextContent.Trim();
                if (!string.IsNullOrWhiteSpace(jokeContent))
                {
                    var categoryName = document.QuerySelector("#content_box .thecategory a").TextContent.Trim();
                    TryAddJoke(jokeContent, categoryName);

                    if (i % 100 == 0)
                    {
                        TrySaveChanges(i);
                    }
                }
            }
        }
Example #29
0
        public void ТестGetAllAsKeyValuePairs()
        {
            var list = new List <Category>()
            {
                new Category()
                {
                    Id = 1, Name = "Математика"
                }, new Category()
                {
                    Id = 2, Name = "Информатика"
                }
            };
            var mockRepo = new Mock <IDeletableEntityRepository <Category> >();

            mockRepo.Setup(x => x.AllAsNoTracking()).Returns(list.AsQueryable());
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Category>())).Callback(
                (Category category) => list.Add(category));

            var service = new CategoriesService(mockRepo.Object);

            var expectedList = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("1", "Математика"),
                new KeyValuePair <string, string>("2", "Информатика"),
            };

            var actual = service.GetAllAsKeyValuePairs();

            Assert.Equal(expectedList, actual);
        }
Example #30
0
        public async Task EditAsync_WithCorrectData_ShouldSuccessfullyEdit()
        {
            var testName = "TestName";

            // Arrange
            var context            = ApplicationDbContextInMemoryFactory.InitializeContext();
            var categoryRepository = new EfDeletableEntityRepository <Category>(context);
            var categoriesService  = new CategoriesService(categoryRepository);

            var inputModel = new CreateCategoryInputModel()
            {
                Name = testName,
            };

            await categoriesService.CreateAsync(inputModel);

            var category = categoryRepository.All().FirstOrDefault(c => c.Name == testName);

            // Act
            var expectedCategoryName = "Edited_TestName";
            var editInputModel       = new CategoryInfoViewModel()
            {
                Id   = category.Id,
                Name = expectedCategoryName,
            };
            await categoriesService.EditAsync(editInputModel);

            var actualCategoryName = category.Name;

            // Assert
            category = await categoryRepository.GetByIdWithDeletedAsync(category.Id);

            Assert.Equal(expectedCategoryName, actualCategoryName);
        }
        private static void Seed()
        {
            CategoriesService categories = new CategoriesService();

            categories.Add("Programming");
            categories.Add("CSharp");
            categories.Add("JavaScript");
            categories.Add("Hobbies");

            var all = categories.All().ToList();

            foreach (var cat in all)
            {

                Console.WriteLine(cat.CategoryName);
            }

            PostsService posts = new PostsService();

            posts.Add("Zopfli Optimization: Literally Free Bandwidth",
                "In 2007 I wrote about using PNGout to produce amazingly small PNG images. I still refer to this topic frequently, as seven years later, the average PNG I encounter on the Internet is very unlikely to be optimized. ",
                "*****@*****.**",
                new List<int>() { 1 });

            posts.Add("The Hugging Will Continue Until Morale Improves",
                "I saw in today's news that Apple open sourced their Swift language. One of the most influential companies in the world explicitly adopting an open source model – that's great! I'm a believer. One of the big reasons we founded Discourse was to build an open source solution that anyone, anywhere could use and safely build upon.",
                "*****@*****.**",
                new List<int>() { 2 });

            posts.Add("The 2016 HTPC Build",
                "I saw in today's news that Apple open sourced their Swift language. One of the most influential companies in the world explicitly adopting an open source model – that's great! I'm a believer. One of the big reasons we founded Discourse was to build an open source solution that anyone, anywhere could use and safely build upon.",
                "*****@*****.**",
                new List<int>() { 1 });
            posts.Add("10 Years of CodeMash",
                @"I spent this past week at the 10th annual CodeMash conference in Sandusky OH. Every single event has been enjoyable, envigorating, and a great way to kick-start the year.

The event has changed dramatically over the past decade, but it still has the same core values from when it was started. It’s a group of people passionate about technology in many incarnations, and willing to share and learn from each other. Looking back at 10 years of CodeMash, several larger trends appear.

Early on, the languages discussed most were Java, C#, VB.NET, and Python. Over time, more and more interest in Ruby grew. Java waned for a time. Functional languages like F#, Haskell, and Erlang became more popular. There were a few Scala sessions.",
                "*****@*****.**",
                new List<int>() { 2 });
            posts.Add("Milk + Soap + Food Coloring = Awesome Reaction",
                @" Food coloring will allow you to see what is actually happening and create beautiful swirls and patterns. Any kind, color or amount will work. Have fun experimenting!
To hold the milk, use a shallow bowl or a plate with raised edges.
Regular old dish soap is the way to go.
Finally some Q-tips to apply the soap with.",
                "*****@*****.**",
                new List<int>() { 4 });

        }
		void OnCategoriesUpdating (CategoriesService service)
		{
			SetBusy(service.Fetching);
		}