public static int? GetVendorIdByName(string vendorName)
        {
            var context = new SupermarketContext();
            var vendorId = context.Vendors.FirstOrDefault(v => v.VendorName == vendorName).Id;

            return vendorId;
        }
        public static int? GetMeasureIdByName(string measureName)
        {
            var context = new SupermarketContext();
            var measureId = context.Measures.FirstOrDefault(m => m.MeasureName == measureName).Id;

            return measureId;
        }
        public static int? GetSupermarketIdByName(string supermarketName)
        {
            var context = new SupermarketContext();
            var supermarketId = context.Supermarkets.FirstOrDefault(s => s.Name == supermarketName).SupermarketId;

            return supermarketId;
        }
        public static int?GetTypeIdByName(string typeName)
        {
            var context = new SupermarketContext();
            var typeId  = context.ProductTypes.FirstOrDefault(pt => pt.TypeName == typeName).Id;

            return(typeId);
        }
        public static int? GetTypeIdByName(string typeName)
        {
            var context = new SupermarketContext();
            var typeId = context.ProductTypes.FirstOrDefault(pt => pt.TypeName == typeName).Id;

            return typeId;
        }
        public static int?GetMeasureIdByName(string measureName)
        {
            var context   = new SupermarketContext();
            var measureId = context.Measures.FirstOrDefault(m => m.MeasureName == measureName).Id;

            return(measureId);
        }
        public static int?GetVendorIdByName(string vendorName)
        {
            var context  = new SupermarketContext();
            var vendorId = context.Vendors.FirstOrDefault(v => v.VendorName == vendorName).Id;

            return(vendorId);
        }
        public static int?GetProductIdByName(string productName)
        {
            var context   = new SupermarketContext();
            var productId = context.Products.FirstOrDefault(p => p.ProductName == productName).Id;

            return(productId);
        }
