コード例 #1
0
        private void GenerateCategories()
        {
            Random random = new Random();

            int productsCount       = this.Context.Products.Count();
            int categoriesMaxRandom = this.Context.Categories.Count() + 1;

            List <CategoryProducts> categoryProducts = new List <CategoryProducts>();

            for (int productId = 1; productId <= productsCount; productId++)
            {
                int categoryId = random.Next(1, categoriesMaxRandom);

                CategoryProducts categoryProduct = new CategoryProducts
                {
                    CategoryId = categoryId,
                    ProductId  = productId,
                };

                categoryProducts.Add(categoryProduct);
            }

            this.Context.CategoryProducts.AddRange(categoryProducts);
            this.Context.SaveChanges();
        }
コード例 #2
0
        public static void SetJsonCategories()
        {
            using (var db = new ProductShopContext())
            {
                var random = new Random();

                var productIds    = db.Products.AsNoTracking().Select(p => p.ProductId).OrderBy(p => p).ToArray();
                var categoryIds   = db.Categories.AsNoTracking().Select(c => c.CategoryId).ToArray();
                int categoryCount = categoryIds.Length;

                var categoryProducts = new List <CategoryProducts>();

                foreach (var p in productIds)
                {
                    for (int i = 0; i < random.Next(0, categoryCount); i++)
                    {
                        int index = random.Next(0, categoryCount);
                        while (categoryProducts.Any(cp => cp.ProductId == p && cp.CategoryId == categoryIds[index]))
                        {
                            index = random.Next(0, categoryCount);
                        }

                        var catPr = new CategoryProducts()
                        {
                            ProductId  = p,
                            CategoryId = categoryIds[index]
                        };
                        categoryProducts.Add(catPr);
                    }
                }

                db.CategoryProducts.AddRange(categoryProducts);
                db.SaveChanges();
            }
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: RumenNovachkov/DbAdvance
        static string ImportProductsXml()
        {
            var path = "products.xml";

            string xmlString = File.ReadAllText(path);

            var xmlDoc = XDocument.Parse(xmlString);

            var elements = xmlDoc.Root.Elements();

            using (var db = new ProductsShopContext())
            {
                var categoryProducts = new List <CategoryProducts>();

                var userIds     = db.Users.Select(u => u.UserId).OrderBy(u => u).ToArray();
                var categoryIds = db.Categories.Select(c => c.CategoryId).OrderBy(c => c).ToArray();

                var rnd = new Random();

                foreach (var e in elements)
                {
                    int userIndex     = rnd.Next(0, userIds.Length);
                    int sellerId      = userIds[userIndex];
                    int categoryIndex = rnd.Next(0, categoryIds.Length);
                    int categoryId    = categoryIds[categoryIndex];

                    var product = new Product()
                    {
                        Name     = e.Element("name").Value,
                        Price    = decimal.Parse(e.Element("price").Value),
                        SellerId = sellerId
                    };

                    var buyerId = rnd.Next(0, userIds.Length);

                    if (product.BuyerId != userIds[buyerId])
                    {
                        product.BuyerId = userIds[buyerId];
                    }

                    if (product.BuyerId - product.SellerId < 5 && product.BuyerId - product.SellerId > 0)
                    {
                        product.BuyerId = null;
                    }

                    var catProduct = new CategoryProducts()
                    {
                        Product    = product,
                        CategoryId = categoryId
                    };

                    categoryProducts.Add(catProduct);
                }

                db.AddRange(categoryProducts);
                db.SaveChanges();
                return($"{categoryProducts.Count} categories and products were imported from file: {path}");
            }
        }
コード例 #4
0
        static string ImportProductsFromXml()
        {
            string path = "Files/products.xml";

            string xmlString = File.ReadAllText(path);

            var xmlDoc = XDocument.Parse(xmlString);

            var elements = xmlDoc.Root.Elements();

            using (var context = new ProductsShopContext())
            {
                var catProducts = new List <CategoryProducts>();

                var userIds     = context.Users.Select(u => u.Id).ToArray();
                var categoryIds = context.Categories.Select(c => c.Id).ToArray();

                Random rnd = new Random();

                foreach (var e in elements)
                {
                    string  name  = e.Element("name").Value;
                    decimal price = decimal.Parse(e.Element("price").Value);

                    int sellerIndex = rnd.Next(0, userIds.Length);
                    int sellerId    = userIds[sellerIndex];

                    var product = new Product()
                    {
                        Name     = name,
                        Price    = price,
                        SellerId = sellerId
                    };

                    int categoryIndex = rnd.Next(0, categoryIds.Length);
                    int categoryId    = categoryIds[categoryIndex];

                    var catProduct = new CategoryProducts()
                    {
                        Product    = product,
                        CategoryId = categoryId
                    };

                    catProducts.Add(catProduct);
                }
                context.AddRange(catProducts);

                context.SaveChanges();

                return($"{catProducts.Count} products were added!");
            }
        }
コード例 #5
0
        public static string ImprotXmlProducts()
        {
            var xmlString = File.ReadAllText("Files/products.xml");

            var xmlDoc = XDocument.Parse(xmlString);

            var elements = xmlDoc.Root.Elements();

            var catProd = new List <CategoryProducts>();

            using (var db = new ProductShopContext())
            {
                var userIds     = db.Users.Select(u => u.UserId).ToArray();
                var categoryIds = db.Categories.Select(c => c.CategoryId).ToArray();

                Random rnd = new Random();

                foreach (var e in elements)
                {
                    var name  = e.Element("name").Value;
                    var price = decimal.Parse(e.Element("price").Value);

                    var sellerIndex = rnd.Next(0, userIds.Length);
                    var sellerId    = userIds[sellerIndex];

                    var product = new Product()
                    {
                        Name     = name,
                        Price    = price,
                        SellerId = sellerId
                    };

                    var categoryIndex = rnd.Next(0, categoryIds.Length);
                    var categoryId    = categoryIds[categoryIndex];

                    var catProduct = new CategoryProducts()
                    {
                        Product    = product,
                        CategoryId = categoryId
                    };

                    catProd.Add(catProduct);
                }
                db.AddRange(catProd);

                db.SaveChanges();
            }
            return($"{catProd.Count} prodcuts were imported");
        }
コード例 #6
0
        public IActionResult Index(string filter = "")
        {
            var q1 = from p in db.Products.Include(p => p.Category).ToList()
                     where string.IsNullOrEmpty(filter) ||
                     p.ProductName.Contains(filter, StringComparison.InvariantCultureIgnoreCase)
                     group p by p.Category?.CategoryName ?? "Sin Categoría"  into CategoryProducts
                     select new CategoryProductsViewModel()
            {
                CategoryName = CategoryProducts.Key,
                Items        = CategoryProducts.ToList()
            };

            ViewBag.filter = filter;

            return(View(q1.ToList()));
        }
コード例 #7
0
 public HttpResponseMessage Patch(int id, [FromBody] CategoryProducts category)
 {
     try {
         CategoryProducts categoryProduct = new CategoryProducts();
         var response = categoryProduct.CategoryProductsPatchRow(id, category.categoryName);
         if (response == 0)
         {
             return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The product with the id " + id.ToString() + " is not found to be updated"));
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.OK, category));
         }
     } catch (SqlException ex) {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
     } catch (Exception e) {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
     }
 }
