Example #1
0
        public async Task AddAsync(CategoryGroup categoryGroup)
        {
            const string existsSql = "SELECT 1 FROM CategoryGroup WHERE Name = @Name AND UserId = @UserId";
            const string insertSql = @"INSERT INTO CategoryGroup (UserId, Name)
                                    VALUES (@UserId, @Name)";

            using (IDbConnection dbConnection = this.dbConnectionFactory.Create())
            {
                IEnumerable <int> result = await dbConnection.QueryAsync <int>(existsSql, new { categoryGroup.Name, categoryGroup.UserId }).ConfigureAwait(false);

                if (result.Any())
                {
                    throw new EntityAlreadyExistsException("Category group already exists");
                }
            }

            using (IDbConnection dbConnection = this.dbConnectionFactory.Create())
            {
                try
                {
                    await dbConnection.ExecuteAsync(insertSql, new
                    {
                        categoryGroup.UserId,
                        categoryGroup.Name
                    }).ConfigureAwait(false);
                }
                catch (SqlException ex)
                {
                    throw new RepositoryException("Failed to add category group", ex);
                }
            }
        }
Example #2
0
        public ProductListPage(CategoryGroup _group)
        {
            InitializeComponent();

            this.Title = _group.Name;

            if (_group.MenuType == Enums.EMenuType.Informative)
            {
                var addNew = new ToolbarItem(AppResource.lblNew, "", async() =>
                {
                    await App.AppCurrent.NavigationService.NavigateAsync(new CreateEditInformativeMenuPage(_group), null, false);
                }, 0, 0);
                addNew.Priority = 1;
                ToolbarItems.Add(addNew);
            }
            else
            {
                var addNew = new ToolbarItem(AppResource.lblNew, "", async() =>
                {
                    await App.AppCurrent.NavigationService.NavigateAsync(new CreateEditProductPage(Group), null, false);
                }, 0, 0);
                addNew.Priority = 1;
                ToolbarItems.Add(addNew);
            }

            Group = _group;


            listView.ItemTapped += ListView_ItemTapped;
        }
