Exemplo n.º 1
0
        static string ImportUsersFromXml()
        {
            string xmlString = File.ReadAllText("users.xml");
            var    xmlDoc    = XDocument.Parse(xmlString); //Read xml from string
            var    elements  = xmlDoc.Root.Elements();

            var users = new List <User>();

            foreach (var e in elements)
            {
                var firstName = e.Attribute("FirstName")?.Value; //? operator if null dosnt take attribute.
                var lastName  = e.Attribute("lastName")?.Value;

                int?age = null;
                if (e.Attribute("age") != null)
                {
                    age = int.Parse(e.Attribute("age").Value);
                }

                var user = new User
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Age       = age,
                };

                users.Add(user);
            }

            var context = new ProductShopContext();

            context.Users.AddRange(users);
            context.SaveChanges();

            return($"{users.Count} users were sucessfully added from users.xml.");
        }
Exemplo n.º 2
0
        static string SetCategories()
        {
            var context = new ProductShopContext();

            var productsIds   = context.Products.Select(p => p.ProductId).ToArray();
            var categoriesIds = context.Categories.Select(c => c.CategoryId).ToArray();

            var rnd = new Random();
            var listCategoryProducts = new List <CategoryProduct>();

            foreach (var p in productsIds)
            {
                //Puts on each productId 3 categoryId
                for (int i = 0; i < 3; i++)
                {
                    var randomCategoryIdIndex = rnd.Next(0, categoriesIds.Length);
                    while (listCategoryProducts.Any(cp => cp.ProductId == p && cp.CategoryId == categoriesIds[randomCategoryIdIndex]))
                    {
                        randomCategoryIdIndex = rnd.Next(0, categoriesIds.Length);
                    }

                    var catProd = new CategoryProduct
                    {
                        ProductId  = p, //p is index from productsIds
                        CategoryId = categoriesIds[randomCategoryIdIndex],
                    };

                    listCategoryProducts.Add(catProd);
                }
            }

            context.CategoryProducts.AddRange(listCategoryProducts);
            context.SaveChanges();

            return($"{listCategoryProducts.Count} categoryProducts were added.");
        }
Exemplo n.º 3
0
        private static void ImportUsers(ProductShopContext context)
        {
            XDocument usersXml = XDocument.Load("../../../Xml-files/users.xml");
            XElement  userRoot = usersXml.Root;

            foreach (var userElementh in userRoot.Elements())
            {
                string firsName = userElementh.Attribute("first-name")?.Value;
                string lastName = userElementh.Attribute("last-name")?.Value;

                int age = Convert.ToInt32(userElementh.Attribute("age")?.Value);//Triabva da e ConvertToint32 a ne Parse inache ne minava
                if (lastName != null)
                {
                    User user = new User()
                    {
                        FirstName = firsName,
                        LastName  = lastName,
                        Age       = age
                    };
                    context.Users.Add(user);
                }
            }
            context.SaveChanges();
        }
        private static void GetUsersAndProducts(ProductShopContext dbContext)
        {
            var users = new UserRootDto()
            {
                Count = dbContext.Users.Count(),
                Users = dbContext
                        .Users
                        .Where(u => u.ProductSold.Count >= 1)
                        .OrderByDescending(u => u.ProductSold.Count)
                        .Select(u => new UserExportDto()
                {
                    FirstName = u.FirstName,
                    LastName  = u.LastName,
                    Age       = u.Age.ToString(),
                    Products  = new ProductSoldRootDto()
                    {
                        Count           = u.ProductSold.Count,
                        ProductSoldDtos = u.ProductSold.Select(s => new ProductSoldDto()
                        {
                            Name  = s.Name,
                            Price = s.Price
                        })
                                          .ToArray()
                    }
                })
                        .ToArray()
            };

            StringBuilder           sb            = new StringBuilder();
            XmlSerializer           serializer    = new XmlSerializer(typeof(UserRootDto), new XmlRootAttribute("users"));
            XmlSerializerNamespaces xmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

            serializer.Serialize(new StringWriter(sb), users, xmlNamespaces);

            File.WriteAllText("../../../Files/Export/users-and-products.xml", sb.ToString());
        }