コード例 #8
0
        private static CategoryProducts[] GenerateCategoryProducts(Product[] products, Category[] categories)
        {
            CategoryProducts[] categoryProducts = new CategoryProducts[products.Length];

            Random random = new Random();

            for (int i = 0; i < categoryProducts.Length; i++)
            {
                CategoryProducts categoryProduct = new CategoryProducts
                {
                    Product  = products[i],
                    Category = categories[random.Next(categories.Length - 1)]
                };

                categoryProducts[i] = categoryProduct;
            }

            return(categoryProducts);
        }
コード例 #9
0
 public HttpResponseMessage Get()
 {
     try {
         List <CategoryProducts> categoryProductsList = new List <CategoryProducts>();
         CategoryProducts        select = new CategoryProducts();
         categoryProductsList = select.CategoryProductsSelectAll();
         if (categoryProductsList.Count != 0)
         {
             return(Request.CreateResponse(HttpStatusCode.OK, categoryProductsList));
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.NoContent, "There is no products in the server"));
         }
     } catch (SqlException ex) {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
     } catch (Exception e) {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
     }
 }
コード例 #10
0
 public HttpResponseMessage Delete(int id)
 {
     try {
         CategoryProducts categoryProduct = new CategoryProducts();
         var response = categoryProduct.CategoryProductsDeleteRow(id);
         if (response == 0)
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Impossible to soft delete this row, this row doesn't exist in soft delete !"));
         }
         else
         {
             var message = Request.CreateResponse(HttpStatusCode.OK, "Product soft deleted");
             return(message);
         }
     } catch (SqlException ex) {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
     } catch (Exception e) {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
     }
 }
