示例#1
0
 public ServiceResult <DtoCategory> Add(DtoCategory item)
 {
     try
     {
         var menuExists = Repository.DbContext.Menus.Any(m => m.Id == item.Id);
         if (!menuExists)
         {
             return(new ServiceResult <DtoCategory>
             {
                 Success = false,
                 ErrorMessage = "Menu not found"
             });
         }
         var result = Repository.Create(new Category()
         {
             Name   = item.CategoryName,
             MenuId = item.MenuId
         });
         return(new ServiceResult <DtoCategory>()
         {
             Item = new DtoCategory(result),
             Success = true
         });
     }
     catch (Exception ex)
     {
         //Log exception
         return(new ServiceResult <DtoCategory>()
         {
             Success = false,
             Exception = ex,
             ErrorMessage = ex.Message
         });
     }
 }
        public ServiceResult <DtoCategory> Add(DtoCategory item)
        {
            //Repository.DbContext.Set<>
            var menuExists = DbContext.Menus.Any(x => x.Id == item.MenuId);

            if (!menuExists)
            {
                return new ServiceResult <DtoCategory>
                       {
                           Success      = false,
                           ErrorMessage = "2404"
                       }
            }
            ;

            var newCategory = new Category
            {
                Id     = 0,
                Name   = item.CategoryName,
                MenuId = item.MenuId
            };
            var result = Repository.Create(newCategory);

            return(new ServiceResult <DtoCategory>()
            {
                Success = true,
                Item = new DtoCategory(result)
            });
        }
 public ServiceResult <DtoCategory> Remove(DtoCategory item)
 {
     try
     {
         Repository.Delete(new Category()
         {
             CategoryID   = item.CategoryID,
             CategoryName = item.CategoryName,
             MenuID       = item.MenuID
         });
         return(new ServiceResult <DtoCategory>()
         {
             Success = true
         });
     }
     catch (Exception ex)
     {
         //Log Exception
         return(new ServiceResult <DtoCategory>()
         {
             Success = false,
             Exception = ex,
             ErrorMessage = ex.Message
         });
     }
 }
        public ActionResult CreateCategory(DtoCategory request)
        {
            ServiceResult <DtoCategory> result = _categoriesService.Add(request);

            if (result.Success)
            {
                return(Json(result.Item));
            }
            return(new HttpStatusCodeResult(400, result.ErrorMessage));
        }
示例#5
0
        public void Edit(DtoCategory category)
        {
            Category data = new Category();

            data.Id     = category.Id;
            data.Name   = category.Name;
            data.Active = category.Active;

            base.Update(data, category.Id);
            base.Save();
        }
示例#6
0
        public void AddCategory_ValidInput_ExpectTwoItems()
        {
            //Act
            //add menus first if none exist in the database!!!
            //DtoMenu menu1 = new DtoMenu()
            //{
            //    TypeEnum = MenuType.Meals,
            //    RestaurantName = "Seavus Restaurant"
            //};

            //DtoMenu menu2 = new DtoMenu()
            //{
            //    TypeEnum = MenuType.Drinks,
            //    RestaurantName = "Seavus Restaurant"
            //};

            DtoCategory category1 = new DtoCategory()
            {
                MenuId       = 1,
                CategoryName = "Salads"
            };

            DtoCategory category2 = new DtoCategory()
            {
                MenuId       = 2,
                CategoryName = "Sodas"
            };

            DtoCategory category3 = new DtoCategory()
            {
                MenuId       = 1,
                CategoryName = "Sandwiches"
            };

            //Arrange
            var categoryService  = new CategoryService();
            var result1          = categoryService.Add(category1); // will add them to the database each time the test is run, and the entries are repeated
            var result2          = categoryService.Add(category2);
            var result3          = categoryService.Add(category3);
            var resultCategories = categoryService.LoadAll();

            //Assert
            Assert.IsNotNull(result1);
            Assert.IsTrue(result1.Success);
            Assert.IsNotNull(result2);
            Assert.IsTrue(result2.Success);
            Assert.IsNotNull(result3);
            Assert.IsTrue(result3.Success);
            Assert.IsNotNull(resultCategories);
            Assert.IsTrue(resultCategories.Success);
            Assert.IsNotNull(resultCategories.ListItems);
            //Assert.AreEqual(2, resultCategories.ListItems.Count);
            Assert.IsTrue(resultCategories.ListItems.Count >= 3); // since test method adds the same entries to the database, here we check if there are at least 3 created
        }
        public static DtoCategory ToDto(Category category)
        {
            var dto = new DtoCategory
            {
                Id       = category.Id,
                Name     = category.Name,
                Keywords = category.Keywords != null?category.Keywords.Select(ToDto).ToList() : null
            };

            return(dto);
        }