Exemplo n.º 9
0
 public static List<VendorExpense> ReadFileXML(string path)
 {
     List<VendorExpense> readedVendorsExpense = new List<VendorExpense>();
     using (XmlReader reader = XmlReader.Create(path))
     {
         while (reader.Read())
         {
             if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "sale"))
             {
                 var newVendor = new VendorExpense();
                 var name = reader.GetAttribute("vendor");
                 var dbCobntext = new SupermarketContext();
                 var vendor = dbCobntext.Vendors.FirstOrDefault(x => x.Name == name);
                 newVendor.Vendor = vendor;
                 reader.Read();
                 reader.Read();
                 while ((reader.NodeType == XmlNodeType.Element) &&
                 (reader.Name == "expenses"))
                 {
                     var month = reader.GetAttribute("month");
                     DateTime vendorMonth = DateTime.ParseExact(month, "MMM-yyyy", CultureInfo.InvariantCulture);
                     var sum = reader.ReadElementString();
                     newVendor.Date = vendorMonth;
                     newVendor.MonthExpense = decimal.Parse(sum, CultureInfo.InvariantCulture);
                     reader.Read();
                     readedVendorsExpense.Add(newVendor);
                     newVendor = new VendorExpense();
                     newVendor.Vendor = vendor;
                 }
             }
         }
         return readedVendorsExpense;
     }
 }
        public static int? GetProductIdByName(string productName)
        {
            var context = new SupermarketContext();
            var productId = context.Products.FirstOrDefault(p => p.ProductName == productName).Id;

            return productId;
        }
        public static void GenerateJSONReports()
        {
            Console.WriteLine("Enter start date in format \'YYYY-MM-DD\': ");
            string startDateInput = Console.ReadLine();
            Console.WriteLine("Enter end date in format \'YYYY-MM-DD\': ");
            string endDateInput = Console.ReadLine();
            Console.WriteLine("Processing data.......");

            try
            {
                DateTime startDate = DateTime.Parse(startDateInput);
                DateTime endDate = DateTime.Parse(endDateInput);
                if (startDate > endDate)
                {
                    throw new ArgumentException("End date must be after start date!");
                }

                var mssqlData = new SupermarketContext();
                var jsSerializaer = new JavaScriptSerializer();
                var sales =
                    mssqlData.SupermarketSalesProducts.Where(s => s.SalesDate >= startDate && s.SalesDate <= endDate)
                        .Select(
                            s =>
                            new
                                {
                                    productId = s.ProductId,
                                    productName = s.Product.ProductName,
                                    vendorName = s.Product.Vendor.VendorName,
                                    totalQuantitySold = s.Quantity,
                                    totalIncomes = s.Quantity * s.Product.Price
                                })
                        .ToList();
                Console.WriteLine("Sending data to MongoDB.....");
                foreach (var sale in sales)
                {
                    var jsonReport = jsSerializaer.Serialize(sale);

                    SaveDataInMongoDb(jsonReport);

                    if (!File.Exists(JsonReportPath + sale.productId + ".json"))
                    {
                        File.WriteAllText(JsonReportPath + sale.productId + ".json", jsonReport);
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid input");
            }

            Console.WriteLine("JSON reports generated.");
            DirectoryInfo directoryInfo = new DirectoryInfo(JsonReportPath);
            Console.WriteLine("Directory:  {0}", directoryInfo.FullName);
            foreach (var file in directoryInfo.GetFiles())
            {
                Console.WriteLine("File:  {0}", file.Name);
            }
            Console.WriteLine("JSON reports were imported successfully.");
        }
        public static int?GetSupermarketIdByName(string supermarketName)

        {
            var context       = new SupermarketContext();
            var supermarketId = context.Supermarkets.FirstOrDefault(s => s.Name == supermarketName).SupermarketId;

            return(supermarketId);
        }
Exemplo n.º 13
0
        static void Main()
        {
            using (var context = new SupermarketContext())
            {
                var customers = context.Customers.Count();

                Console.WriteLine(customers);
            }
        }
 private List<ProductReport> GetProductReports()
 {
     using (SupermarketContext context = new SupermarketContext())
     {
         List<ProductReport> productReports = new List<ProductReport>();
         productReports = context.Database.SqlQuery<ProductReport>(ProductReportQuery).ToList();
         return productReports;
     }
 }
        public void MigrateDataFromMySqlToSqlServer()
        {
            using (var supermarketContextSqlServer = new SupermarketContext())
            {
                using (var supermarketContextMySql = new SupermarketModel())
                {
                    foreach (var measureMySql in supermarketContextMySql.Measures)
                    {
                        if (!supermarketContextSqlServer.Measures
                            .Any(m => m.MeasureName == measureMySql.MeasureName))
                        {
                            supermarketContextSqlServer.Measures.Add(new Models.Measure()
                            {
                                MeasureName = measureMySql.MeasureName
                            });
                        }
                    }

                    foreach (var vendorMySql in supermarketContextMySql.Vendors)
                    {
                        if (!supermarketContextSqlServer.Vendors
                            .Any(v => v.VendorName == vendorMySql.VendorName))
                        {
                            supermarketContextSqlServer.Vendors.Add(new Models.Vendor()
                            {
                                VendorName = vendorMySql.VendorName
                            });
                        }
                    }

                    supermarketContextSqlServer.SaveChanges();

                    foreach (var productMySql in supermarketContextMySql.Products)
                    {
                        if (!supermarketContextSqlServer.Products
                            .Any(p => p.Name == productMySql.ProductName))
                        {
                            var vendorSqlServer = supermarketContextSqlServer.Vendors
                                .First(v => v.VendorName == productMySql.Vendor.VendorName);
                            var measureSqlServer = supermarketContextSqlServer.Measures
                                .First(m => m.MeasureName == productMySql.Measure.MeasureName);

                            supermarketContextSqlServer.Products.Add(new Models.Product()
                            {
                                BasePrice = productMySql.BasePrice,
                                Name = productMySql.ProductName,
                                Measure = measureSqlServer,
                                Vendor = vendorSqlServer,
                            });
                        }
                    }
                }

                supermarketContextSqlServer.SaveChanges();
            }
        }
Exemplo n.º 16
0
        private static void FromMySqlNeverAgain()
        {
            var dbcontext = new SupermarketContext();

            var mySqlContx = new SupermarketModel();
            using (mySqlContx)
            {
                var products = mySqlContx.Products.OrderBy(e => e.ID).ToList();
                var vendors = mySqlContx.Vendors.ToList();
                var mesuares = mySqlContx.Measures.ToList();
                using (dbcontext)
                {

                    foreach (var mesuare in mesuares)
                    {
                        var newMeasure = new Measure()
                        {
                            ID = mesuare.ID,
                            Name = mesuare.Name
                        };
                        dbcontext.Measures.Add(newMeasure);

                    }

                    foreach (var vendor in vendors)
                    {
                        var newVendor = new Vendor()
                        {
                            ID = vendor.ID,
                            Name = vendor.Name
                        };
                        dbcontext.Vendors.Add(newVendor);
                    }


                    foreach (var product in products)
                    {
                        var some = new Product
                        {
                            BasePrice = product.BasePrice,
                            Measure_ID = product.Measure_ID,
                            Name = product.Name,
                            Vendor_ID = product.Vendor_ID,
                        };
                        dbcontext.Products.Add(some);
                    }

                    dbcontext.SaveChanges();
                }


            }
        }
        ///<summary>
        ///This is summary for method that transfer records from Oracle model into MQ SQL Server model.
        ///The method first select records from Oracle model which have not yet been copied or deleted.
        ///Second it inserts record into MS SQL Method and mark them as copied into Oracle model
        ///</summary>
        public static void UpdateMeasuresFromOracle()
        {
            var oracleContext = new OracleEntities();
            var msSqLcontext = new SupermarketContext();
            var measures = oracleContext.MEASURES
                    .Where(m => m.ISCOPIED == false && m.ISDELETED == false)
                    .Select(m => new
                    {
                        m.MEASURENAME
                    }).ToList();

            if (measures.Count > 0)
            {
                var addedMeasuresList = new List<string>();

                foreach (var measure in measures)
                {
                    var measureName = measure.MEASURENAME;

                    try
                    {
                        msSqLcontext.Measures.AddOrUpdate(
                            m => m.MeasureName,
                            new Measure()
                            {
                                MeasureName = measureName
                            });

                        msSqLcontext.SaveChanges();
                        addedMeasuresList.Add(measureName);
                    }
                    catch (Exception ex)
                    {
                        throw new ArgumentException();
                    }

                }

                var measuresToChange = oracleContext.MEASURES.Where(m => addedMeasuresList.Contains(m.MEASURENAME)).ToList();
                measuresToChange.ForEach(m => m.ISCOPIED = true);
                oracleContext.SaveChanges();

                Console.WriteLine("\nAdded new Measures from OracleBD into MS SQL Server:");
                measuresToChange.ForEach(m => Console.WriteLine("Added measure name: {0}", m.MEASURENAME));
            }
            else
            {
                Console.WriteLine("\nThere is no new records to import into MEASURES table!");
            }
        }
        private static void GenerateJSONReports()
        {
            Console.WriteLine("Enter start date in format \'YYYY-MM-DD\': ");
            string startDateInput = Console.ReadLine();
            Console.WriteLine("Enter end date in format \'YYYY-MM-DD\': ");
            string endDateInput = Console.ReadLine();

            try
            {
                DateTime startDate = DateTime.Parse(startDateInput);
                DateTime endDate = DateTime.Parse(endDateInput);
                if (startDate > endDate)
                {
                    throw new ArgumentException("End date must be after start date!");
                }

                var mssqlData = new SupermarketContext();
                var jsSerializaer = new JavaScriptSerializer();
                var sales =
                    mssqlData.Sales.Where(s => s.SoldDate >= startDate && s.SoldDate <= endDate)
                        .Select(
                            s =>
                            new
                                {
                                    productId = s.ProductId,
                                    productName = s.Product.ProductName,
                                    vendorName = s.Product.Vendor.VendorName,
                                    totalQuantitySold = s.Quantity,
                                    totalIncomes = s.Quantity * s.Product.Price
                                })
                        .ToList();

                foreach (var sale in sales)
                {
                    var jsonReport = jsSerializaer.Serialize(sale);

                    SaveDataInMongoDb(jsonReport);

                    if (!File.Exists(JsonReportPath + sale.productId + ".json"))
                    {
                        File.WriteAllText(JsonReportPath + sale.productId + ".json", jsonReport);
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid input");
            }
        }
Exemplo n.º 19
0
        private static void FillExpensesInSql(ICollection<Expense> expenses)
        {
            SupermarketContext context = new SupermarketContext();
            using (context)
            {
                foreach (var expense in expenses)
	            {
                    context.Expenses.Add(expense);
	            }

                context.SaveChanges();
            }

            Console.WriteLine("5. Expenses saved in SQL Server!");
        }
        /// <summary>
        /// Load the zipped files with the excel reports.
        /// </summary>
        /// <param name="context">The context relationship with the Entity framework and the database</param>
        public void LoadExelReports(SupermarketContext context)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(this.FilePath);
            Console.WriteLine(@"        Loading Exel Reports To MsSqlDB
            ------------------------------------------------");
            Console.WriteLine("Extracting data from file  {0}", directoryInfo.FullName);

            string tempFolder = string.Format("{0}{1}", Directory.GetCurrentDirectory(), TempFolderName);
            string currentReportDate = string.Empty;

            using (ZipArchive archive = ZipFile.OpenRead(this.FilePath))
            {
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    if (entry.FullName.EndsWith("/", StringComparison.OrdinalIgnoreCase))
                    {
                        //Gets from the folders the date in which the reports are made
                        currentReportDate = entry.FullName.TrimEnd('/');
                    }
                    else
                    {
                        if (!Directory.Exists(tempFolder))
                        {
                            Directory.CreateDirectory(tempFolder);
                        }
                        //extract the readed file always into this "temporary" file
                        entry.ExtractToFile(Path.Combine(tempFolder, TempFileName), true);
                        DataTable excelData = this.ReadExcelData(string.Format("{0}{1}", tempFolder, TempFileName));
                        DataRowCollection arrExelData = excelData.Rows;
                        string marketName = this.SupermarketName(arrExelData[0].ItemArray);

                        this.CheckForExistingSupermarket(arrExelData[0].ItemArray, context);

                        //The loop starts from 2, because of the cell formatting in the excel file, if the loop starts form 0 it will iterate trough array full of empty strings
                        for (int i = 2; i < arrExelData.Count-1; i++)
                        {
                            InsertIntoDataBase(arrExelData[i].ItemArray,context,currentReportDate,marketName);
                        }
                    }
                }
            }

            Console.WriteLine("Zip excel reports imported.");
        }
        public void MigrateDataFromExcelFiles(string zipFilePath)
        {
            ExtractZipFile(zipFilePath);

            using (var supermarketContext = new SupermarketContext())
            {
                IList<Models.Sale> allSales = new List<Models.Sale>();
                GetSales(TempFolderForExtract, supermarketContext, allSales);

                foreach (var sale in allSales)
                {
                    supermarketContext.Sales.Add(sale);
                }

                supermarketContext.SaveChanges();
            }

            Directory.Delete(TempFolderForExtract, true);
        }
        public static List<JSonReport> GetJsonReports()
        {
            var dbContex = new SupermarketContext();
            using (dbContex)
            {
                var jsonReports =
               from p in dbContex.Products
               join dr in dbContex.DailyReports on p.Id equals dr.ProductId
               join v in dbContex.Vendors on p.VendorId equals v.Id
               select new JSonReport
               {
                   ProductId = p.Id,
                   ProductName = p.ProductName,
                   VendorName = v.VendorName,
                   TotalQuntitySold = dr.Quantity,
                   TotalIncome = dr.Quantity * dr.Price
               };

                return jsonReports.ToList() ;
            }
        }
        public void CreateXmlSalesByVendorsReport(string destinationFilePath)
        {
            Encoding encoding = Encoding.GetEncoding("utf-8");
            using (var supermarketContext = new SupermarketContext())
            {
                using (var writer = new XmlTextWriter(destinationFilePath, encoding))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.IndentChar = '\t';
                    writer.Indentation = 1;

                    writer.WriteStartDocument();
                    writer.WriteStartElement("sales");
                    foreach (var vendor in supermarketContext.Vendors.ToList())
                    {
                        WriteSalesByVendor(writer, supermarketContext.Sales, vendor);
                    }

                    writer.WriteEndDocument();
                }
            }
        }
        public static void UpdateProductsFromMssql()
        {
            var msSqLcontext = new SupermarketContext();
            var mySqlContext = new marketsystemEntities();
            var products = msSqLcontext.Products
                .ToList();

            foreach (var product in products)
            {
                var productId = product.Id;
                var productName = product.ProductName;
                var vendorId = product.VendorId;
                var measureId = product.MeasureId;
                var typeId = product.ProductTypeId;
                var price = product.Price;

                try
                {
                    mySqlContext.products.AddOrUpdate(
                        p => p.productId,
                        new product()
                        {
                            productId = productId,
                            productName = productName,
                            vendorId = (int) vendorId,
                            measureId = (int)measureId,
                            productTypeId = (int)typeId,
                            productPrice = (decimal) price
                        });

                    mySqlContext.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new ArgumentException();
                }
            }
        }
        private void LoadVendorExpensesToSqlServer(IList<string[]> expenses)
        {
            using (var supermarketContext = new SupermarketContext())
            {
                foreach (var expense in expenses)
                {
                    string vendorName = expense[0];
                    int vendorID = supermarketContext.Vendors.First(v => v.VendorName == vendorName).ID;
                    decimal value = decimal.Parse(expense[2]);

                    Models.Expense newExpense = new Models.Expense()
                    {
                        VendorID = vendorID,
                        Month = DateTime.Parse(expense[1]),
                        Value = value
                    };

                    supermarketContext.Expenses.Add(newExpense);
                }

                supermarketContext.SaveChanges();
            }
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            //// only the first time

           // FromMySqlNeverAgain();
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<SupermarketContext, Configuration>());

            /// run separately or it will be slow :)

            //Zipper.UnzipFiles();
            //ExcelReader.ReadExcelData();
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());


            var dbCobntext = new SupermarketContext();


            XmlReport.GenerateXml("../../../../GeneratedReports/xmlSales.xml");

            JsonReport jsonReport = new JsonReport(dbCobntext);
            jsonReport.GetProductsReport(@"../../../../GeneratedReports/productsReport.json");
            jsonReport.GenerateJsonFilesForEachProduct(@"../../../../GeneratedReports/ProductReportsForMongo/");
            MongoDbProvider.AddProducts(jsonReport);
            var ProductsFRomMongo = MongoDbProvider.MongoDBCollectionToList();

            ExcelReport excelReport = new ExcelReport(dbCobntext);
            excelReport.GenerateVendorTotalReport("n", ProductsFRomMongo);

            var vendorExpenses = ReadXML.ReadFileXML("../../../../Reports/Vendors-Expenses.xml");
            MongoDbProvider.AddVendorExpenses(vendorExpenses);


            Console.WriteLine();
        }
        ///<summary>
        ///This is summary for methods that transfer records from MQ SQL Server model into MySQL DB.
        ///The method first select all records from MQ SQL Server model model.
        ///Second it inserts record into MySQL DB.
        ///</summary>
        public static void UpdateMeasuresFromMssql()
        {
            var msSqLcontext = new SupermarketContext();
            var mySqlContext = new marketsystemEntities();
            var measures = msSqLcontext.Measures
                 .ToList();

            foreach (var measure in measures)
            {
                var id = measure.Id;
                var name = measure.MeasureName;

                mySqlContext.measures.AddOrUpdate(
                    m => m.measureId,
                    new MySqlModel.measure()
                    {
                       measureId = id,
                       measureName = name
                    });

                mySqlContext.SaveChanges();

            }
        }
        /// <summary>
        /// Insert the content of the excel files into the database.
        /// </summary>
        /// <param name="rowData">array of data containing name, type, price and quantity of the product</param>
        /// <param name="context">the Entity Framework connection to the database</param>
        /// <param name="reportDate">the date taken from the folder with the reports</param>
        /// <param name="supmarketName">the name of the supermarket</param>
        private void InsertIntoDataBase(object[] rowData, SupermarketContext context,string reportDate, string supmarketName)
        {
            //    string[] inputNameType = rowData[0].ToString().Split();
            //    string prodType = inputNameType[0];
            //    string prodName = inputNameType[1];
            string prodName = rowData[0].ToString();
            int quantity = int.Parse(rowData[1].ToString());
            float price = float.Parse(rowData[2].ToString());
            DateTime dateReport = DateTime.ParseExact(reportDate, "dd-MMM-yyyy", CultureInfo.InvariantCulture);

            //this.CheckProductType(prodType, context);
            this.CheckProduct(prodName,price,context);

            var productId = context.Products.Where(p => p.ProductName == prodName).Select(p => p.Id).FirstOrDefault();
            var marketId = context.Supermarkets.Where(s => s.Name == supmarketName).Select(s => s.SupermarketId).FirstOrDefault();
            var existMarketSalesProduct = context.SupermarketSalesProducts
                .Where(s => s.SupermarketId == marketId &&
                            s.ProductId == productId &&
                            s.SalesDate == dateReport)
                .Select(s => new
                {
                    s.ProductId,
                    s.SupermarketId,
                    s.SalesDate
                }).FirstOrDefault();

            if (existMarketSalesProduct == null)
            {
                context.SupermarketSalesProducts.Add(new SupermarketSalesProduct
                {
                    SupermarketId = marketId,
                    ProductId = productId,
                    Quantity = quantity,
                    Price = (decimal) price,
                    SalesDate = dateReport
                });
                context.SaveChanges();
            }
        }
        /// <summary>
        /// Check for existing product type, because we want to have distinct data in the database and if the product type do not exists the method add it to the database. 
        /// </summary>
        /// <param name="prodTypeName">the type to be checked</param>
        /// <param name="context">the Entity Framework connection to the database</param>
        private void CheckProductType(string prodTypeName, SupermarketContext context)
        {
            var existPodType = context.ProductTypes
                .Where(t => t.TypeName == prodTypeName)
                .Select(t => t.TypeName)
                .FirstOrDefault();

            if (existPodType == null)
            {
                context.ProductTypes.Add(new ProductType
                {
                    TypeName = prodTypeName
                });
                context.SaveChanges();
            }
        }
        /// <summary>
        /// Check for existing product type, because we want to have distinct data in the database and if the product do not exists the method add it to the database. 
        /// </summary>
        /// <param name="productName">the name to be checked</param>
        /// <param name="price">the price needed to be eventually created new product</param>
        /// <param name="context">the Entity Framework connection to the database</param>
        private void CheckProduct(string productName,float price, SupermarketContext context)
        {
            var existProd = context.Products
             .Where(p => p.ProductName == productName)
             .Select(p => p.ProductName)
             .FirstOrDefault();

            if (existProd == null)
            {
                context.Products.Add(new Product
                {
                    ProductName = productName,
                    Price = price
                });
                context.SaveChanges();
                Console.WriteLine("Product: {0} added!", productName);
            }
            else
            {
                Console.WriteLine("Product: {0} existed!", productName);
            }
        }
        /// <summary>
        ///Check for existing supermarket, because we want to have distinct data in the database and if the supermarket do not exists the method add it to the database. 
        /// </summary>
        /// <param name="supName">the array containig the supermarket name</param>
        /// <param name="context">the Entity Framework connection to the database</param>
        private void CheckForExistingSupermarket(object[] supName, SupermarketContext context)
        {
            string marketName = this.SupermarketName(supName);
            var existSupName = context.Supermarkets.Where(s => s.Name == marketName).Select(s => s.Name).FirstOrDefault();

            if (existSupName == null)
            {
                context.Supermarkets.Add(new MS_SQL_Server.Supermarket
                {
                    Name = marketName,
                    IsDeleted = false
                });
                context.SaveChanges();
                Console.WriteLine("Supermarket: {0} added!", marketName);
            }
            else
            {
                Console.WriteLine("Supermarket: {0} existed!",marketName);
            }
        }
        private static double PourReportData(PdfPTable table)
        {
            double totalSum = 0;
            double grandTotal = 0;

            var msSQLcontext = new SupermarketContext();
            msSQLcontext.Vendors.FirstOrDefault();

            var salesReport = msSQLcontext.SupermarketSalesProducts
                .Select(p => new
                {
                    date = p.SalesDate,
                    location = p.Supermarket.Name,
                    product = p.Product.ProductName,
                    quantity = p.Quantity,
                    price = p.Price,
                    measure = p.Product.Measure.MeasureName
                })
                .GroupBy(d => d.date);

            foreach (var item in salesReport)
            {
                HeaderGeneration(table, item.Key);

                double sum = 0;

                foreach (var item2 in item)
                {
                    sum = (double) (item2.quantity * item2.price);

                    table.AddCell(item2.product);
                    table.AddCell(item2.quantity.ToString() + " " + item2.measure);
                    table.AddCell(String.Format("{0:0.00}", item2.price));
                    table.AddCell(item2.location);
                    table.AddCell(String.Format("{0:0.00}", sum));

                    totalSum += sum;
                }

                FooterGeneration(table, totalSum, item.Key);

                grandTotal += totalSum;
                totalSum = 0;
            }

            return grandTotal;
        }
        public static void GenerateXMLReport()
        {
            var msSQLcontext = new SupermarketContext();
            string filePath = @"..\..\..\..\Reports\Sales-by-Vendors-Report.xml";
            msSQLcontext.Vendors.FirstOrDefault();

            var data = msSQLcontext.SupermarketSalesProducts
                .Select(s => new
                {
                    vendor = s.Product.Vendor.VendorName,
                    date = s.SalesDate,
                    quontity = s.Quantity,
                    price = s.Price
                })
                .GroupBy(v => new
                {
                    v.vendor,
                }).ToList();

            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);
            XmlElement sales = doc.CreateElement("sales");
            doc.AppendChild(sales);

            foreach (var vendorData in data)
            {
                XmlNode vendorTag = doc.LastChild;
                XmlElement sale = doc.CreateElement("sale");

                sale.SetAttribute("vendor", vendorData.Key.vendor);

                double totalSum = 0;

                var vendorByDate = vendorData
                        .GroupBy(g => g.date)
                        .Select(s => new
                        {
                            date = s.Key,
                            quantity = s.Select(q => q.quontity),
                            price = s.Select(p => p.price)
                        })
                        .ToList();

                foreach (var d in vendorByDate)
                {
                    XmlElement summary = doc.CreateElement("summary");
                    summary.SetAttribute("date", d.date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture));

                    var q = d.quantity.ToList();
                    var p = d.price.ToList();
                    for (int i = 0; i < q.Count; i++)
                    {
                        totalSum += (double) (q[i] * p[i]);
                    }

                    summary.SetAttribute("total-sum", String.Format("{0:0.00}", totalSum));
                    sale.AppendChild(summary);
                    totalSum = 0;
                }

                vendorTag.AppendChild(sale);
            }

            doc.Save(filePath);
            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            Console.WriteLine("XML report generated.");
            Console.WriteLine("File:  {0}", directoryInfo.FullName);
        }