コード例 #11
0
        private static void InitializeCategoriesAndProducts(ProductShopContext context)
        {
            var categoryProducts = new List <CategoryProducts>();

            for (int productId = 1; productId < 201; productId++)
            {
                var categoryId = new Random().Next(1, 12);

                var categoryProduct = new CategoryProducts()
                {
                    ProductId  = productId,
                    CategoryId = categoryId
                };

                categoryProducts.Add(categoryProduct);
            }

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();
        }
コード例 #12
0
        private static void ImportCategoryProducts(ProductsShopContext context)
        {
            var productsIds = context.Products.Select(p => p.Id).ToArray();
            var categoryIds = context.Categories.Select(c => c.Id).ToArray();

            var rnd = new Random();
            var categoryProducts = new List <CategoryProducts>();

            foreach (var productId in productsIds)
            {
                var usedCategoryIds = new int[3];

                for (int i = 0; i < 3; i++)
                {
                    var categoryIndex = rnd.Next(0, categoryIds.Length);
                    var categoryId    = categoryIds[categoryIndex];

                    while (usedCategoryIds.Contains(categoryId))
                    {
                        categoryIndex = rnd.Next(0, categoryIds.Length);
                        categoryId    = categoryIds[categoryIndex];
                    }

                    usedCategoryIds[i] = categoryId;

                    var categoryProduct = new CategoryProducts
                    {
                        ProductId  = productId,
                        CategoryId = categoryId
                    };

                    categoryProducts.Add(categoryProduct);
                }
            }

            context.CategoryProducts.AddRange(categoryProducts);

            context.SaveChanges();

            Console.WriteLine($"{categoryProducts.Count} category and products combinations were added.");
        }
コード例 #13
0
        public static void ImportCategories(ShopDbContext db, IMapper mapper)
        {
            String        xmlString  = File.ReadAllText("categories.xml");
            XmlSerializer serializer = new XmlSerializer(typeof(CategoryDto[]), new XmlRootAttribute("categories"));

            CategoryDto[] deserializedCategories = (CategoryDto[])serializer.Deserialize(new StringReader(xmlString));

            List <Category> categories = new List <Category>();

            foreach (CategoryDto categoryDto in deserializedCategories)
            {
                if (!IsValid(categoryDto))
                {
                    continue;
                }

                var category = mapper.Map <Category>(categoryDto);
                categories.Add(category);
            }

            db.Categories.AddRange(categories);
            db.SaveChanges();

            List <CategoryProducts> categoriesProducts = new List <CategoryProducts>();

            for (int productId = 1; productId < 201; productId++)
            {
                var categoryId = new Random().Next(1, 11);

                var categoryProduct = new CategoryProducts()
                {
                    ProductId  = productId,
                    CategoryId = categoryId
                };

                categoriesProducts.Add(categoryProduct);
            }
            Console.WriteLine();
            db.CategorieProducts.AddRange(categoriesProducts);
            db.SaveChanges();
        }
コード例 #14
0
        public HttpResponseMessage Get(int id)
        {
            try {
                CategoryProducts categoryProduct = new CategoryProducts();

                var response = categoryProduct.CategoryProductsSelectRow(id);

                if (response.categoryId != 0)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, response));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The product with the id = " + id.ToString() + " is not found"));
                }
            } catch (SqlException ex) {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            } catch (Exception e) {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
            }
        }
コード例 #15
0
        private void GenerateCategoryProducts()
        {
            Random random = new Random();
            List <CategoryProducts> categoryProducts = new List <CategoryProducts>();

            for (int productId = 1; productId < 200; productId++)
            {
                int categoryId = random.Next(1, 12);

                CategoryProducts categoryProduct = new CategoryProducts()
                {
                    ProductId  = productId,
                    CategoryId = categoryId,
                };

                categoryProducts.Add(categoryProduct);
            }

            this.Context.CategoryProducts.AddRange(categoryProducts);
            this.Context.SaveChanges();
        }
コード例 #16
0
 public HttpResponseMessage Post([FromBody] CategoryProducts category)
 {
     try {
         CategoryProducts categoryProduct = new CategoryProducts();
         var response = categoryProduct.CategoryProductsInsertRow(category.categoryId, category.categoryName);
         if (response == 0)
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Impossible to insert new row, check out your arguments"));
         }
         else
         {
             var message = Request.CreateResponse(HttpStatusCode.Created, category);
             message.Headers.Location = new Uri(Request.RequestUri + categoryProduct.categoryId.ToString());
             return(message);
         }
     } catch (SqlException ex) {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
     } catch (Exception e) {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
     }
 }