示例#8
0
        public DtoCategory GetById(int id)
        {
            var data = base.Get(id);

            DtoCategory category = new DtoCategory();

            category.Id     = data.Id;
            category.Name   = data.Name;
            category.Active = data.Active;

            return(category);
        }
        public static Category ToDomain(DtoCategory dtoCategory)
        {
            var category = new Category
            {
                Id       = dtoCategory.Id,
                Name     = dtoCategory.Name,
                Keywords = dtoCategory.Keywords != null
                    ? dtoCategory.Keywords.Select(ToDomain).ToList() : null
            };

            return(category);
        }
        public DtoCategory GetCategory(Guid id)
        {
            if (id == null)
            {
                return(new DtoCategory());
            }

            var categoryItem = this.GetById(id);

            DtoCategory category = _mapper.Map <Category, DtoCategory>(categoryItem);

            return(category);
        }
        public static DtoCategory ToDTO(this Category model)
        {
            if (model == null)
            {
                return(null);
            }
            var dto = new DtoCategory();

            dto.Id   = model.Id;
            dto.Name = model.Name;

            return(dto);
        }
示例#12
0
 public async Task CreateCategory(DtoCategory category)
 {
     try
     {
         await this.categorizer.AddCategory(CategorizerConverter.ToDomain(category));
     }
     catch (CategorizerExceptionBase ex)
     {
         throw new FaultException <CategorizerFaultBase>(
                   new CategorizerFaultBase {
             Message = ex.Message
         });
     }
 }
        public static Category ToRepository(this DtoCategory dto)
        {
            if (dto == null)
            {
                return(null);
            }
            var model = new Category();

            model.Id          = dto.Id;
            model.Name        = dto.Name;
            model.Category_id = dto.RefCategory?.Id;

            return(model);
        }
        private DtoCategory CreateLinksForCategory(DtoCategory category)
        {
            var objId = new { id = category.Id };

            category.Links = new List <LinkDto>();
            category.Links.Add(
                new LinkDto(_linkGenerator.GetPathByAction(nameof(this.GetCategory), "Categories", objId), "self", "GET"));
            category.Links.Add(
                new LinkDto(_linkGenerator.GetPathByAction(nameof(this.PutCategory), "Categories", objId), "update_category", "PUT"));
            category.Links.Add(
                new LinkDto(_linkGenerator.GetPathByAction(nameof(this.DeleteCategory), "Categories", objId), "delete_category", "DELETE"));

            return(category);
        }
        public object UpdateCategory(DtoCategory model)
        {
            if (model == null)
            {
                return(new DtoCategory());
            }

            Category category = this.GetById(model.CategoryId);

            category.Id          = model.CategoryId;
            category.Name        = model.CategoryName;
            category.UpdatedBy   = model.UpdatedBy;
            category.UpdatedDate = DateTime.Now;

            this.Update(category);
            this.Save();

            return(model);
        }
        public object PostCategory(DtoCategory model)
        {
            if (model == null)
            {
                return(new DtoCategory());
            }

            Category category = new Category();

            category.Name        = model.CategoryName;
            category.CreatedBy   = "Test: Safa";
            category.CreatedDate = DateTime.Now;

            this.Add(category);
            this.Save();

            model.CategoryId = category.Id;

            return(model);
        }
        //private readonly MenuRepository _menuRepository;

        //public CategoryService()
        //{
        //    _menuRepository = new MenuRepository();
        //}

        public ServiceResult <DtoCategory> Add(DtoCategory item)
        {
            try
            {
                //if (_menuRepository.GetById(item.MenuId) != null)
                //{
                if (Context.Menus.Any(m => m.MenuId == item.MenuId))
                {
                    var result = Repository.Create(new Category()
                    {
                        MenuId       = item.MenuId,
                        CategoryName = item.CategoryName
                    });

                    return(new ServiceResult <DtoCategory>()
                    {
                        Item = new DtoCategory(result),
                        Success = true
                    });
                }
                else
                {
                    return(new ServiceResult <DtoCategory>()
                    {
                        Success = false,
                        ErrorMessage = "Menu with requested ID does not exist."
                    });
                }
            }
            catch (Exception ex)
            {
                //Log exception
                return(new ServiceResult <DtoCategory>()
                {
                    Success = false,
                    Exception = ex,
                    ErrorMessage = ex.Message
                });
            }
        }
