Exemplo n.º 1
0
 public IEnumerable <Category> GetAll()
 {
     using (var connection = context.CreateConnection())
     {
         return(connection.Query <Category>(CategoryQuery.All()));
     }
 }
Exemplo n.º 2
0
 public async Task <IEnumerable <Category> > GetAllAsync()
 {
     using (var connection = context.CreateConnection())
     {
         return(await connection.QueryAsync <Category>(CategoryQuery.All()));
     }
 }
Exemplo n.º 3
0
        public JsonResult GetCategories([DataSourceRequest] DataSourceRequest req)
        {
            try
            {
                var query = new CategoryQuery();

                var result   = _metadataServiceClient.GetCategories(query);
                var response = result.Result.Select(r => new CategoryViewModel
                {
                    CategoryId       = r.CategoryId,
                    Name             = r.Name,
                    LongDescription  = r.LongDescription,
                    Type             = r.Type,
                    ParentId         = r.ParentId,
                    ShortDescription = r.ShortDescription,
                }).ToList().OrderByDescending(i => i.CategoryId).ToDataSourceResult(req);

                return(Json(response, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                Log(LogMode.Error, $"There is an error while getting the category data!", ex);
                ModelState.AddModelError("Get Categories", ex.Message);
                var result = ModelState.ToDataSourceResult();
                return(Json(result, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 4
0
        public void CategoryQueryHandler_CategoryQueryNotEmptyDatabase_Array()
        {
            //given
            var repository   = LiteDbHelper.CreateMemoryDb();
            var handler      = new CategoryQueryHandler(repository);
            var query        = new CategoryQuery();
            var rootCategory = new Category(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1))
            {
                Name   = "1",
                Parent = null
            };
            var categories = new[]
            {
                rootCategory,
                new Category(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2))
                {
                    Name   = "2",
                    Parent = rootCategory
                }
            };

            repository.Database.GetCollection <Category>().InsertBulk(categories);

            //when
            var result = handler.Execute(query);

            //then
            Assert.Equal(categories, result);
        }
Exemplo n.º 5
0
        public async Task GetCategoryReturnsCategoryBasedOnReadTypeAndVisibilityTest(
            ReadType readType,
            bool isVisible,
            bool valueReturned)
        {
            var expected = Model.Create <Category>().Set(x => x.Visible = isVisible);

            var store = Substitute.For <ICategoryStore>();
            var cache = Substitute.For <ICategoryCache>();

            var sut = new CategoryQuery(store, cache);

            using (var tokenSource = new CancellationTokenSource())
            {
                store.GetCategory(expected.Group, expected.Name, tokenSource.Token).Returns(expected);

                var actual = await sut.GetCategory(readType, expected.Group, expected.Name, tokenSource.Token)
                             .ConfigureAwait(false);

                if (valueReturned)
                {
                    actual.Should().BeEquivalentTo(expected);
                }
                else
                {
                    actual.Should().BeNull();
                }
            }
        }
Exemplo n.º 6
0
 public Category GetById(Guid id)
 {
     using (var connection = context.CreateConnection())
     {
         return(connection.Query <Category>(CategoryQuery.ById(id)).SingleOrDefault());
     }
 }
Exemplo n.º 7
0
 public async Task <IEnumerable <Category> > GetByParentIdAsync(Guid id)
 {
     using (var connection = context.CreateConnection())
     {
         return(await connection.QueryAsync <Category>(CategoryQuery.ByParentId(id)));
     }
 }
Exemplo n.º 8
0
        public IEnumerable <CategoryDTO> Execute(CategoryQuery request)
        {
            var query = Context.Categories.AsQueryable();

            if (request.Name != null)
            {
                query = query.Where(c => c.Name
                                    .ToLower()
                                    .Contains(
                                        request.Name.ToLower()
                                        ));
            }

            return(query.Select(c => new CategoryDTO
            {
                Id = c.Id,
                Name = c.Name,
                Ads = c.Ads.Select(a => new AdDTO
                {
                    Title = a.Title,
                    Body = a.Body,
                    Price = a.Price,
                    IsShipping = a.IsShipping
                })
            }));
        }
        public async void ProcessEvent_SelectJoke_LoopUntilValidInputCount()
        {
            // Given
            var jokeService = Substitute.For <IJokeService <CategoryQuery> >();
            var nameService = Substitute.For <INameService>();
            var prompt      = Substitute.For <IPrompt>();
            var printer     = Substitute.For <IPrinter>();

            prompt.InputKey(string.Empty).Returns('r');
            prompt.Confirm("Want to use a random name? y/(n)").Returns(false);
            prompt.Confirm("Want to specify a category? y/(n)").Returns(true);
            prompt.Input("Enter a category:").Returns(DefaultCategories[0]);
            prompt.Input("How many jokes do you want? (1-9)").Returns(
                "0", "-1", "-2", "10", "9"
                );
            var categoryQuery = new CategoryQuery(DefaultCategories[0]);

            jokeService.GetRandomJoke(categoryQuery).Returns(new Joke(DefaultJokeValue));
            var sut = new ConsoleJokeGenerator(jokeService, nameService, prompt, printer);

            // When
            var proceed = await sut.ProcessEvent();

            // Then
            Assert.True(proceed);
            jokeService.Received(9).GetRandomJoke(categoryQuery);
            printer.Received(1).WriteLine(string.Empty);
            printer.Received(9).WriteLine(DefaultJokeValue);
            printer.Received(4).WriteLine($"Please enter a count between {ConsoleJokeGenerator.MinJokeCount} and {ConsoleJokeGenerator.MaxJokeCount}");
            prompt.Received(0).Input(DefaultJokeValue);
        }
Exemplo n.º 10
0
        public async Task <IEnumerable <Category> > FindAsync(
            CategoryQuery query = null,
            IComparer <Category> categoryComparer = null)
        {
            var queryBuilder = _session.Query <Models.Category>();

            if (query != null)
            {
                if (query.Type != null)
                {
                    queryBuilder = queryBuilder.Where(c => c.Type == (int)query.Type.Value);
                }
            }

            if (categoryComparer == null)
            {
                categoryComparer = CategoryComparers.DefaultCategoryComparer;
            }

            var queryResult = await queryBuilder
                              .Select(c => new Models.Category
            {
                Id          = c.Id,
                Name        = c.Name,
                Description = c.Description,
                Type        = c.Type
            })
                              .ToListAsync();

            return(queryResult
                   .Select(CategoryConverter.Convert)
                   .OrderBy(c => c, categoryComparer));
        }
        public async Task <IActionResult> Index(string productCategory, string searchString)
        {
            var products = from p in _context.Products
                           select p;

            if (!string.IsNullOrEmpty(searchString))
            {
                products = products.Where(s => s.ProductName.Contains(searchString));
            }

            if (!string.IsNullOrEmpty(productCategory))
            {
                products = products.Where(x => x.Category.CategoryName == productCategory);
            }

            var maxItemInList = _configuration.MaxItemsInList;

            products = products
                       .Include(p => p.Category)
                       .Include(p => p.Supplier);

            products = maxItemInList > 0
                ? products.Take(maxItemInList)
                : products;

            var productCategoryVM = new ProductCategoryViewModel()
            {
                Categories = new SelectList(await CategoryQuery.Select(c => c.CategoryName).Distinct().ToListAsync()),
                Products   = await products.ToListAsync()
            };

            return(View(productCategoryVM));
        }
        public override IEnumerable<ChoiceModel> GetChoices(string selectedFirstChoiceId, string currentContentId)
        {
            var catId = -1;
            Category cat = null;
            var currentContent = ContentReference.EmptyReference;
            if (int.TryParse(selectedFirstChoiceId, out catId))
            {
                cat = _categoryRepository.Get(catId);
            }

            if (catId == -1 || cat == null)
            {
                return new List<ChoiceModel>();
            }

            ContentReference.TryParse(currentContentId, out currentContent);

            var resultList = new List<ChoiceModel>();

            var searchHanler = ServiceLocator.Current.GetInstance<SearchHandler>();

            var query = new CategoryQuery(LuceneOperator.OR);
            query.Items.Add(cat.ID.ToString());

            var results = searchHanler.GetSearchResults(query, 1, int.MaxValue);
            resultList.AddRange(results.IndexResponseItems.SelectMany(CreateHitModel));

            if (currentContent != ContentReference.EmptyReference)
                resultList.RemoveAll(i => i.Id == currentContent.ID.ToString());

            return resultList;
        }
Exemplo n.º 13
0
 public IEnumerable <Category> GetByParentId(Guid id)
 {
     using (var connection = context.CreateConnection())
     {
         return(connection.Query <Category>(CategoryQuery.ByParentId(id)));
     }
 }
Exemplo n.º 14
0
        private static String QuerySql(CategoryQuery query)
        {
            var builder = new SQLBuilder();

            builder.AppendWhere();
            builder.Append(query.RestaurantId > 0, "and", "RestaurantId=@RestaurantId");

            return(builder.Sql());
        }
Exemplo n.º 15
0
        public async Task <Category> GetByIdAsync(Guid id)
        {
            using (var connection = context.CreateConnection())
            {
                var query = await connection.QueryAsync <Category>(CategoryQuery.ById(id));

                return(query.SingleOrDefault());
            }
        }
Exemplo n.º 16
0
        // GET: Categories
        public ActionResult Index(string sortOrder, string searchString, CategoryQuery query)
        {
            ViewBag.CategorySortParam = String.IsNullOrEmpty(sortOrder) ? "category_desc" : "";
            ViewBag.CurrentSortOrder  = sortOrder;
            ViewBag.CurrentFilter     = searchString;

            var categoryList = _getCategories.Execute(query);

            return(View(categoryList));
        }
Exemplo n.º 17
0
        public JsonResult GetProductsByCategory([DataSourceRequest] DataSourceRequest req, int categoryId)
        {
            try
            {
                // Create the category query
                var categoryQuery = new CategoryQuery()
                {
                    CategoryIds = new List <int> {
                        categoryId
                    },
                    Envelope = "full"
                };

                var category = metadataServiceClient.GetCategories(categoryQuery).Result.FirstOrDefault();

                // Get all root categories
                var rootcategories = GetRootCategoriesFromCategories(category, new List <Category>());

                // Get the categoy ids
                var categoryids = rootcategories.Select(s => s.CategoryId).ToList();

                // Add selected category id to list
                categoryids.Add(categoryId);

                if (categoryids.Count != 0)
                {
                    // Create the product query
                    var productQuery = new ProductQuery()
                    {
                        CategoryIds = categoryids
                    };

                    // Get the products
                    var result = metadataServiceClient.GetProducts(productQuery);

                    // Set the data to model
                    var response = result.Result.Select(r => new ProductViewModel
                    {
                        ProductId        = r.ProductId,
                        Name             = r.Name,
                        ShortDescription = r.ShortDescription
                    }).ToList().OrderByDescending(i => i.ProductId).ToDataSourceResult(req);

                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new ProductViewModel(), JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                return(Json(ex));
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            RegisterMappings.Register();

            var categories = new CategoryQuery().GetAll();

            Console.WriteLine("Categories");
            foreach (var category in categories)
            {
                Console.WriteLine($"\t{category.Id} | {category.Description}");
            }

            var people = new PersonQuery().GetAll();

            Console.WriteLine("People and categories");
            foreach (var person in people)
            {
                Console.WriteLine($"\t{person.Id} | {person.Name} | {person.Age} | {person.CategoryId} | {person.Category.Description}");
            }

            var peopleProjects = new PersonQuery().GetAllWithProjects();

            Console.WriteLine("People and projects");
            foreach (var person in peopleProjects)
            {
                Console.WriteLine($"\t{person.Id} | {person.Name}");
                if (person.Projects != null)
                {
                    foreach (var project in person.Projects)
                    {
                        Console.WriteLine($"\t\t{project.Id} | {project.Name}");
                    }
                }
                else
                {
                    Console.WriteLine($"\t\tNo projects");
                }
            }

            var priorities = new PriorityQuery().GetAll();

            Console.WriteLine("Priorities");
            foreach (var priority in priorities)
            {
                Console.WriteLine($"\t{priority.Id} | {priority.Description}");
            }

            var tickets = new TicketQuery().GetAll();

            Console.WriteLine("Tickets");
            foreach (var ticket in tickets)
            {
                Console.WriteLine($"\t{ticket.Description} | {ticket.PersonId} | {(ticket.Person?.Name ?? "No requester")} | {(ticket.Person?.CategoryId.ToString() ?? "No category id")} | {(ticket.Person?.Category?.Description ?? "No category")} | {(ticket.PriorityId.ToString() ?? "No priority Id")} | {(ticket.Priority?.Description ?? "No Priority")}");
            }
        }
Exemplo n.º 19
0
        public async Task <CategoryCollection> List(CategoryQuery query)
        {
            var dbQuery = await query.Create(this.Entities);

            var total = await dbQuery.CountAsync();

            dbQuery = dbQuery.Skip(query.SkipTo(total)).Take(query.Limit);
            var results = await dbQuery.ToListAsync();

            return(new CategoryCollection(query, total, results.Select(i => mapper.MapCategory(i, new Category()))));
        }
Exemplo n.º 20
0
 public ActionResult <IEnumerable <CategoryDto> > Get([FromQuery] CategoryQuery query)
 {
     try
     {
         return(Ok(_getCategories.Execute(query)));
     }
     catch (NotFoundException)
     {
         return(NotFound());
     }
 }
Exemplo n.º 21
0
        //GET /Category
        public IHttpActionResult Get([FromUri] CategoryQuery request)
        {
            // Query, ordering, pagination
            var list = CategoryService.List(request);

            // Maps to Api model
            var mapped = list.Map <Category, CategoryModel>();

            // Returns a 200 status with custom headers (paging)
            return(Page(mapped));
        }
Exemplo n.º 22
0
        public static Tuple <string, string, dynamic> Select(CategoryQuery query)
        {
            string whereSql  = QuerySql(query);
            string countsql  = string.Format("select count(Id) as Count from foodcategory {0};", whereSql);
            string selectsql = string.Join(" ", BaseSelectSql(), whereSql, "order by Id desc", "limit @limit offset @offset;");

            return(new Tuple <string, string, dynamic>(countsql, selectsql, new
            {
                limit = query.Limit,
                offset = query.Offset,
                RestaurantId = query.RestaurantId
            }));
        }
Exemplo n.º 23
0
        public void GetCategoryThrowsExceptionWithInvalidNameTest(string name)
        {
            var store = Substitute.For <ICategoryStore>();
            var cache = Substitute.For <ICategoryCache>();

            var sut = new CategoryQuery(store, cache);

            Func <Task> actual = async() =>
                                 await sut.GetCategory(ReadType.VisibleOnly, CategoryGroup.Skill, name, CancellationToken.None)
                                 .ConfigureAwait(false);

            actual.Should().Throw <ArgumentException>();
        }
Exemplo n.º 24
0
            async Task List()
            {
                //This could be more complete
                var repo = mockup.Get <ICategoryRepository>();
                await repo.AddRange(new CategoryInput[] { CategoryTests.CreateInput(), CategoryTests.CreateInput(), CategoryTests.CreateInput() });

                var query  = new CategoryQuery();
                var result = await repo.List(query);

                Assert.Equal(query.Limit, result.Limit);
                Assert.Equal(query.Offset, result.Offset);
                Assert.Equal(3, result.Total);
                Assert.NotEmpty(result.Items);
            }
Exemplo n.º 25
0
        public void CategoryQueryHandler_CategoryQueryEmptyDatabase_EmptyArray()
        {
            //given
            var repository = LiteDbHelper.CreateMemoryDb();
            var handler    = new CategoryQueryHandler(repository);
            var query      = new CategoryQuery();

            //when
            var result = handler.Execute(query);

            //then
            Assert.NotNull(result);
            Assert.Empty(result);
        }
Exemplo n.º 26
0
        public async Task LoadCategories(string categoryUrl)
        {
            var query = new CategoryQuery(User);

            var result = await _categoryHandler.Execute(query);

            if (!string.IsNullOrEmpty(categoryUrl))
            {
                CurrentCategory = result
                                  .FirstOrDefault(x => string.Equals(x.UrlSegment, categoryUrl));
            }

            Categories.AddRange(result);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Search by criteria
        /// </summary>
        /// <param name="request">Filter, pagination, sorting parameters</param>
        /// <returns>Paged result (sorted)</returns>
        public PagedList <Category> List(CategoryQuery request)
        {
            var query = base.List();

            // Build que query
            if (!string.IsNullOrWhiteSpace(request.Name))
            {
                query = query.Where(i => i.Name.Contains(request.Name));
            }

            // Apply paging and sorting
            var result = query.ToPaged(request);

            return(result);
        }
Exemplo n.º 28
0
        public IReturn Select(int restaurantId)
        {
            int           totalRow = 0;
            CategoryQuery query    = new CategoryQuery
            {
                PageIndex    = 1,
                PageSize     = 100,
                RestaurantId = restaurantId
            };

            var category = RepositoryRegistry.Category.Select(query, out totalRow).ToList();

            return(this.Write("Select", new PageList <DomainModel.Category> {
                TotalRows = totalRow, Collections = category
            }));
        }
Exemplo n.º 29
0
        public async Task GetCategoriesReturnsEmptyListWhenCategoriesNotFoundTest()
        {
            var store = Substitute.For <ICategoryStore>();
            var cache = Substitute.For <ICategoryCache>();

            var sut = new CategoryQuery(store, cache);

            using (var tokenSource = new CancellationTokenSource())
            {
                cache.GetCategories().Returns((ICollection <Category>)null);
                store.GetAllCategories(tokenSource.Token).Returns((IEnumerable <Category>)null);

                var actual = await sut.GetCategories(ReadType.All, tokenSource.Token).ConfigureAwait(false);

                actual.Should().BeEmpty();
            }
        }
Exemplo n.º 30
0
        public async Task GetCategoriesReturnsCachedCategoriesTest()
        {
            var expected = Model.Create <List <Category> >();

            var store = Substitute.For <ICategoryStore>();
            var cache = Substitute.For <ICategoryCache>();

            cache.GetCategories().Returns(expected);

            var sut = new CategoryQuery(store, cache);

            using (var tokenSource = new CancellationTokenSource())
            {
                var actual = await sut.GetCategories(ReadType.All, tokenSource.Token).ConfigureAwait(false);

                actual.Should().BeEquivalentTo(expected);
            }
        }
Exemplo n.º 31
0
        /// <summary>
        /// 获取商品分类ORM集合
        /// </summary>
        /// <param name="queryParameter"></param>
        /// <returns></returns>
        public async Task <EntitySet <Category> > GetCategoryEnititySetAsync(CategoryQuery queryParameter)
        {
            var query = context.Categorys.AsQueryable();

            if (queryParameter.ParentId > 0)
            {
                query = query.Where(c => c.ParentId == queryParameter.ParentId);
            }
            if (!string.IsNullOrEmpty(queryParameter.Name))
            {
                query.Where(c => c.IsDel == false);
            }
            //默认按时间逆序
            query.OrderBy(c => c.Id);
            var categorySet = await query.ToEntitySetAsync(queryParameter);

            return(categorySet);
        }
Exemplo n.º 32
0
 protected CategoryRepository()
 {
     dbLocation = DatabaseFilePath;
     db = new MaDatabase (dbLocation);
     cq = new CategoryQuery (dbLocation);
 }