Exemplo n.º 5
0
        private static void ImportCategories()
        {
            var context = new ProductShopContext();

            XDocument categoriesXml = XDocument.Load("../../xmls/categories.xml");

            var categories = categoriesXml.Root.Elements()
                             .Select(c => new Category()
            {
                Name = c.Element("name")?.Value
            })
                             .ToList();

            int num             = 17;
            int categoriesCount = context.Categories.Count();

            foreach (var p in context.Products)
            {
                categories[num++ % categories.Count].Products.Add(p);
            }

            context.Categories.AddRange(categories);
            context.SaveChanges();
        }
        private static string ImportXmlUsers()
        {
            var usersPath = "Resources\\users.xml";
            var xmlString = File.ReadAllText(usersPath);
            var xDocUsers = XDocument.Parse(xmlString);

            var users = new List <User>();

            var elements = xDocUsers.Root.Elements().ToArray();

            foreach (var e in elements)
            {
                string firstName = e.Attribute("firstName")?.Value;
                string lastName  = e.Attribute("lastName").Value;

                int?age = null;
                if (e.Attribute("age") != null)
                {
                    age = int.Parse(e.Attribute("age").Value);
                }

                var user = new User
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Age       = age
                };
                users.Add(user);
            }
            using (var db = new ProductShopContext())
            {
                db.Users.AddRange(users);
                db.SaveChanges();
            }
            return($"Successfully added {users.Count} users to the Database");
        }
Exemplo n.º 7
0
        private static void ImportCategories(ProductShopContext context)
        {
            XDocument categoriesDocs = XDocument.Load(@"c:\users\stoyadim\documents\visual studio 2015\Projects\XML_HW_ProductShop\XML_HW_ProductShop\Imports\products.xml");

            XElement        categoriesRoot  = categoriesDocs.Root;
            Random          rnd             = new Random();
            List <Category> categories      = new List <Category>();
            int             countOfProducts = context.Products.Count();

            foreach (XElement categoryElement in categoriesRoot.Elements())
            {
                Category category = new Category()
                {
                    Name = categoryElement.Element("name").Value,
                };
                for (int i = 0; i < countOfProducts; i++)
                {
                    Product product = context.Products.Find(rnd.Next(1, countOfProducts + 1));
                    category.Products.Add(product);
                }
                context.Categories.Add(category);
            }
            context.SaveChanges();
        }
Exemplo n.º 8
0
        private static void ImportCategoriesInDatabase(IMapper mapper, ProductShopContext context)
        {
            var xmlString = File.ReadAllText("../../../Xml/categories.xml");

            var serializer             = new XmlSerializer(typeof(CategoryImportDto[]), new XmlRootAttribute("categories"));
            var deserializedCategories = (CategoryImportDto[])serializer.Deserialize(new StringReader(xmlString));

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

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

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

                categories.Add(category);
            }

            context.Categories.AddRange(categories);
            context.SaveChanges();
        }
Exemplo n.º 9
0
        private static void ExportCategoriesByProductsCount(ProductShopContext ctx)
        {
            ICollection <XElement> elements = new List <XElement>();

            ctx.Categories.OrderBy(c => c.Products.Count())
            .Select(c => new
            {
                name          = c.Name,
                productsCount = c.Products.Count(),
                averagePrice  = c.Products.Average(p => p.Price),
                totalRevenue  = c.Products.Sum(p => p.Price)
            }).ToList().ForEach(c =>
            {
                elements.Add(new XElement("category",
                                          new XAttribute("name", c.name),
                                          new XElement("products-count", c.productsCount),
                                          new XElement("average-price", c.averagePrice),
                                          new XElement("total-revenue", c.totalRevenue)));
            });
            XDocument doc = new XDocument();

            doc.Add(new XElement("categories", elements));
            doc.Save("../../../Export-XML/categories-by-products.xml");
        }