示例#18
0
        public ServiceResult <DtoCategory> Add(DtoCategory type)
        {
            try
            {
                var resultMenu = /*_menuRepository.GetById(type.MenuId);*/ Repository.DbContext.Menues.Any(m => m.Id == type.MenuId);

                if (resultMenu)
                {
                    var result = Repository.Create(new Category()
                    {
                        Id     = 0,
                        Name   = type.CategoryName,
                        MenuId = type.MenuId
                    });
                    var resultFinal = new  ServiceResult <DtoCategory>()
                    {
                        Item    = new DtoCategory(result),
                        Success = true
                    };
                    return(resultFinal);
                }
                else
                {
                    return(new ServiceResult <DtoCategory>()
                    {
                        Success = false,
                    });
                }
            }
            catch (Exception ex)
            {
                return(new ServiceResult <DtoCategory>()
                {
                    Success = false,
                    Exception = ex,
                    ErrorMessage = ex.Message
                });
            }
        }
 public ServiceResult <DtoCategory> Add(DtoCategory item)
 {
     try
     {
         using (var service = new MenuService())
         {
             if (!service.LoadAll().Items.Any(m => m.MenuID == item.MenuID))
             {
                 return new ServiceResult <DtoCategory>
                        {
                            Success      = false,
                            ErrorMessage = "Menu id does not exist in this context"
                        }
             }
             ;
         }
         // Treba da se napravi proverka dali postoi MenuID
         var result = Repository.Create(new Category()
         {
             CategoryName = item.CategoryName,
             MenuID       = item.MenuID
         });
         return(new ServiceResult <DtoCategory>()
         {
             Item = new DtoCategory(result),
             Success = true
         });
     }
     catch (Exception ex)
     {
         //Log Exception
         return(new ServiceResult <DtoCategory>()
         {
             Success = false,
             Exception = ex,
             ErrorMessage = ex.Message
         });
     }
 }
 public ServiceResult <DtoCategory> Load(DtoCategory item)
 {
     try
     {
         var result = Repository.Get(item.CategoryID);
         return(new ServiceResult <DtoCategory>()
         {
             Item = new DtoCategory(result),
             Success = true
         });
     }
     catch (Exception ex)
     {
         //Log Exception
         return(new ServiceResult <DtoCategory>()
         {
             Success = false,
             Exception = ex,
             ErrorMessage = ex.Message
         });
     }
 }
 public ServiceResult <DtoCategory> Edit(DtoCategory item)
 {
     try
     {
         using (var service = new MenuService())
         {
             if (!service.LoadAll().Items.Any(m => m.MenuID == item.MenuID))
             {
                 return new ServiceResult <DtoCategory>
                        {
                            Success      = false,
                            ErrorMessage = "Menu id does not exist in this context"
                        }
             }
             ;
         }
         Repository.Insert(new Category()
         {
             CategoryID   = item.CategoryID,
             CategoryName = item.CategoryName,
             MenuID       = item.MenuID
         });
         return(new ServiceResult <DtoCategory>()
         {
             Success = true
         });
     }
     catch (Exception ex)
     {
         //Log Exception
         return(new ServiceResult <DtoCategory>()
         {
             Success = false,
             Exception = ex,
             ErrorMessage = ex.Message
         });
     }
 }
        public ServiceResult <DtoCategory> Edit(DtoCategory item)
        {
            try
            {
                if (Context.Menus.Any(m => m.MenuId == item.MenuId))
                {
                    Repository.Update(new Category()
                    {
                        MenuId       = item.MenuId,
                        CategoryName = item.CategoryName
                    });

                    return(new ServiceResult <DtoCategory>()
                    {
                        Success = true
                    });
                }
                else
                {
                    return(new ServiceResult <DtoCategory>()
                    {
                        Success = false,
                        ErrorMessage = "Menu with requested ID does not exist."
                    });
                }
            }
            catch (Exception ex)
            {
                //Log exception
                return(new ServiceResult <DtoCategory>()
                {
                    Success = false,
                    Exception = ex,
                    ErrorMessage = ex.Message
                });
            }
        }