Example #3
0
        public async Task UpdateAsync(CategoryGroup categoryGroup)
        {
            const string existsSql = "SELECT 1 FROM CategoryGroup WHERE Name = @Name AND UserId = @UserId";
            const string updateSql = @"UPDATE CategoryGroup
                                        SET Name = @Name
                                        WHERE Id = @Id";

            using (IDbConnection dbConnection = this.dbConnectionFactory.Create())
            {
                IEnumerable <int> result = await dbConnection.QueryAsync <int>(existsSql, new { categoryGroup.Name, categoryGroup.UserId }).ConfigureAwait(false);

                if (result.Any())
                {
                    throw new EntityAlreadyExistsException("Category group already exists");
                }
            }

            using (IDbConnection dbConnection = this.dbConnectionFactory.Create())
            {
                try
                {
                    await dbConnection.ExecuteAsync(updateSql, new
                    {
                        categoryGroup.Id,
                        categoryGroup.Name
                    }).ConfigureAwait(false);
                }
                catch (SqlException ex)
                {
                    throw new RepositoryException("Failed to update category group", ex);
                }
            }
        }
        public async Task StoreCategoryLinksOverwritesExistingEntryUsingNewBatchTest()
        {
            const CategoryGroup group = CategoryGroup.Gender;
            var categoryName          = Guid.NewGuid().ToString();
            var changes = new List <CategoryLinkChange>
            {
                new CategoryLinkChange
                {
                    ChangeType = CategoryLinkChangeType.Add,
                    ProfileId  = Guid.NewGuid()
                }
            };

            var sut = new CategoryLinkStore(Config.Storage);

            await sut.StoreCategoryLinks(group, categoryName, changes, CancellationToken.None).ConfigureAwait(false);

            await sut.StoreCategoryLinks(group, categoryName, changes, CancellationToken.None).ConfigureAwait(false);

            var actual = (await sut.GetCategoryLinks(group, categoryName, CancellationToken.None).ConfigureAwait(false))
                         .ToList();

            actual.All(x => x.CategoryGroup == group).Should().BeTrue();
            actual.All(x => x.CategoryName.Equals(categoryName, StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            actual.Should().BeEquivalentTo(changes, opt => opt.ExcludingMissingMembers());
        }
        public async Task StoreCategoryLinksAddsNewItemsWhenTableNotFoundTest()
        {
            // Retrieve storage account from connection-string
            var storageAccount = CloudStorageAccount.Parse(Config.Storage.ConnectionString);

            // Create the table client
            var client = storageAccount.CreateCloudTableClient();

            var table = client.GetTableReference("CategoryLinks");

            await table.DeleteIfExistsAsync().ConfigureAwait(false);

            const CategoryGroup group = CategoryGroup.Gender;
            var categoryName          = Guid.NewGuid().ToString();
            var changes = Model.Create <List <CategoryLinkChange> >()
                          .SetEach(x => x.ChangeType = CategoryLinkChangeType.Add);

            var sut = new CategoryLinkStore(Config.Storage);

            await sut.StoreCategoryLinks(group, categoryName, changes, CancellationToken.None).ConfigureAwait(false);

            var actual = (await sut.GetCategoryLinks(group, categoryName, CancellationToken.None).ConfigureAwait(false))
                         .ToList();

            actual.All(x => x.CategoryGroup == group).Should().BeTrue();
            actual.All(x => x.CategoryName.Equals(categoryName, StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            actual.Should().BeEquivalentTo(changes, opt => opt.ExcludingMissingMembers());
        }
        public async Task StoreCategoryLinksAddsMultipleItemsWithDifferentBatchSizesAndMixedChangedTypesTest(
            int itemCount)
        {
            var builder = Model.BuildStrategy.Clone();

            builder.TypeCreators.OfType <EnumerableTypeCreator>().Single().AutoPopulateCount = itemCount;

            const CategoryGroup group = CategoryGroup.Gender;
            var categoryName          = Guid.NewGuid().ToString();
            var changes = Model.Create <List <CategoryLinkChange> >();

            changes.Count.Should().Be(itemCount);

            var sut = new CategoryLinkStore(Config.Storage);

            await sut.StoreCategoryLinks(group, categoryName, changes, CancellationToken.None).ConfigureAwait(false);

            var actual = (await sut.GetCategoryLinks(group, categoryName, CancellationToken.None).ConfigureAwait(false))
                         .ToList();

            actual.All(x => x.CategoryGroup == group).Should().BeTrue();
            actual.All(x => x.CategoryName.Equals(categoryName, StringComparison.OrdinalIgnoreCase)).Should().BeTrue();
            actual.Should().BeEquivalentTo(
                changes.Where(x => x.ChangeType == CategoryLinkChangeType.Add),
                opt => opt.ExcludingMissingMembers());
        }
Example #7
0
        private static TableOperation BuildLinkChangeTableOperation(
            CategoryGroup categoryGroup,
            string categoryName,
            CategoryLinkChange change)
        {
            var link = new CategoryLink
            {
                CategoryGroup = categoryGroup,
                CategoryName  = categoryName,
                ProfileId     = change.ProfileId
            };
            var            adapter = new CategoryLinkAdapter(link);
            TableOperation operation;

            if (change.ChangeType == CategoryLinkChangeType.Add)
            {
                operation = TableOperation.InsertOrReplace(adapter);
            }
            else
            {
                // We don't care about concurrency here because we are removing the item
                adapter.ETag = "*";

                operation = TableOperation.Delete(adapter);
            }
            return(operation);
        }
Example #8
0
        public CreateEditGroupPage(CategoryGroup group = null, string _categoryId = "", EMenuType type = EMenuType.Undefined)
        {
            InitializeComponent();

            Group      = group;
            categoryId = _categoryId;
            _type      = type;

            if (Group == null)
            {
                LoadTotals();
                this.Title          = AppResource.lblCreateGroup;
                swtActive.IsToggled = true;
            }
            else
            {
                isEdit     = true;
                this.Title = AppResource.lblEditGroup;

                txtName.Text            = Group.Name;
                swtActive.IsToggled     = !Group.IsDisabled;
                txtPosition.Text        = group.OrderingNumber.ToString();
                lblTotalPositions.Text += group.TotalItens;
            }

            this.BindingContext = Group;
        }
        public async Task <IActionResult> Edit(int id, CategoryGroup categoryGroup)
        {
            if (id != categoryGroup.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(categoryGroup);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CategoryGroupExists(categoryGroup.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(categoryGroup));
        }
Example #10
0
        public async Task <ServiceResult> PostEditBlockRssBind([FromBody] ViewModel.ContentManager.CategoryRssBindEditVM model)
        {
            try
            {
                //Clean All Blocks Then Add BlockRssIdBind
                var res = await ContentManagerRepository.DeleteUserCategoriesBlocks();

                foreach (var CategoryGroup in model.BlockRssBind.GroupBy(q => q.CategoryId))
                {
                    foreach (var BlockCodeGroup in CategoryGroup.GroupBy(q => q.BlockCode))
                    {
                        var BlockModel = new Models.ContentManager.Block
                        {
                            code         = BlockCodeGroup.FirstOrDefault().BlockCode,
                            blockrssbind = (from b in BlockCodeGroup select b.RssId).ToList()
                        };
                        res = await ContentManagerRepository.EditCategoryBlocks(BlockCodeGroup.FirstOrDefault().CategoryId, BlockModel);
                    }
                }
                return(new ViewModel.ServiceResult()
                {
                    ServiceResultStatus = (int)Rdio.Util.Common.ServiceResultStatus.OK,
                    ServiceResultMassage = Util.Common.ServiceResultMessage.OKMessage.ToString()
                });
            }
            catch (Exception ex)
            {
                return(new ViewModel.ServiceResult()
                {
                    ServiceResultStatus = (int)Rdio.Util.Common.ServiceResultStatus.Error,
                    ServiceResultMassage = ex.GetBaseException().Message
                });
            }
        }
        public void Process(Website website)
        {
            Console.WriteLine($"{nameof(CategoryParser)} Start");
            sw.Start();
            var categoryGroups = new List <CategoryGroup>();
            var categories     = new List <Category>();

            var document = SouqApi.GetCategories();
            var divNodes = document.DocumentNode.Descendants().FindByNameNClass("div", "grouped-list");

            foreach (var divNode in divNodes)
            {
                var categoryGroup = new CategoryGroup
                {
                    Id             = Guid.NewGuid(),
                    Name           = divNode.PreviousSibling.InnerText.Cleanify(),
                    Parent         = null,
                    Categories     = new List <Category>(),
                    CategoryGroups = new List <CategoryGroup>()
                };

                ParseRecursively(categories, categoryGroup, divNode);

                categoryGroups.Add(categoryGroup);
            }

            website.CategoryGroups = categoryGroups;
            website.Categories     = categories;
            sw.Stop();
            Console.WriteLine($"{nameof(CategoryParser)} ElapseTime: {sw.Elapsed.ToString()}");
        }
Example #12
0
        public async Task <IActionResult> AddCategoryGroup(CategoryGroup categoryGroup)
        {
            if (this.ModelState.IsValid)
            {
                ApplicationUser user = await this.userRepository.FindByNameAsync(this.User.Identity.Name);

                categoryGroup.UserId = user.Id;

                try
                {
                    await this.categoryGroupRepository.AddAsync(categoryGroup);

                    return(this.RedirectToAction("Index"));
                }
                catch (EntityAlreadyExistsException)
                {
                    this.ModelState.AddModelError(string.Empty, "A category group with this name already exists.");
                }
                catch (RepositoryException)
                {
                    this.ModelState.AddModelError(string.Empty, "Failed to add category group, an unexpected error occured.");
                }
            }

            return(this.View(categoryGroup));
        }
        private void ParseRecursively(List <Category> categories, CategoryGroup categoryGroup, HtmlNode container)
        {
            var ulNode  = container.ChildNodes.SingleByName("ul");
            var liNodes = ulNode.ChildNodes.FindByName("li");

            foreach (var liNode in liNodes)
            {
                if (liNode.Attributes.Contains("class") &&
                    liNode.Attributes["class"].Value == "parent")
                {
                    var aNode = liNode.ChildNodes.SingleByName("a");

                    var childCategoryGroup = new CategoryGroup()
                    {
                        Id             = Guid.NewGuid(),
                        Name           = aNode.InnerText.Cleanify(),
                        Parent         = categoryGroup,
                        Categories     = new List <Category>(),
                        CategoryGroups = new List <CategoryGroup>()
                    };

                    ParseRecursively(categories, childCategoryGroup, liNode);

                    categoryGroup.CategoryGroups.Add(childCategoryGroup);
                }
                else
                {
                    var aNode = liNode.ChildNodes.SingleByName("a");
                    var url   = aNode.Attributes["href"].Value;

                    if (url.ExtractOperation() == "list" && !url.HasFilterTags())
                    {
                        var category = categories.SingleOrDefault(l => l.Url.ToLower() == aNode.Attributes["href"].Value.ToLower());

                        if (category != null)
                        {
                            category.CategoryGroups.Add(categoryGroup);
                        }
                        else
                        {
                            category = new Category()
                            {
                                Id             = Guid.NewGuid(),
                                Name           = aNode.InnerText.Cleanify(),
                                Url            = aNode.Attributes["href"].Value,
                                CategoryGroups = new List <CategoryGroup>()
                                {
                                    categoryGroup
                                },
                                IsFaulty = false
                            };

                            categories.Add(category);
                        }

                        categoryGroup.Categories.Add(category);
                    }
                }
            }
        }
        public async Task StoreCategoryLinkCreatesTableAndAddsCategoryLinkWhenTableNotFoundTest()
        {
            // Retrieve storage account from connection-string
            var storageAccount = CloudStorageAccount.Parse(Config.Storage.ConnectionString);

            // Create the table client
            var client = storageAccount.CreateCloudTableClient();

            var table = client.GetTableReference("CategoryLinks");

            await table.DeleteIfExistsAsync().ConfigureAwait(false);

            const CategoryGroup group = CategoryGroup.Gender;
            var categoryName          = Guid.NewGuid().ToString();
            var change = Model.Create <CategoryLinkChange>().Set(x => x.ChangeType = CategoryLinkChangeType.Add);

            var sut = new CategoryLinkStore(Config.Storage);

            await sut.StoreCategoryLink(group, categoryName, change, CancellationToken.None).ConfigureAwait(false);

            var links = await sut.GetCategoryLinks(group, categoryName, CancellationToken.None).ConfigureAwait(false);

            var actual = links.Single();

            actual.CategoryGroup.Should().Be(group);
            actual.CategoryName.Should().Be(categoryName.ToUpperInvariant());
            actual.ProfileId.Should().Be(change.ProfileId);
        }
    public async Task <Tuple <CategoryGroup, CategoryGroup> > Reorder(Tuple <ReorderItemRequest, ReorderItemRequest> request)
    {
        using (var connection = new NpgsqlConnection(ConnectionString))
        {
            await connection.OpenAsync();

            string sql = $@"UPDATE category_group
          SET sort_order = @Item1SortOrder
          WHERE id = @Item1Id
          RETURNING {RETURN_OBJECT};
          
          UPDATE category_group
          SET sort_order = @Item2SortOrder
          WHERE id = @Item2Id
          RETURNING {RETURN_OBJECT};";

            GridReader gridReader = await connection.QueryMultipleAsync(sql, new {
                Item1Id        = request.Item1.Id,
                Item1SortOrder = request.Item1.SortOrder,
                Item2Id        = request.Item2.Id,
                Item2SortOrder = request.Item2.SortOrder
            });

            CategoryGroup item1 = (await gridReader.ReadAsync <CategoryGroup>()).First();
            CategoryGroup item2 = (await gridReader.ReadAsync <CategoryGroup>()).First();

            return(new Tuple <CategoryGroup, CategoryGroup>(item1, item2));
        }
    }
        private static void DetermineCategoryChanges(
            CategoryGroup categoryGroup,
            string originalName,
            string updatedName,
            ProfileChangeResult result)
        {
            // Categories are stored with case insensitive keys to avoid duplicates
            // So we don't care if just the case has changed for the category link
            if (HasStringChanged(originalName, updatedName, StringComparison.OrdinalIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(originalName) == false)
                {
                    // There was previous a gender assigned
                    result.AddChange(categoryGroup, originalName, CategoryLinkChangeType.Remove);

                    result.ProfileChanged = true;
                }

                if (string.IsNullOrWhiteSpace(updatedName) == false)
                {
                    // There is a new gender assigned
                    result.AddChange(categoryGroup, updatedName, CategoryLinkChangeType.Add);

                    result.ProfileChanged = true;
                }
            }
        }
Example #17
0
        public async Task StoreCategoryLinks(CategoryGroup categoryGroup, string categoryName, IEnumerable <CategoryLinkChange> changes, CancellationToken cancellationToken)
        {
            Ensure.String.IsNotNullOrWhiteSpace(categoryName, nameof(categoryName));
            Ensure.Any.IsNotNull(changes, nameof(changes));

            var table = GetTable(TableName);

            var batch = new TableBatchOperation();

            foreach (var change in changes)
            {
                if (batch.Count == 100)
                {
                    // Batches can only handle 100 items, need to execute this batch
                    await ExecuteBatch(table, batch, cancellationToken).ConfigureAwait(false);

                    batch.Clear();
                }

                var operation = BuildLinkChangeTableOperation(categoryGroup, categoryName, change);

                batch.Add(operation);
            }

            if (batch.Count == 0)
            {
                // We were provided a changes instance but no changes to be made
                return;
            }

            await ExecuteBatch(table, batch, cancellationToken).ConfigureAwait(false);
        }
Example #18
0
        public async void Create()
        {
            try
            {
                Acr.UserDialogs.UserDialogs.Instance.ShowLoading(AppResource.alertLoading);



                CategoryGroup group = new CategoryGroup();


                group.Name           = txtName.Text;
                group.IsDisabled     = !swtActive.IsToggled;
                group.CompanyId      = Helpers.Settings.DisplayUserCompany;
                group.CategoryId     = categoryId;
                group.OrderingNumber = Convert.ToInt32(txtPosition.Text);
                group.MenuType       = _type;

                var result = await companyService.CreateCategoryGroup(group);

                Acr.UserDialogs.UserDialogs.Instance.Toast(AppResource.lblItemCreatedSucess);
                await App.AppCurrent.NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                this.DisplayAlert(MocoApp.Resources.AppResource.alertAlert, ex.Message, AppResource.textOk);
            }
            finally
            {
                Acr.UserDialogs.UserDialogs.Instance.HideLoading();
            }
        }
        private async Task <CategoryGroup> CreateCategoryGroup(int id)
        {
            var newGroup = new CategoryGroup($"Group {id}");

            await InsertAsync(newGroup);

            return(newGroup);
        }
        public CreateEditInformativeMenuPage(CategoryGroup group, string id = null)
        {
            InitializeComponent();
            _id    = id;
            _group = group;


            LoadMenu(id);
        }
        private async Task <Category> CreateCategory(int categoryId)
        {
            var categoryGroupFromDb = new CategoryGroup($"Group for {categoryId}");
            var categoryFromDb      = new Category($"Category {categoryId}", categoryGroupFromDb);

            await InsertAsync(categoryFromDb);

            return(categoryFromDb);
        }
        private async Task ArrangeWith(CategoryGroup groupToReturnFromGet)
        {
            await ClearDatabaseAsync();

            if (groupToReturnFromGet != null)
            {
                await InsertAsync(groupToReturnFromGet);
            }
        }
Example #23
0
        public Task StoreCategoryLink(CategoryGroup categoryGroup, string categoryName, CategoryLinkChange change, CancellationToken cancellationToken)
        {
            Ensure.String.IsNotNullOrWhiteSpace(categoryName, nameof(categoryName));
            Ensure.Any.IsNotNull(change, nameof(change));

            var operation = BuildLinkChangeTableOperation(categoryGroup, categoryName, change);
            var table     = GetTable(TableName);

            return(ExecuteWithCreateTable(table, operation, cancellationToken));
        }
Example #24
0
        public async Task <IActionResult> EditCategoryGroup(int id)
        {
            CategoryGroup model = await this.categoryGroupRepository.GetAsync(id);

            if (model == null)
            {
                return(this.RedirectToAction("Index"));
            }

            return(this.View(model));
        }
Example #25
0
        public async Task <IActionResult> Create(CategoryGroup categoryGroup)
        {
            if (ModelState.IsValid)
            {
                _context.Add(categoryGroup);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(categoryGroup));
        }
Example #26
0
        public MainForm()
        {
            InitializeComponent();
            IntializeColumns();
            PopulateComboboxes();

            _FeedGroup     = new FeedGroup();
            _CategoryGroup = new CategoryGroup();

            LoadAllFeeds();
            LoadAllCategories();
        }
    public async Task <CategoryGroup> Create(CategoryGroup categoryGroup)
    {
        using (var connection = new NpgsqlConnection(ConnectionString))
        {
            await connection.OpenAsync();

            string sql = $@"INSERT INTO category_group (name, sort_order) 
      VALUES (@Name, @SortOrder)
      RETURNING {RETURN_OBJECT}";
            return(await connection.QueryFirstOrDefaultAsync <CategoryGroup>(sql, categoryGroup));
        }
    }
Example #28
0
        private List <CategoryData> GetCityDatas(CategoryGroup ct)
        {
            List <CategoryGroup> cg     = ct.Childrens;
            List <CategoryData>  cities = new List <CategoryData>();

            cities.Add(ct.Root);
            foreach (CategoryGroup item in cg)
            {
                cities.AddRange(GetCityDatas(item));
            }
            return(cities);
        }
    public async Task <CategoryGroup> Update(CategoryGroup categoryGroup)
    {
        using (var connection = new NpgsqlConnection(ConnectionString))
        {
            await connection.OpenAsync();

            string sql = $@"UPDATE category_group
      SET name = @Name, sort_order = @SortOrder
      WHERE id = @Id
      RETURNING {RETURN_OBJECT}";
            return(await connection.QueryFirstOrDefaultAsync <CategoryGroup>(sql, categoryGroup));
        }
    }
Example #30
0
        public void AddChange(CategoryGroup categoryGroup, string categoryName, CategoryLinkChangeType changeType)
        {
            Ensure.String.IsNotNullOrWhiteSpace(categoryName, nameof(categoryName));

            var change = new CategoryChange
            {
                CategoryGroup = categoryGroup,
                CategoryName  = categoryName,
                ChangeType    = changeType
            };

            CategoryChanges.Add(change);
        }