Exemplo n.º 10
0
        private static void ExportUsersSoldProductToJSON(ProductShopContext context)
        {
            var usersSoldProduct = context.Users
                                   .Where(sp => sp.SoldProducts.Count > 0)
                                   .OrderBy(ln => ln.LastName)
                                   .ThenBy(fn => fn.FirstName)
                                   .Select(user => new
            {
                firstName    = user.FirstName,
                lastName     = user.LastName,
                soldProducts = user.SoldProducts.Select(product => new
                {
                    name           = product.Name,
                    price          = product.Price,
                    buyerFirstName = product.Buyer.FirstName,
                    buyerLastName  = product.Buyer.LastName
                })
            });

            var outputAsJson = JsonConvert.SerializeObject(usersSoldProduct, Formatting.Indented);

            File.WriteAllText("../../users-sold-products.json", outputAsJson);
            Console.WriteLine(outputAsJson);
        }
Exemplo n.º 11
0
        public static string ImportUsersFromXml()
        {
            string    xmlString = File.ReadAllText(xmlUsers);
            XDocument xml       = XDocument.Parse(xmlString);

            XElement[]  elements = xml.Root.Elements().ToArray();
            List <User> users    = new List <User>();

            foreach (var e in elements)
            {
                string firstName = e.Attribute("firstName")?.Value;
                string lastName  = e.Attribute("lastName").Value;

                int?age = null;
                if (e.Attribute("age")?.Value != null)
                {
                    age = int.Parse(e.Attribute("age").Value);
                }

                User user = new User()
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Age       = age,
                };

                users.Add(user);
            }
            using (var db = new ProductShopContext())
            {
                db.AddRange(users);
                db.SaveChanges();
            }

            return($"{users.Count} users import successfuly from file: {xmlUsers}");
        }
Exemplo n.º 12
0
        public static void Main(string[] args)
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <ProductShopProfile>();
            });
            var mapper = config.CreateMapper();

            var context = new ProductShopContext();

            context.Database.EnsureCreated();

            using (context)
            {
                //ImportUsers(context, mapper);
                //ImportProducts(context, mapper);
                // ImportCategories(context,mapper);
                //ImportCategoriesProducts(context, mapper);
                // GetProductInRange(context, mapper);
                //GetSuccessfullySoldProdutcs(context, mapper);
                //GetCategoriesByProductCount(context, mapper);
                GetUsersAndProducts(context, mapper);
            }
        }
Exemplo n.º 13
0
        private static void GetSuccessfullySoldProdutcs(ProductShopContext context, IMapper mapper)
        {
            var users = context.Users
                        .Where(u => u.ProductsSold.Count() >= 1)
                        .Select(p => new UserExportDto()
            {
                FirstName    = p.FirstName,
                LastName     = p.LastName,
                SoldProducts = p.ProductsSold.Select(sp => new SoldProductsDto()
                {
                    Name           = sp.Name,
                    Price          = sp.Price,
                    BuyerFirstName = sp.Buyer.FirstName,
                    BuyerLastName  = sp.Buyer.LastName
                }).ToArray()
            })
                        .OrderBy(u => u.LastName)
                        .ThenBy(u => u.FirstName)
                        .ToArray();

            string jsonString = JsonConvert.SerializeObject(users, Formatting.Indented);

            File.WriteAllText("../../../Dto/Export/sold-products.json", jsonString);
        }
Exemplo n.º 14
0
        private static void GetUserAndProducts(ProductShopContext db)
        {
            var users = new UserRootDto
            {
                Count = db.Users.Count(),
                Users = db.Users
                        .Where(x => x.ProductsSold.Count >= 1)
                        .Select(x => new UserPdto
                {
                    FirstName    = x.FirstName,
                    LastName     = x.LastName,
                    Age          = x.Age.ToString(),
                    SoldProducts = new SoldProductDto
                    {
                        Count        = x.ProductsSold.Count(),
                        ProductUdtos = x.ProductsSold
                                       .Select(k => new ProductUdto
                        {
                            Name  = k.Name,
                            Price = k.Price
                        })
                                       .ToList()
                    }
                })
                        .ToList()
            };

            var sb            = new StringBuilder();
            var xmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

            var serializer = new XmlSerializer(typeof(UserRootDto), new XmlRootAttribute("users"));

            serializer.Serialize(new StringWriter(sb), users, xmlNamespaces);

            File.WriteAllText("../../../Xml/users-and-products.xml", sb.ToString());
        }
        private void ImportCategories(IMapper mapper, ProductShopContext context)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(CategoryDto[]), new XmlRootAttribute("categories"));

            var deserializedCategories = (CategoryDto[])serializer.Deserialize(new StreamReader("../../../../XmlImport/categories.xml"));

            var categories = new List <Category>();

            foreach (var categoryDto in deserializedCategories)
            {
                if (!IsValid(categoryDto))
                {
                    Console.WriteLine("Category not valid!!");
                    continue;
                }
                var category = mapper.Map <Category>(categoryDto);

                categories.Add(category);
            }

            context.Categories.AddRange(categories);

            context.SaveChanges();
        }