示例#23
0
        public void Save(ref DtoCategory category)
        {
            var repo = category.ToRepository();

            if (repo.Id == 0)
            {
                repo.Id = Insert(repo, "Category");
            }
            else
            {
                Update(repo, "Category");
            }

            List <DtoCategory> subcategories;

            if (category.SubCategories != null)
            {
                subcategories = new List <DtoCategory>();
                foreach (var subcCategory in category.SubCategories)
                {
                    var dbSubCategory = subcCategory.ToRepository();
                    dbSubCategory.Category_id = repo.Id;
                    if (dbSubCategory.Id == 0)
                    {
                        dbSubCategory.Id = Insert(dbSubCategory, "Category");
                    }
                    else
                    {
                        Update(dbSubCategory, "Category");
                    }
                    subcategories.Add(FillCategory(dbSubCategory));
                }
                category.SubCategories = subcategories;
            }
            category = FillCategory(repo);
        }
示例#24
0
        public void AddCategory_ValidInput_ExpectTwoItems()
        {
            DtoCategory category1 = new DtoCategory()
            {
                CategoryName = "Food",
                MenuID       = 1
            };
            DtoCategory category2 = new DtoCategory()
            {
                CategoryName = "Drink",
                MenuID       = 2
            };
            DtoCategory category3 = new DtoCategory()
            {
                CategoryName = "Wines",
                MenuID       = 10
            };

            var service          = new CategoryService();
            var result1          = service.Add(category1);
            var result2          = service.Add(category2);
            var result3          = service.Add(category3);
            var resultCategories = service.LoadAll();

            Assert.IsNotNull(result1);
            Assert.IsTrue(result1.Success);

            Assert.IsNotNull(result2);
            Assert.IsTrue(result2.Success);

            Assert.IsNotNull(result3);
            Assert.IsFalse(result3.Success);

            Assert.IsNotNull(resultCategories);
            Assert.IsTrue(resultCategories.Success);
        }