コード例 #17
0
        private static void ReadCategoriesXml()
        {
            var config = new MapperConfiguration(x =>
            {
                x.AddProfile <ProductShopProfile>();
            });
            var mapper                 = config.CreateMapper();
            var xmlString              = File.ReadAllText("Xml/categories.xml");
            var serializer             = new XmlSerializer(typeof(CategoryDto[]), new XmlRootAttribute("categories"));
            var deserializedCategories = (CategoryDto[])serializer.Deserialize(new StringReader(xmlString));

            var categories = new List <Categories>();

            foreach (var categoryDto in deserializedCategories)
            {
                if (!IsValid(categoryDto))
                {
                    continue;
                }

                var category = mapper.Map <Categories>(categoryDto);
                categories.Add(category);
            }
            var categoryProducts = new List <CategoryProducts>();

            for (int productId = 201; productId <= 400; productId++)
            {
                var categoryId      = new Random().Next(1, 12);
                var categoryProduct = new CategoryProducts()
                {
                    ProductId  = productId,
                    CategoryId = categoryId
                };
                categoryProducts.Add(categoryProduct);
            }
            var context = new ProductShopDbContext();

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();
        }
コード例 #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (CategoryProducts != null)
            {
                CategoryProducts.NameProducts = textBox2.Text;
            }
            else
            {
                CategoryProducts = new CategoryProducts()
                {
                    NameProducts = textBox2.Text
                };
            }

            Close();

            //var c = CategoryProducts ?? new CategoryProducts();

            //c.NameProducts = textBox2.Text;

            //Close();
        }
コード例 #19
0
        static void SetCategories()
        {
            using (var context = new ProductsShopContext())
            {
                var productIds  = context.Products.Select(p => p.Id).ToArray();
                var categoryIds = context.Categories.Select(c => c.Id).ToArray();

                int categoryCount = categoryIds.Length;

                Random rnd = new Random();

                var categoryProducts = new List <CategoryProducts>();

                foreach (var p in productIds)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        int index = rnd.Next(0, categoryIds.Length);
                        while (categoryProducts.Any(cp => cp.ProductId == p &&
                                                    cp.CategoryId == categoryIds[index]))
                        {
                            index = rnd.Next(0, categoryCount);
                        }

                        var catPr = new CategoryProducts()
                        {
                            ProductId  = p,
                            CategoryId = categoryIds[index]
                        };

                        categoryProducts.Add(catPr);
                    }
                }

                context.CategoryProducts.AddRange(categoryProducts);

                context.SaveChanges();
            }
        }
        static void Main(string[] args)
        {
            List <Users>      users      = new List <Users>();
            List <Categories> categories = new List <Categories>();
            List <Products>   products   = new List <Products>();

            string readstring     = File.ReadAllText("users.xml");
            string categorystring = File.ReadAllText("categories.xml");
            string productstring  = File.ReadAllText("products.xml");


            //  var serializer1 = new XmlSerializer(typeof(UserDto[]),new XmlRootAttribute("users"));
            var serializer2 = new XmlSerializer(typeof(CategoriesDto[]), new XmlRootAttribute("categories"));
            var serializer  = new XmlSerializer(typeof(ProductsDto[]), new XmlRootAttribute("products"));


            // var desirializer1 = (UserDto[])serializer1.Deserialize(new StringReader(readstring));
            var desirializer2 = (CategoriesDto[])serializer2.Deserialize(new StringReader(categorystring));
            var desirializer  = (ProductsDto[])serializer.Deserialize(new StringReader(productstring));


            var config = new MapperConfiguration(cfg => {
                cfg.AddProfile <AutoMapperProfile>();
                cfg.CreateMap <UserDto, Users>();
                cfg.CreateMap <CategoriesDto, Categories>();
                cfg.CreateMap <ProductsDto, Products>();
            });



            var mapper = config.CreateMapper();

            /*    foreach (var user in desirializer1)
             *  {
             *
             *   bool Valid = isValid(user);
             *
             *     if (Valid == false)
             *     {
             *         continue;
             *     }
             *
             *      var currentUser = mapper.Map<Users>(user);
             *
             *     users.Add(currentUser);
             *  }
             *
             *   foreach (var category in desirializer2)
             *   {
             *       bool Valid = isValid(category);
             *
             *     if (Valid == false)
             *     {
             *         continue;
             *     }
             *
             *     var currentCategory = mapper.Map<Categories>(category);
             *
             *
             *       categories.Add(currentCategory);
             *   }
             *
             */
            int counter = 1;

            foreach (var product in desirializer)
            {
                bool Valid = isValid(product);

                if (Valid == false)
                {
                    continue;
                }

                var currentproduct = mapper.Map <Products>(product);

                int boughtId = new Random().Next(57, 87);
                int soldId   = new Random().Next(87, 112);
                currentproduct.Sellerid = soldId;
                currentproduct.BuyerId  = boughtId;

                if (counter == 4)
                {
                    currentproduct.BuyerId = null;
                    counter = 1;
                }


                counter++;
                products.Add(currentproduct);
            }


            var context = new AlbumDatabaseContext();
            List <CategoryProducts> categoryProducts = new List <CategoryProducts>();



            for (int i = 0; i < 11; i++)
            {
                int categoryID = new Random().Next(1, 10);
                int productID  = new Random().Next(3662, 3697);

                var currentCattegoryProducts = new CategoryProducts()
                {
                    CategoryId = categoryID,
                    ProductId  = productID
                };
                categoryProducts.Add(currentCattegoryProducts);
            }


            using (context)
            {
                // context.Users.AddRange(users);
                // context.Products.AddRange(products);
                //  context.Categories.AddRange(categories);

                context.CategoryProducts.AddRange(categoryProducts);

                context.SaveChanges();
            }
        }