Exemplo n.º 16
0
        private static void CategoryByProductsCount(ProductShopContext context)
        {
            var categories = context.Categories.OrderBy(p => p.Products.Count)
                             .Select(category => new
            {
                Name = category.Name,
                CategoryByProductsCount = category.Products.Count,
                AveragePrice            = category.Products.Average(p => p.Price),
                TotalRevenu             = category.Products.Sum(p => p.Price)
            }
                                     );
            var xmlDocument = new XElement("categories");

            foreach (var cat in categories)
            {
                var categoryNode = new XElement("category");
                categoryNode.Add(new XAttribute("products-count", cat.CategoryByProductsCount));
                categoryNode.Add(new XAttribute("average-price", cat.AveragePrice));
                categoryNode.Add(new XAttribute("total-revenue", cat.TotalRevenu));

                xmlDocument.Add(categoryNode);
            }
            xmlDocument.Save("../../../categoryProductsCount.xml");
        }
Exemplo n.º 17
0
        public static void GenerateCategoryProducts(ProductShopContext context)
        {
            int categoriesCount = context.Categories.Count();

            int productsCounts = context.Products.Count();

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

            for (int productId = 1; productId <= productsCounts; productId++)
            {
                int categoryid = new Random().Next(1, categoriesCount + 1);

                var categoryProduct = new CategoryProduct
                {
                    CategoryId = categoryid,
                    ProductId  = productId
                };
                categoryProducts.Add(categoryProduct);
            }

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();
            Console.WriteLine("Category-Products generated succesfully");
        }
Exemplo n.º 18
0
        private static void ImportUsersInDatabase(IMapper mapper, ProductShopContext context)
        {
            var xmlString = File.ReadAllText("../../../Xml/users.xml");

            var serializer        = new XmlSerializer(typeof(UserImportDto[]), new XmlRootAttribute("users"));
            var deserializedUsers = (UserImportDto[])serializer.Deserialize(new StringReader(xmlString));

            List <User> users = new List <User>();

            foreach (var userDto in deserializedUsers)
            {
                if (!IsValid(userDto))
                {
                    continue;
                }

                var user = mapper.Map <User>(userDto);

                users.Add(user);
            }

            context.Users.AddRange(users);
            context.SaveChanges();
        }
Exemplo n.º 19
0
        public static void ImportProducts(ProductShopContext context)
        {
            var jsonString   = File.ReadAllText("../../../Json/products.json");
            var deserializer = JsonConvert.DeserializeObject <Product[]>(jsonString);

            List <Product> products = new List <Product>();

            foreach (Product product in deserializer)
            {
                if (IsValid(product) == false)
                {
                    Console.WriteLine("Invalid product data");
                    continue;
                }

                int usersCount = context.Users.Count();
                int sellerId   = new Random().Next(1, usersCount / 2);
                int buyerId    = new Random().Next(usersCount / 2, usersCount + 1);
                int randomNum  = new Random().Next(1, 5);

                product.SellerId = sellerId;
                product.BuyerId  = buyerId;


                if (randomNum == 2)
                {
                    product.BuyerId = null;
                }

                products.Add(product);
            }

            context.Products.AddRange(products);
            context.SaveChanges();
            Console.WriteLine("Products added succesfully");
        }
Exemplo n.º 20
0
        public static void ImportProducts()
        {
            var context = new ProductShopContext();

            var jsonString = File.ReadAllText("../../../Json/products.json");

            var deserializedProducts = JsonConvert.DeserializeObject <Product[]>(jsonString);

            List <Product> products = new List <Product>();

            foreach (var product in deserializedProducts)
            {
                if (!IsValid(product))
                {
                    continue;
                }

                var sellerId = new Random().Next(1, 35);
                var bayerId  = new Random().Next(35, 57);

                var random = new Random().Next(1, 4);

                product.SellerId = sellerId;
                product.BuyerId  = bayerId;

                if (random == 3)
                {
                    product.BuyerId = null;
                }

                products.Add(product);
            }

            context.Products.AddRange(products);
            context.SaveChanges();
        }