示例#25
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Init DB Session");
            Console.ForegroundColor = ConsoleColor.Gray;
            new IhChegou.Repository.Query.ProductQueries();

            Console.ForegroundColor = ConsoleColor.DarkBlue;
            Console.WriteLine("Searching...");
            Console.ForegroundColor = ConsoleColor.White;

            const string URL_BASE = "https://consultaremedios.com.br";
            const string URL_LISTA_MEDICAMENTOS = URL_BASE + "/medicamentos";

            var errorUrl = new ConcurrentBag <string>();


            var client = new WebClient();

            client.Encoding = Encoding.UTF8;

            var response = client.DownloadString(URL_LISTA_MEDICAMENTOS);

            var document = new HtmlDocument();

            document.LoadHtml(response);

            var letters = document.DocumentNode.SelectNodes("//*[@id=\"letras\"]/div/div/div/div/div[2]/*").Select(i => i.GetAttributeValue("href", ""));

            var prodUrls = new List <string>();

            foreach (var item in letters)
            {
                var prodUrl = new List <string>();
                int page    = 1;
                do
                {
                    response = client.DownloadString(URL_BASE + item + "?pagina=" + page);
                    document = new HtmlDocument();
                    document.LoadHtml(response);
                    prodUrl = document.DocumentNode.SelectNodes("//*[@class=\"product-block__title\"]/a")?.Select(i => i.GetAttributeValue("href", ""))?.ToList();
                    if (prodUrl != null)
                    {
                        prodUrls.AddRange(prodUrl);
                    }
                    page++;
                } while (prodUrl != null && prodUrl?.Count() != 0);
            }

            //  var nodes = documents[0].DocumentNode.SelectNodes("//div[@class='item col-xs-12 col-sm-4 col-md-3']");


            // Parallel.ForEach(nodes, new ParallelOptions { MaxDegreeOfParallelism = 1 }, (nod) =>
            foreach (var prodUrl in prodUrls)
            {
                var ProdResponse    = client.DownloadString(URL_BASE + prodUrl);
                var productDocument = new HtmlDocument();
                productDocument.LoadHtml(ProdResponse);


                var query = new IhChegou.Repository.Query.ProductQueries();

                var product = new DtoProduct();
                product.Name = HttpUtility.HtmlDecode(productDocument.DocumentNode.SelectSingleNode("//*[@class=\"product-header__title\"]").InnerText);

                try
                {
                    product.Serving = HttpUtility.HtmlDecode(productDocument.DocumentNode.SelectSingleNode("//*[@id=\"indication-collapse\"]").InnerText);



                    var producerName = productDocument.DocumentNode.SelectSingleNode("//*[@class=\"cr-icon-factory product-block__meta-icon\"]/..").InnerText;

                    var producer = query.GetAllProducers().Where(i => i.Name == producerName).SingleOrDefault();
                    if (producer == null)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkMagenta;
                        Console.WriteLine("New Producer - " + producerName);
                        producer = new DtoProducer()
                        {
                            Name = producerName
                        };
                        query.Save(ref producer);
                    }
                    product.Producer = producer;

                    var dbProduct = query.GetProductByNameAndProducer(product.Name, product.Producer);
                    if (dbProduct != null)
                    {
                        product = dbProduct;
                    }
                    else
                    {
                        Console.WriteLine("New Product - " + product.Name);
                    }

                    var skuUrls = productDocument.DocumentNode.SelectNodes("//*[@class=\"presentation-offer-info__description\"]/a")?.Select(i => i.GetAttributeValue("href", ""))?.ToList();

                    foreach (var skuUrl in skuUrls)
                    {
                        var skuResponse  = client.DownloadString(URL_BASE + skuUrl);
                        var skutDocument = new HtmlDocument();
                        skutDocument.LoadHtml(skuResponse);

                        var infoNodes = skutDocument.DocumentNode.SelectNodes("//*[@class=\"extra-infos-block\"]");

                        if (skuUrls.IndexOf(skuUrl) == 0)
                        {
                            foreach (var infoNode in infoNodes)
                            {
                                switch (infoNode.FirstChild.InnerText)
                                {
                                case "Tipo do Medicamento":
                                    if (infoNode.LastChild.InnerText == "Referência")
                                    {
                                        product.Type = Global.Enumerators.ProductType.Reference;
                                    }
                                    if (infoNode.LastChild.InnerText == "Similar")
                                    {
                                        product.Type = Global.Enumerators.ProductType.Similar;
                                    }
                                    if (infoNode.LastChild.InnerText == "Genérico")
                                    {
                                        product.Type = Global.Enumerators.ProductType.Generic;
                                    }
                                    break;

                                case "Necessita de Receita":
                                    if (infoNode.SelectSingleNode("//*/b").InnerText == "Sim")
                                    {
                                        product.NeedRecipe = true;
                                    }
                                    break;

                                case "Princípio Ativo":
                                {
                                    var prodPrinciples = new List <DtoPrinciple>();

                                    var princepleText = infoNode.LastChild.InnerText.Split('+');

                                    if (princepleText.Length > 0)
                                    {
                                        foreach (var item in princepleText)
                                        {
                                            var principle = query.GetAllPrnciples().Where(i => i.Name == item).SingleOrDefault();

                                            if (principle == null)
                                            {
                                                Console.ForegroundColor = ConsoleColor.DarkYellow;
                                                Console.WriteLine("New Principle - " + item);
                                                principle = new DtoPrinciple()
                                                {
                                                    Name = item
                                                };
                                                query.Save(ref principle);
                                            }
                                            prodPrinciples.Add(principle);
                                        }
                                        foreach (var principle in prodPrinciples)
                                        {
                                            product.Principles = product.Principles ?? new List <DtoPrinciple>();
                                            if (product.Principles.FirstOrDefault(i => i.Id == principle.Id) == null)
                                            {
                                                product.Principles.Add(principle);
                                            }
                                        }
                                    }
                                }
                                break;
                                }
                            }
                            var categorias = productDocument.DocumentNode.SelectNodes("//*[@id='product-page']/div[1]/div/div[1]/div/div/nav/ul/li").Select(i => i.InnerText.Replace("\n", "")).ToList();

                            categorias.RemoveAt(categorias.IndexOf(categorias.FirstOrDefault()));
                            categorias.RemoveAt(categorias.IndexOf(categorias.LastOrDefault()));

                            var ProdCategories = new List <DtoCategory>();
                            foreach (var item in categorias)
                            {
                                var category = query.GetCategory(item);

                                if (category == null)
                                {
                                    Console.ForegroundColor = ConsoleColor.Cyan;
                                    Console.WriteLine("New Category - " + item);

                                    var position = categorias.IndexOf(item);
                                    category = new DtoCategory()
                                    {
                                        Name = item
                                    };
                                    if (position > 0)
                                    {
                                        var father = query.GetCategory(categorias[position - 1]);
                                        father.SubCategories = father.SubCategories ?? new List <DtoCategory>();
                                        father.SubCategories.Add(category);
                                        category = father;
                                    }
                                    query.Save(ref category);
                                }
                                category = query.GetCategory(item);
                                ProdCategories.Add(category);
                            }
                            foreach (var category in ProdCategories)
                            {
                                product.Categories = new List <DtoCategory>();
                                product.Categories.Add(query.GetCategory(category.Name));
                            }
                        }

                        var newSku = new DtoSku
                        {
                            Image = skutDocument.DocumentNode.SelectSingleNode("//*[@class=\"product-header__beauty-image\"]/img")?.GetAttributeValue("src", ""),
                            Name  = skutDocument.DocumentNode.SelectSingleNode("//*[@id=\"product-page\"]/div[1]/div/div[2]/div[2]/h1").InnerText,
                        };
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        var dbsku = product.Skus?.FirstOrDefault(i => i.Name == newSku.Name);
                        if (dbsku == null)
                        {
                            Console.WriteLine("New Sku - " + newSku.Name);
                        }
                        else
                        {
                            newSku.Id = dbsku.Id;
                        }
                        product.Skus = product.Skus ?? new List <DtoSku>();
                        if (product.Skus.Where(i => i.Id == newSku.Id).Count() > 0)
                        {
                            product.Skus.Remove(product.Skus.Where(i => i.Id == newSku.Id).SingleOrDefault());
                        }
                        product.Skus.Add(newSku);
                    }
                    Console.ForegroundColor = ConsoleColor.Green;

                    query.Save(ref product);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"- {ex.Message} -{ ex.InnerException?.Message}");
                    Console.ResetColor();
                }
            }
            //});

            var writer = new StreamWriter("errorList.json");

            writer.WriteLine(JsonConvert.SerializeObject(errorUrl));

            writer.Close();
        }
示例#26
0
 public ServiceResult <DtoCategory> Edit(DtoCategory type)
 {
     throw new NotImplementedException();
 }
 public object UpdateCategory(DtoCategory model)
 {
     return(_categoryService.UpdateCategory(model));
 }
 public object PostCategory(DtoCategory model)
 {
     return(_categoryService.PostCategory(model));
 }
示例#29
0
 public object CategoryEdit([FromBody] DtoCategory category)
 {
     _Category.Edit(category);
     return(category.Id);
 }
 public ServiceResult <DtoCategory> Remove(DtoCategory item)
 {
     throw new NotImplementedException();
 }