Exemplo n.º 34
0
 public JsonReport(SupermarketContext dbContext)
 {
     this.DbContext = dbContext;
 }
Exemplo n.º 35
0
        public static void GenerateXml(string fileName)
        {
            
            Encoding encoding = Encoding.GetEncoding("utf-8");
            using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding))
            {
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;

                writer.WriteStartDocument();
                writer.WriteStartElement("sales");

                var dbContext = new SupermarketContext();
                using (dbContext)
                {
                    foreach (var vendorData in dbContext.Vendors)
                    {
                        writer.WriteStartElement("sale");
                        writer.WriteAttributeString("vendor", vendorData.Name);

                        var data =
                            from vendor in dbContext.Vendors
                            join product in dbContext.Products
                            on vendor.ID equals product.Vendor_ID
                            join sale in dbContext.Sales
                            on product.ID equals sale.Product.ID
                            where vendor.ID == vendorData.ID
                            select new
                            {
                                SaleDate = sale.Date,
                                TotalSales = sale.Sum
                            };

                        var result =
                            from item in data
                            group item by new { item.SaleDate } into r

                            select new
                            {
                                SaleDate = r.FirstOrDefault().SaleDate,
                                TotalSum = r.Sum(v => v.TotalSales)
                            };

                        foreach (var resultItem in result)
                        {
                            WriteSummary(writer, resultItem.SaleDate.ToString(), resultItem.TotalSum.ToString());
                        }

                        writer.WriteEndElement();

                    }

                    //for (int i = 0; i < length; i++)
                    //{
                    //    writer.WriteStartElement("sale");
                    //    writer.WriteAttributeString("vendor", date);
                    //    for (int i = 0; i < length; i++)
                    //    {

                    //    }
                    //    writer.WriteEndElement();
                    //}
                }

                writer.WriteEndDocument();
            }
            //Console.WriteLine("Document {0} created.", fileName);
        }