Exemplo n.º 21
0
        private static void ImportXmlUsers(ProductShopContext context)
        {
            var users = context.Users.Where(x => x.SoldProducts.Count > 1)
                        .OrderBy(x => x.LastName)
                        .ThenBy(x => x.FirstName)
                        .Select(x => new UserDtoExp
            {
                FirstName    = x.FirstName,
                LastName     = x.LastName,
                SoldProducts = x.SoldProducts.Select(s => new SoldProduct
                {
                    Name  = s.Name,
                    Price = s.Price
                }).ToArray()
            }).ToArray();

            var sb            = new StringBuilder();
            var xmlNameSpaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var serializer    = new XmlSerializer(typeof(UserDtoExp[]), new XmlRootAttribute("users"));

            serializer.Serialize(new StringWriter(sb), users, xmlNameSpaces);

            File.WriteAllText("../../../XmlFiles/users-sold-products.xml", sb.ToString());
        }
        private static string ImportProductsInDB()
        {
            string productsPath = "Resources\\products.json";

            Product[] products             = ImportJson <Product>(productsPath);
            int       currentProductNumber = 0;

            using (var db = new ProductShopContext())
            {
                int[] userIds = db.Users.Select(u => u.UserId).ToArray();

                Random random = new Random();

                foreach (var product in products)
                {
                    var sellerIdIndex = random.Next(0, userIds.Length);
                    product.SellerId = userIds[sellerIdIndex];

                    if (currentProductNumber % 7 != 0)
                    {
                        var buyerIdIndex = random.Next(0, userIds.Length);
                        while (sellerIdIndex == buyerIdIndex)
                        {
                            buyerIdIndex = random.Next(0, userIds.Length);
                        }
                        product.BuyerId = userIds[buyerIdIndex];
                    }

                    currentProductNumber++;
                }

                db.Products.AddRange(products);
                db.SaveChanges();
                return($"Successfully added {products.Length} products into the Database");
            }
        }
Exemplo n.º 23
0
        public static void Q4UsersAndProducts()
        {
            var context = new ProductShopContext();

            var users = new
            {
                userCount = context.Users.Count(),
                users     = context.Users
                            .OrderByDescending(x => x.ProductsSold.Count)
                            .ThenBy(l => l.LastName)
                            .Where(x => x.ProductsSold.Count >= 1 && x.ProductsSold.Any(s => s.Buyer != null))
                            .Select(u => new
                {
                    firstName    = u.FirstName,
                    lastName     = u.LastName,
                    age          = u.Age,
                    soldProducts = new
                    {
                        count    = u.ProductsSold.Count,
                        products = u.ProductsSold.Select(s => new
                        {
                            name  = s.Name,
                            price = s.Price
                        }).ToArray()
                    }
                }).ToArray()
            };

            var jsonProducts = JsonConvert.SerializeObject(users, new JsonSerializerSettings
            {
                Formatting        = Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore
            });

            File.WriteAllText("../../../Json/users-and-products.json", jsonProducts);
        }