コード例 #21
0
 public CategoryProducAddForm(CategoryProducts category) : this()
 {
     CategoryProducts = category;
     textBox2.Text    = CategoryProducts.NameProducts;
 }
コード例 #22
0
        /// <summary>
        /// Important! * DB should already contain users and categories, in order for 'ImportProductsToDb to function properly'
        /// Imports products to ProductShop database
        /// </summary>
        /// <param name="products">Ienumarable of products for ProductShop</param>
        /// <param name="context">ProductShop db context</param>
        /// <param name="rnd">instance of System.Random</param>
        public static void ImportProductsToDb(IEnumerable <Product> products, ProductsShopContext context, Random rnd)
        {
            HashSet <int> usersIDs = context.Users
                                     .Select(e => e.Id)
                                     .ToHashSet();

            HashSet <int> categoriesIDs = context.Categories
                                          .Select(e => e.Id)
                                          .ToHashSet();

            int minimalUserId     = usersIDs.Min();
            int maximalUserId     = usersIDs.Max();
            int minimalCategoryId = categoriesIDs.Min();
            int maximalCategoryId = categoriesIDs.Max();

            foreach (Product product in products)
            {
                while (true)
                {
                    int randomUserId = rnd.Next(minimalUserId, maximalUserId + 1);

                    if (usersIDs.Contains(randomUserId))
                    {
                        product.SellerId = randomUserId;
                        break;
                    }
                }

                // 10 percent chance for BuyerId to remain null
                if (rnd.Next(0, 10) != 0)
                {
                    while (true)
                    {
                        int randomUserId = rnd.Next(minimalUserId, maximalUserId + 1);

                        if (usersIDs.Contains(randomUserId) && product.SellerId != randomUserId)
                        {
                            product.BuyerId = randomUserId;
                            break;
                        }
                    }
                }

                // Generate 1 to 3 categories for the product
                for (int i = 0; i < rnd.Next(1, 4); i++)
                {
                    while (true)
                    {
                        int randomCategoryId = rnd.Next(minimalCategoryId, maximalCategoryId + 1);

                        if (categoriesIDs.Contains(randomCategoryId))
                        {
                            CategoryProducts newProductCategory = new CategoryProducts
                            {
                                ProductId  = product.Id,
                                CateogryId = randomCategoryId
                            };

                            if (!product.ThisProductsCategories.Contains(newProductCategory))
                            {
                                product.ThisProductsCategories.Add(newProductCategory);
                                break;
                            }
                        }
                    }
                }
            }

            context.Products.AddRange(products);
            context.SaveChanges();
        }
コード例 #23
0
 public async Task WhenICallTheProductCategoryAPIForCategoryId(string categoryId)
 {
     categoryProducts = await apiClient.ProductAPI.ListProductsAsync(categoryId).ConfigureAwait(false);
 }
コード例 #24
0
 public ActionResult Upsert(CategoryProducts categoryProducts)
 {
     categoryProducts.Upsert();
     return(new EmptyResult());
 }
コード例 #25
0
 public ActionResult Upsert(CategoryProducts categoryProducts)
 {
     categoryProducts.Upsert();
     return new EmptyResult();
 }