Exemplo n.º 24
0
        public static void ExportCategoriesByProductCount()
        {
            var context    = new ProductShopContext();
            var categories = context.Categories
                             .OrderByDescending(c => c.CategoryProducts.Count)
                             .Select(x => new CategoryExportDto()
            {
                Name         = x.Name,
                ProductCount = x.CategoryProducts.Count,
                TotalRevenue = x.CategoryProducts.Sum(p => p.Product.Price),
                AveragePrice = x.CategoryProducts.Select(p => p.Product.Price)
                               .DefaultIfEmpty(0)
                               .Average()
            })
                             .ToArray();

            var serializer    = new XmlSerializer(typeof(CategoryExportDto[]), new XmlRootAttribute("categories"));
            var xmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var sb            = new StringBuilder();

            serializer.Serialize(new StringWriter(sb), categories, xmlNamespaces);

            File.WriteAllText(@"XmlOutput/categories-by-products-count.xml", sb.ToString());
        }
        private static List <Product> ImportProducts(IMapper mapper, string xmlName, List <User> users)
        {
            var xmlString = File.ReadAllText("../../../Xml/" + xmlName);

            var serializer  = new XmlSerializer(typeof(ProductDto[]), new XmlRootAttribute("products"));
            var productDtos = (ProductDto[])serializer.Deserialize(new StringReader(xmlString));

            var products = new List <Product>();

            foreach (var productDto in productDtos)
            {
                if (IsValid(productDto))
                {
                    var product  = mapper.Map <Product>(productDto);
                    var sellerId = new Random().Next(0, users.Count / 2);
                    var buyerId  = new Random().Next(users.Count / 2 + 1, users.Count);
                    var addBuyer = Convert.ToBoolean(new Random().Next(0, 2));

                    product.SellerId = users[sellerId].Id;
                    if (addBuyer)
                    {
                        product.BuyerId = users[buyerId].Id;
                    }

                    products.Add(product);
                }
            }

            using (var db = new ProductShopContext())
            {
                db.Products.AddRange(products);
                db.SaveChanges();
            }

            return(products);
        }
Exemplo n.º 26
0
        public static void GenerateCategories()
        {
            var config = new MapperConfiguration(cfg => { cfg.AddProfile <ProductShopProfile>(); });
            var mapper = config.CreateMapper();

            var categoryProducts = new List <CategoryProduct>();

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

                var categoryProduct = new CategoryProduct()
                {
                    CategoryId = categotyId,
                    ProductId  = productId
                };

                categoryProducts.Add(categoryProduct);
            }
            var context = new ProductShopContext();

            context.CategoryProducts.AddRange(categoryProducts);
            context.SaveChanges();
        }
Exemplo n.º 27
0
 public JsonProcessor(ProductShopContext context)
 {
     this.context = context;
 }
 public XmlProcessor()
 {
     this.context = new ProductShopContext();
 }
Exemplo n.º 29
0
        public static void GetUsersAndProductsXml()
        {
            using (var db = new ProductShopContext())
            {
                var users = db.Users
                            .Where(u => u.SoldProducts.Count > 0)
                            .Include(u => u.SoldProducts)
                            .OrderByDescending(u => u.SoldProducts.Count)
                            .ThenBy(u => u.LastName)
                            .Select(u => new
                {
                    firstName    = u.FirstName,
                    lastName     = u.LastName,
                    age          = u.Age,
                    soldProducts = new
                    {
                        count    = u.SoldProducts.Count,
                        products = u.SoldProducts.Select(p => new
                        {
                            name  = p.Name,
                            price = p.Price
                        })
                    }
                });

                var usersToSerialize = new
                {
                    usersCount = users.Count(),
                    users
                };

                var xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", null), new XElement("users", new XAttribute("count", usersToSerialize.usersCount)));

                foreach (var u in usersToSerialize.users)
                {
                    var user = new XElement("user");
                    if (u.firstName != null)
                    {
                        user.Add(new XAttribute("first-name", u.firstName));
                    }
                    user.Add(new XAttribute("last-name", u.lastName));
                    if (u.age != null)
                    {
                        user.Add(new XAttribute("age", u.age));
                    }

                    var soldProducts = new XElement("sold-products", new XAttribute("count", u.soldProducts.count));

                    foreach (var p in u.soldProducts.products)
                    {
                        var product = new XElement("product",
                                                   new XAttribute("name", p.name),
                                                   new XAttribute("price", p.price));
                        soldProducts.Add(product);
                    }

                    user.Add(soldProducts);
                    xmlDoc.Root.Add(user);
                }
                File.WriteAllText("UsersAndProducts.xml", xmlDoc.ToString());
            }
        }
 public GenericUnitOfWork()
 {
     this.dbContext = new ProductShopContext();
 }
        static void Main()
        {
            var context = new ProductShopContext();
            var count = context.Categories.Count();
            //Console.WriteLine(count);

            // Query 1 - Products In Range.Get all products in a specified price range (e.g. 500 to 1000) which have no buyer. Order them by price (from lowest to highest).
            //Select only the product name, price and the full name of the seller. Export the result to JSON.

            var productsInRange = context.Products
                .Where(p => p.Buyer == null && p.Price >= 500 && p.Price <= 1000)
                .OrderBy(p => p.Price)
                .Select(p => new
                {
                    p.Name,
                    p.Price,
                    SellerFullName = p.Seller.FirstName + " " + p.Seller.LastName
                });

            var serializedProducts = JsonConvert.SerializeObject(productsInRange, Formatting.Indented);
            //File.WriteAllText("../../01-products-in-range.json", serializedProducts);

            //Query 2 - Successfully Sold Products. Get all users who have at least 1 sold item with a buyer. Order them by last name, then by first name.
            //Select the person's first and last name. For each of the sold products (products with buyers), select the product's name,
            //price and the buyer's first and last name

            var usersSoldProducts = context.Users
                .Where(u => u.ProductsSold.Any() && u.ProductsSold.Where(p => p.Buyer.Id != null).Count() > 0)
                .OrderBy(u => u.LastName)
                .ThenBy(u => u.FirstName)
                .Select(u => new
                {
                    firstName = u.FirstName,
                    lastName = u.LastName,
                    soldProducts = u.ProductsSold.Select(p => new
                     {
                         name = p.Name,
                         price = p.Price,
                         buyerFirstName = p.Buyer.FirstName,
                         buyerLastName = p.Buyer.LastName
                     })
                }).ToList();

            var serializedusersSoldProducts = JsonConvert.SerializeObject(usersSoldProducts, Formatting.Indented);
            //File.WriteAllText("../../02-users-sold-products.json", serializedusersSoldProducts);

            //Query 3 - Categories By Products Count. Get all categories. Order them by the number of products in that
            //category (a product can be in many categories). For each category select its name, the number of products,
            //the average price of those products and the total revenue (total price sum) of those products
            //(regardless if they have a buyer or not).

            var categoriesByProducts = context.Categories
                .OrderByDescending(c => c.Products.Count())
                .Select(c => new
                {
                    category = c.Name,
                    productsCount = c.Products.Count(),
                    averagePrice = c.Products.Average(p => p.Price),
                    totalRevenue = c.Products.Sum(p => p.Price)
                }).ToList();

            var serializedCategories = JsonConvert.SerializeObject(categoriesByProducts, Formatting.Indented);
            //File.WriteAllText("../../03-categories-by-products.json", serializedCategories);

            //Query 4 - Users and Products. Get all users who have at least 1 sold product. Order them by the number of sold products (from highest to lowest),
            //then by last name (ascending). Select only their first and last name, age and for each product - name and price. Export the results to XML.
            //Follow the format below to better understand how to structure your data. Note: If a user has no first name or age, do not add attributes.

            var usersTraders = context.Users
                .Where(u => u.ProductsSold.Any() && u.ProductsSold.Where(p => p.Buyer.Id != null).Count() > 0)
                .OrderByDescending(u => u.ProductsSold.Count)
                .ThenBy(u => u.LastName)
                .Select(u => new
                {
                    u.FirstName,
                    u.LastName,
                    u.Age,
                    Products = u.ProductsSold.Select(p => new
                     {
                         p.Name,
                         p.Price,
                     })
                }).ToList();

            var xmlDoc = new XDocument();
            var roorElement = new XElement("users");
            roorElement.SetAttributeValue("count", usersTraders.Count);
            xmlDoc.Add(roorElement);

            foreach (var u in usersTraders)
            {
                var userTag = new XElement("user");

                if (u.FirstName != null)
                {
                    userTag.SetAttributeValue("first-name", u.FirstName);
                }
                if (u.LastName != null)
                {
                    userTag.SetAttributeValue("last-name", u.LastName);
                }
                if (u.Age != null)
                {
                    userTag.SetAttributeValue("age", u.Age);
                }

                var productsTag = new XElement("sold-products");
                productsTag.SetAttributeValue("count", u.Products.Count());

                foreach (var p in u.Products)
                {
                    var pTag = new XElement("product");
                    pTag.SetAttributeValue("name", p.Name);
                    pTag.SetAttributeValue("price", p.Price);

                    productsTag.Add(pTag);
                }

                userTag.Add(productsTag);
                roorElement.Add(userTag);
            }

            xmlDoc.Save("../../04-users-and-products.xml", SaveOptions.None);
        }