public async Task <ActionResult> CheckEmailExternalLogin(string userId, string code, string returnUrl, string info1)
        {
            var info = await AuthenticationManager.GetExternalLoginInfoAsync();

            var result = await UserManager.AddLoginAsync(userId, info.Login);

            ApplicationUser user = await UserManager.FindByIdAsync(userId);

            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                user.EmailConfirmed = true;
                await UserManager.UpdateAsync(user);

                SupermarketEntities entities = new SupermarketEntities();
                var    k    = entities.AspNetUsers.SingleOrDefault(m => m.Email == user.Email);
                string role = k.AspNetRoles.FirstOrDefault().Name;
                if (role.Equals("Admin"))
                {
                    return(RedirectToAction("AdminHome", "Home"));
                }
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                return(RedirectToAction("Login"));
            }
        }
 // POST: api/Category
 public void Post(Category category)
 {
     using (SupermarketEntities entities = new SupermarketEntities())
     {
         entities.Categories.Add(category);
         entities.SaveChanges();
     }
 }
Beispiel #3
0
 public static void PopulateProducts()
 {
     productsModel = new ProductsModel();
     market        = new SupermarketEntities();
     AddMeasurements();
     AddVendors();
     AddProducts();
 }
        public static void CreateReport()
        {
            string directoryCreating = "..\\..\\..\\SalesReports.pdf";
            if (File.Exists(directoryCreating))
            {
                File.Delete(directoryCreating);
            }
            Document pdfReport = new Document();
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfReport,
                new System.IO.FileStream(directoryCreating, System.IO.FileMode.Create));

            pdfReport.Open();
            using (pdfReport)
            {
                PdfPTable reportTable = new PdfPTable(5);

                AddCellToTable(reportTable, "Aggregated Sales Report", TextAlign.Center, 5);

                using (var supermarketEntities = new SupermarketEntities())
                {
                    var reportsOrderedByDate = supermarketEntities.Reports.OrderBy(x => x.ReportDate);
                    var currentDate = reportsOrderedByDate.First().ReportDate;
                    decimal currentSum = 0;
                    decimal totalSum = 0;
                    var headerColor = new BaseColor(217, 217, 217);
                    AddHeader(reportTable, currentDate, headerColor);
                    // aligment  0 = left, 1 = center, 2 = right

                    foreach (var report in reportsOrderedByDate)
                    {
                        if (currentDate != report.ReportDate)
                        {
                            AddFooter(reportTable, "Total sum for " + currentDate.ToString(), currentSum);
                            currentSum = 0;
                            currentDate = report.ReportDate;
                            AddHeader(reportTable, currentDate, headerColor);
                        }
                        else
                        {
                            AddCellToTable(reportTable, report.Product.ProductName.ToString(), 0);
                            AddCellToTable(reportTable, report.Quantity.ToString(), 0);
                            AddCellToTable(reportTable, report.UnitPrice.ToString(), 0);
                            AddCellToTable(reportTable, report.Supermarket.ToString(), 0);
                            AddCellToTable(reportTable, report.Sum.ToString(), 0);
                            totalSum += (decimal)report.Sum;
                            currentSum += (decimal)report.Sum;
                        }
                    }

                    AddFooter(reportTable, "Total sum for " + currentDate.ToString(), currentSum);
                    AddFooter(reportTable, "Grand total:", totalSum);
                }

                pdfReport.Add(reportTable);
            }
        }
Beispiel #5
0
        static void Main()
        {
            using (var db = new EntitiesModel())
            {
                var vendors  = db.Vendors;
                var products = db.Products;
                var measures = db.Measures;

                using (var dbSql = new SupermarketEntities())
                {
                    foreach (var vendor in vendors)
                    {
                        Supermarket_EF.Data.Vendor vendorObj = new Supermarket_EF.Data.Vendor();
                        vendorObj.ID         = vendor.IdvendorsID;
                        vendorObj.VendorName = vendor.VendorName;
                        dbSql.Vendors.Add(vendorObj);
                    }
                    foreach (var measure in measures)
                    {
                        Supermarket_EF.Data.Measure measureObj = new Supermarket_EF.Data.Measure()
                        {
                            ID          = measure.ID,
                            MeasureName = measure.MeasureName
                        };
                        dbSql.Measures.Add(measureObj);
                    }
                    foreach (var product in products)
                    {
                        Supermarket_EF.Data.Product productObj = new Supermarket_EF.Data.Product()
                        {
                            ID          = product.ID,
                            VendorID    = product.VendorID,
                            ProductName = product.ProductName,
                            MeasureID   = product.MeasureID,
                            BasePrice   = (decimal)product.BasePrice
                        };
                        dbSql.Products.Add(productObj);
                    }
                    dbSql.SaveChanges();
                    MyExtract();

                    string dirPath = "../../../Extracted Files";
                    var    dir     = Directory.GetDirectories(dirPath);

                    Traverse(dir);

                    PdfReportCreator.CreatePDFs();
                    XmlReportCreator.CreateReport();
                    ExportReportInMongoDB.CreateReport();
                    VendorExpenses.LoadVendorExpenses();

                    VendorsReports.CreateExcel();
                }
            }
        }
        public static void GenerateXMLSalesReportByVendors(string filename = "Sales-by-Vendors-report.xml")
        {
            using (var sqlContext = new SupermarketEntities())
            {
                //var firstQuery = from sales in sqlContext.Sales
                //                 join products in sqlContext.Products
                //                 on sales.ProductId equals products.Id
                //                 join vendors in sqlContext.Vendors
                //                 on products.VendorId equals vendors.Id
                //                 group new
                //                 {
                //                     SaleDate = sales.Date,
                //                     Sum = sales.Sum
                //                 } by vendors.Name;

                //var secondQuery= from inner in firstQuery
                //                 group inner by inner.SaleDate

                var vendorGroupedReport = from sales in sqlContext.Sales
                                          join products in sqlContext.Products on sales.ProductId equals products.Id
                                          join vendors in sqlContext.Vendors on products.VendorId equals vendors.Id
                                          group new
                                          {
                                              SaleDate = sales.Date,
                                              Sum = sales.Sum
                                          } by vendors.Name;

                var xmlTree = new XElement("sales");
                foreach (var item in vendorGroupedReport)
                {
                    var sale = new XElement("sale", new XAttribute("vendor", item.Key));
                    var aggregatedReport = from aggregated in item
                                           group aggregated by aggregated.SaleDate into p
                                           select new
                                           {
                                               Date = p.Distinct().Select(d => d.SaleDate).FirstOrDefault(),
                                               Total = p.Sum(s => s.Sum)
                                           };

                    foreach (var inner in aggregatedReport)
                    {
                        var summary = new XElement("summary", new XAttribute("date",
                            string.Format("{0:dd-MMM-yyyy}", inner.Date)),
                            new XAttribute("total-sum", inner.Total));
                        sale.Add(summary);
                    }
                    xmlTree.Add(sale);
                }

                var output = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xmlTree);
                //Console.WriteLine(output);
                output.Save(filename);
             }
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            // nếu nhập ok phần client và k bị ràng buộc lỗi gì cả
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            // neu chua xac thuc Email, k dc login
            SupermarketEntities entities = new SupermarketEntities();
            var k = entities.AspNetUsers.SingleOrDefault(m => m.Email == model.Email);

            if (k != null)
            {
                if (k.EmailConfirmed == false)
                {
                    ModelState.AddModelError("", "Please confirm your email first");
                    return(View(model));
                }
                else
                {
                    // This doesn't count login failures towards account lockout
                    // To enable password failures to trigger account lockout, change to shouldLockout: true
                    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

                    switch (result)
                    {
                    case SignInStatus.Success:
                    {
                        string role = k.AspNetRoles.FirstOrDefault().Name;
                        if (role.Equals("Admin"))
                        {
                            return(RedirectToAction("AdminHome", "Home"));
                        }
                        return(RedirectToLocal(returnUrl));
                    }

                    case SignInStatus.LockedOut:
                        return(View("Lockout"));

                    case SignInStatus.RequiresVerification:
                        return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        return(View(model));
                    }
                }
            }
            ModelState.AddModelError("", "Invalid login attempt.");
            return(View(model));
        }
        public static void SaveToMSSqlServer(string xmlLocation)
        {
            using (var supermarketEntities = new SupermarketEntities())
            {
                using (XmlReader reader = XmlReader.Create(xmlLocation))
                {
                    int vendorId = 0;
                    while (reader.Read())
                    {
                        if (reader.IsStartElement())
                        {
                            if (reader.Name == "sale")
                            {
                                string vendorName = reader["vendor"];

                                var vendorQuery = from v in supermarketEntities.Vendors
                                                  where v.VendorName == vendorName
                                                  select v.VendorId;

                                foreach (var v in vendorQuery)
                                {
                                    vendorId = v;
                                }
                            }

                            if (reader.Name == "expenses")
                            {
                                DateTime expenseDate = DateTime.Parse(reader["month"]);
                                reader.Read();
                                decimal money = decimal.Parse(reader.Value);
                                Vendor vendor = supermarketEntities.Vendors.Find(vendorId);
                                var expense = new Expens()
                                {
                                    Vendor = vendor,
                                    Month = expenseDate,
                                    Sum = money
                                };

                                supermarketEntities.Expenses.Add(expense);
                            }
                        }
                    }
                    supermarketEntities.SaveChanges();
                }
            }
        }
        private void AddRecordToDatabase(int productId, int quantity, decimal unitPrice, decimal sum, DateTime reportDate, string supermarketName)
        {
            using (var supermarketEntities = new SupermarketEntities())
            {
                var report = new Report()
                {
                    ProductId = productId,
                    Quantity = quantity,
                    UnitPrice = unitPrice,
                    Sum = sum,
                    ReportDate = reportDate,
                    Supermarket = supermarketName
                };

                supermarketEntities.Reports.Add(report);
                supermarketEntities.SaveChanges();
            }
        }
Beispiel #10
0
        public static void CreateReport()
        {
            using (var dbSql = new SupermarketEntities())
            {
                var reportsQuery = from sale in dbSql.Sales.Include("Products").Include("Vendors")
                                   orderby sale.ProductID
                                   group sale by new { sale.ProductID, sale.Product.ProductName, sale.Product.Vendor.VendorName }
                into g
                let totalSold = g.Sum(x => x.Quanity)
                                let totalIncome = g.Sum(y => y.Sum)
                                                  select new TotalReport
                {
                    product_id          = g.Key.ProductID,
                    product_name        = g.Key.ProductName,
                    vendor_name         = g.Key.VendorName,
                    total_quantity_sold = totalSold,
                    total_incomes       = totalIncome
                };

                string pathString = "../../../Product-Reports";

                System.IO.Directory.CreateDirectory(pathString);

                var mongoClient    = new MongoClient("mongodb://localhost/");
                var mongoServer    = mongoClient.GetServer();
                var productReports = mongoServer.GetDatabase("Product-Reports");
                var reports        = productReports.GetCollection("reports");

                foreach (var report in reportsQuery)
                {
                    reports.Insert <TotalReport>(report);

                    string jsonReports = report.ToJson();
                    jsonReports = jsonReports.Replace('_', '-');
                    jsonReports = jsonReports.Replace(",", ",\n");
                    File.WriteAllText(pathString + "/" + report.product_id + ".json",
                                      jsonReports);
                }

                WriteToSqlLite(reports);
            }
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
            {
                SupermarketEntities entities = new SupermarketEntities();
                var k    = entities.AspNetUsers.SingleOrDefault(m => m.Email == loginInfo.Email.ToLower());
                var role = k.AspNetRoles.FirstOrDefault().Name;
                if (role.Equals("Admin"))
                {
                    return(RedirectToAction("AdminHome", "Home"));
                }
                return(RedirectToLocal(returnUrl));
            }

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email.ToLower()
                }));
            }
        }
        private static void GenerateMongoReportsFromMSSql(MongoCollection<BsonDocument> productReports)
        {
            using (var supermarketEntities = new SupermarketEntities())
            {
                var reportsOrederedByProductId = supermarketEntities.Reports
                                                                    .Include("Product.Vendor")
                                                                    .OrderBy(p => p.ProductId);
                var firstProduct = reportsOrederedByProductId.First();
                int currentProductId = firstProduct.ProductId;
                int totalQuantitySold = 0;
                decimal totalIncome = 0;
                ProductReport productReport;
                Report lastReport = new Report();

                foreach (var report in reportsOrederedByProductId)
                {
                    if (currentProductId != report.ProductId)
                    {
                        productReport = new ProductReport(currentProductId,
                            report.Product.ProductName.ToString(),
                            report.Product.Vendor.VendorName.ToString().Trim(),
                            totalQuantitySold, totalIncome);
                        totalIncome = 0;
                        totalQuantitySold = 0;
                        currentProductId = report.ProductId;
                        productReports.Insert(productReport);
                    }

                    totalIncome += report.Sum;
                    totalQuantitySold += report.Quantity;
                    lastReport = report;
                }

                productReport = new ProductReport(currentProductId,
                            lastReport.Product.ProductName.ToString(),
                            lastReport.Product.Vendor.VendorName.ToString().Trim(),
                            totalQuantitySold, totalIncome);
                productReports.Insert(productReport);
            }
        }
        public static void MigrateDataFromMySqlToMSSqlServer()
        {
            using (var mySqlSuperMarketEntities = new OpenAccessMySqlSupermarketEntityModel())
            {
                using (var msSqlSeverSupermarketEntities = new SupermarketEntities())
                {
                    foreach (var mySqlMeasure in mySqlSuperMarketEntities.Measures)
                    {
                        msSqlSeverSupermarketEntities.Measures.Add(new MSSQLSupermarketEntityFramework.Measure()
                        {
                            MeasureId = mySqlMeasure.MeasureId,
                            MeasureName = mySqlMeasure.MeasureName,
                        });
                    }

                    foreach (var mySqlMeasure in mySqlSuperMarketEntities.Vendors)
                    {
                        msSqlSeverSupermarketEntities.Vendors.Add(new MSSQLSupermarketEntityFramework.Vendor()
                        {
                            VendorId = mySqlMeasure.VendorId,
                            VendorName = mySqlMeasure.VendorName,
                        });
                    }

                    foreach (var mySqlMeasure in mySqlSuperMarketEntities.Products)
                    {
                        msSqlSeverSupermarketEntities.Products.Add(new MSSQLSupermarketEntityFramework.Product()
                        {
                            BasePrice = mySqlMeasure.BasePrice,
                            MeasureId = mySqlMeasure.MeasureId,
                            ProductId = mySqlMeasure.ProductId,
                            ProductName = mySqlMeasure.ProductName,
                            VendorId = mySqlMeasure.VendorId
                        });
                    }

                    msSqlSeverSupermarketEntities.SaveChanges();
                }
            }
        }
Beispiel #14
0
        public static void CreateReport()
        {
            string      path                = "../../../Report.xml";
            Encoding    encoding            = Encoding.GetEncoding("windows-1251");
            CultureInfo nonInvariantCulture = new CultureInfo("en-US");

            Thread.CurrentThread.CurrentCulture = nonInvariantCulture;

            using (var data = new SupermarketEntities())
            {
                using (XmlTextWriter writer = new XmlTextWriter(path, encoding))
                {
                    writer.Formatting  = Formatting.Indented;
                    writer.IndentChar  = '\t';
                    writer.Indentation = 2;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("sales");

                    var salesByVendor = data.Sales.GroupBy(y => y.Location).ToList();
                    foreach (var sales in salesByVendor)
                    {
                        writer.WriteStartElement("sale");
                        writer.WriteAttributeString("vendor", sales.First().Location.LocationName);
                        foreach (var sale in sales)
                        {
                            writer.WriteStartElement("summary");

                            writer.WriteAttributeString("date", sale.Date.Value.ToString("dd-MMM-yyyy"));
                            writer.WriteAttributeString("total-sum", sale.Sum.ToString("{0:0.00}"));
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }
            }
        }
        internal static void GenerateXmlByVendors()
        {
            using (var entity = new SupermarketEntities())
            {
                string xmlReportDirectory = "..\\..\\..\\sales-xml.xml";
                if (File.Exists(xmlReportDirectory))
                {
                    File.Delete(xmlReportDirectory);
                }
                XElement rootElement = new XElement("sales");

                var orderedByVendors = entity.Reports
                                             .Include("Product.Vendor")
                                             .OrderBy(v => v.Product.Vendor.VendorName);
                var firstReport = orderedByVendors.First();
                string currentVendorName = firstReport.Product.Vendor.VendorName.ToString().Trim();
                XElement currentVendor = new XElement("sale", new XAttribute("vendor",
                    firstReport.Product.Vendor.VendorName.Trim()));

                foreach (var currentSaleReport in orderedByVendors)
                {
                    if (currentVendorName != currentSaleReport.Product.Vendor.VendorName.Trim())
                    {
                        rootElement.Add(currentVendor);
                        currentVendor = new XElement("sale", new XAttribute("vendor",
                            currentSaleReport.Product.Vendor.VendorName.Trim()));
                       currentVendorName = currentSaleReport.Product.Vendor.VendorName.Trim();
                    }

                    XElement currentVendorSummary = new XElement("summary",
                        new XAttribute("date", string.Format("{0}", currentSaleReport.ReportDate.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture))),
                        new XAttribute("total-sum", string.Format("{0:f2}", currentSaleReport.Sum)));
                    currentVendor.Add(currentVendorSummary);

                }
                rootElement.Add(currentVendor);
                rootElement.Save(xmlReportDirectory);
            }
        }
Beispiel #16
0
        public static void CreatePDFs()
        {
            Console.WriteLine("PDF Report creation started...");
            StringBuilder sb = new StringBuilder();

            using (var dbEF = new SupermarketEntities())
            {
                sb.Append("<table cellpadding='5' border='1'>");
                sb.Append("<tr><th align='center'><b>Aggregated Sales Report</b></th></tr>");
                sb.Append("</table>");
                sb.Append("<table cellpadding='5' border='1'>");

                decimal grandTotal = 0M;

                var db = dbEF.Sales.Select(x => x.Date).OrderBy(d => d.Value).Distinct();
                foreach (var dateTime in db)
                {
                    var date = DateTime.Parse(dateTime.ToString()).ToShortDateString();
                    //Console.WriteLine(dateTime);
                    sb.AppendFormat("<tr bgcolor='silver'><td colspan='5'>Date: {0}</td></tr>", date);
                    sb.Append("<tr bgcolor='silver'>");
                    sb.Append("<td><b>Product</b></td>");
                    sb.Append("<td><b>Quantity</b></td>");
                    sb.Append("<td><b>Unit Price</b></td>");
                    sb.Append("<td><b>Location</b></td>");
                    sb.Append("<td><b>Sum</b></td>");
                    sb.Append("</tr>");

                    var     d   = dbEF.Sales.Where(x => x.Date == dateTime);
                    decimal sum = 0M;
                    foreach (var item in d)
                    {
                        sb.Append("<tr>");
                        sb.AppendFormat("<td>{0}</td>", item.Product.ProductName);
                        sb.AppendFormat("<td>{0}</td>", item.Quanity);
                        sb.AppendFormat("<td>{0:F2}</td>", item.UnitPrice);
                        sb.AppendFormat("<td>{0}</td>", item.Location.LocationName);
                        sb.AppendFormat("<td>{0:F2}</td>", item.Sum);
                        sb.Append("</tr>");
                        sum += item.Sum;
                    }
                    grandTotal += sum;
                    sb.Append("<tr><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr>");
                    sb.AppendFormat("<tr><td colspan='4' align='right'>Total sum for {0}:</td><td><b>{1:F2}</b></td></tr>", date, sum);
                }
                sb.AppendFormat("<tr><td colspan='4' align='right'>Grand Total:</td><td><b>{0:F2}</b></td></tr>", grandTotal);

                sb.Append("</table>");
                Console.WriteLine("PDF Report generated.");
            }

            PDFBuilder.HtmlToPdfBuilder builder = new PDFBuilder.HtmlToPdfBuilder(PageSize.LETTER);
            PDFBuilder.HtmlPdfPage      page    = builder.AddPage();
            page.AppendHtml(sb.ToString());
            byte[] file         = builder.RenderPdf();
            string tempFolder   = "../../../PdfResult\\";
            string tempFileName = DateTime.Now.ToString("yyyy-MM-dd") + "-" + Guid.NewGuid() + ".pdf";

            if (Helpers.Helper.DirectoryExist(tempFolder))
            {
                if (!File.Exists(tempFolder + tempFileName))
                {
                    File.WriteAllBytes(tempFolder + tempFileName, file);
                }
            }
        }
        public static void ReadExpensesFile(string filename = "Vendors-Expenses.xml")
        {
            XDocument xmlDoc = XDocument.Load(filename);
            var salesData =
                from sales in xmlDoc.Descendants("sale")
                select new
                {
                    Vendor = sales.Attribute("vendor").Value,
                    Expenses = from expenses in sales.Elements("expenses")
                               select new
                               {
                                   Date = expenses.Attribute("month").Value,
                                   Sum = expenses.Value
                               }
                };

            //Console.WriteLine("Found {0} sales:", salesData.Count());
            //foreach (var item in salesData)
            //{
            //    Console.WriteLine("Vendor: " + item.Vendor);
            //    foreach (var exp in item.Expenses)
            //    {
            //        Console.WriteLine("Date: {0}, Sum: {1}", exp.Date, exp.Sum);
            //    }
            //}

            if (salesData != null && salesData.Count() > 0)
            {
                using (var sqlContext = new SupermarketEntities())
                {
                    foreach (var sale in salesData)
                    {
                        using (var scope = new System.Transactions.TransactionScope())
                        {
                            var vendor = sqlContext.Vendors.Where(v => v.Name == sale.Vendor).ToList();
                            if (vendor.Count == 0)
                            {
                                var newVendor = new Vendor();
                                newVendor.Name = sale.Vendor;

                                sqlContext.Vendors.Add(newVendor);
                                // sqlContext.SaveChanges();
                                vendor.Add(newVendor);
                            }

                            foreach (var exp in sale.Expenses)
                            {
                                var expense = new Expense();
                                expense.VendorId = vendor[0].Id;
                                expense.Value = decimal.Parse(exp.Sum);
                                expense.Month = DateTime.Parse("1-" + exp.Date);
                                if (sqlContext.Expenses.Where(
                                    e => e.Month == expense.Month && e.VendorId==expense.VendorId).Count() == 0)
                                {
                                    sqlContext.Expenses.Add(expense);
                                }
                            }

                            sqlContext.SaveChanges();
                            scope.Complete();
                        }
                    }
                }
            }
        }
Beispiel #18
0
        public static void LoadVendorExpenses()
        {
            XmlDocument doc = new XmlDocument();

            doc.Load("../../../Vendors-Expenses.xml");

            XmlNode rootNode = doc.DocumentElement;

            List <Expens> expenses = new List <Expens>();

            using (var db = new SupermarketEntities())
            {
                string vendorName;
                var    mongoClient    = new MongoClient("mongodb://localhost/");
                var    mongoServer    = mongoClient.GetServer();
                var    productReports = mongoServer.GetDatabase("Product-Reports");
                var    reports        = productReports.GetCollection("expenses");

                foreach (XmlNode item in rootNode.ChildNodes)
                {
                    XmlAttribute atr = item.Attributes[0];
                    vendorName = atr.Value;

                    int id = db.Vendors.Where(x => x.VendorName == vendorName).Select(x => x.ID).FirstOrDefault();

                    foreach (XmlNode node in item.ChildNodes)
                    {
                        Expens   expense    = new Expens();
                        string   atrDate    = node.Attributes[0].Value.ToString();
                        string   dateFormat = "MMM-yyyy";
                        DateTime date       = DateTime.ParseExact(atrDate, dateFormat, CultureInfo.InvariantCulture);

                        decimal expenseValue = decimal.Parse(node.InnerText);

                        expense.Date     = date;
                        expense.Expenses = expenseValue;
                        expense.VendorId = id;



                        expenses.Add(expense);

                        ExpenseByName expenseByName = new ExpenseByName();
                        expenseByName.VendorName = vendorName;
                        expenseByName.Date       = expense.Date;
                        expenseByName.Expenses   = expense.Expenses;

                        reports.Insert(expenseByName);
                    }
                }



                foreach (Expens item in expenses)
                {
                    db.Expenses.Add(item);
                }

                db.SaveChanges();

                WriteToSqlLite(reports);
            }
        }
Beispiel #19
0
        public void GenerateVendorTotalReport(string filePath, List <ProductReportJson> listOfProduct)
        {
            SupermarketEntities sqliteCotext = new SupermarketEntities();

            var hashWithProducts   = new Dictionary <string, Supermarket.Sqlite.Product>();
            var productsFromSqlite = sqliteCotext.Products.ToList();

            foreach (var item in productsFromSqlite)
            {
                string itemName = item.ProductName;
                if (!hashWithProducts.ContainsKey(itemName))
                {
                    hashWithProducts.Add(itemName, item);
                }
            }



            var matching = (from prod in listOfProduct where hashWithProducts.ContainsKey(prod.Name)

                            select
                            new ProductForVendorsReport
            {
                Id = prod.ProductId,
                Incomes = prod.Incomes,
                TaxPercent = hashWithProducts[prod.Name].PercentTax
            }).OrderBy(a => a.Id).ToList();

            var vendorsFRomSql = (from prod in this.DbContext.Products

                                  select new
            {
                ProductName = prod.Name,
                VendorName = prod.Vendor.Name,
                Id = prod.ID
            }).ToList();

            var vendors = (from prod in vendorsFRomSql
                           where hashWithProducts.ContainsKey(prod.ProductName)

                           select new ProductForVendorsReport
            {
                VendorName = prod.VendorName,
                Id = prod.Id
            }).OrderBy(a => a.Id).ToList();
            List <ProductForVendorsReport> report = new List <ProductForVendorsReport>();

            for (int i = 0; i < matching.Count; i++)
            {
                report.Add(new ProductForVendorsReport
                {
                    Id         = matching[i].Id,
                    Incomes    = matching[i].Incomes,
                    TaxPercent = matching[i].TaxPercent,
                    VendorName = vendors[i].VendorName,
                });

                Debug.Assert(matching[i].Id == vendors[i].Id);
            }



            // var matches =  from prod in listOfProduct where prod.Name
        }
Beispiel #20
0
        public void GenerateVendorTotalReport(string filePath, List<ProductReportJson> listOfProduct)
        {

            SupermarketEntities sqliteCotext = new SupermarketEntities();

            var hashWithProducts = new Dictionary<string , Supermarket.Sqlite.Product>();
            var productsFromSqlite =  sqliteCotext.Products.ToList();

            foreach (var item in productsFromSqlite)
            {
                string itemName = item.ProductName;
                if (!hashWithProducts.ContainsKey(itemName))
                {
                    hashWithProducts.Add(itemName, item);
                }
               
            }

            

            var matching = (from prod in listOfProduct where hashWithProducts.ContainsKey(prod.Name)
                           
                           select
                               new ProductForVendorsReport
            {
                 Id = prod.ProductId,
                 Incomes = prod.Incomes,
                 TaxPercent = hashWithProducts[prod.Name].PercentTax

            }).OrderBy( a=> a.Id).ToList();

            var vendorsFRomSql = (from prod in this.DbContext.Products
                         
                          select new 
                              {
                                  ProductName = prod.Name,
                                  VendorName = prod.Vendor.Name,
                                  Id = prod.ID
                              }).ToList();

            var vendors = (from prod in vendorsFRomSql
                           where hashWithProducts.ContainsKey(prod.ProductName)
                          
                           select new ProductForVendorsReport
                           {
                               VendorName = prod.VendorName,
                               Id = prod.Id
                           }).OrderBy(a => a.Id).ToList();
            List<ProductForVendorsReport> report = new List<ProductForVendorsReport>();
            for (int i = 0; i < matching.Count; i++)
            {
                report.Add(new ProductForVendorsReport
                {
                    Id = matching[i].Id,
                    Incomes = matching[i].Incomes,
                    TaxPercent = matching[i].TaxPercent,
                    VendorName = vendors[i].VendorName,

                });

                Debug.Assert(matching[i].Id == vendors[i].Id);
            }


        
           // var matches =  from prod in listOfProduct where prod.Name
        }
Beispiel #21
0
        private static void ReadWriteExcell(string file)
        {
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file +
                                      @";Extended Properties=""Excel 12.0 Xml;HDR=Yes;""";

            OleDbConnection dbCon = new OleDbConnection(connectionString);

            dbCon.Open();

            using (dbCon)
            {
                OleDbCommand    readTable = new OleDbCommand("SELECT * FROM [Sales$]", dbCon);
                OleDbDataReader reader    = readTable.ExecuteReader();

                using (var db = new SupermarketEntities())
                {
                    using (reader)
                    {
                        Sale saleObj = new Sale();

                        reader.Read();
                        string locationName = reader[0].ToString();

                        string   dateFormat = "dd-MMM-yyyy";
                        string   currDate   = file.Substring(file.Length - 15, 11);
                        DateTime date       = DateTime.ParseExact(currDate, dateFormat, CultureInfo.InvariantCulture);

                        reader.Read();

                        while (reader.Read())
                        {
                            if (reader[0].ToString().CompareTo("…") != 0)
                            {
                                int?locId = db.Locations
                                            .Where(x => x.LocationName == locationName)
                                            .Select(x => x.ID)
                                            .FirstOrDefault();
                                Location location = new Location();

                                if (locId == 0)
                                {
                                    location.LocationName = locationName;
                                    saleObj.Location      = location;
                                }
                                else
                                {
                                    saleObj.LocationID = (int)locId;
                                }

                                saleObj.ProductID = int.Parse(reader[0].ToString());
                                saleObj.Quanity   = int.Parse(reader[1].ToString());
                                saleObj.UnitPrice = decimal.Parse(reader[2].ToString());
                                saleObj.Sum       = decimal.Parse(reader[3].ToString());
                                saleObj.Date      = date;

                                db.Sales.Add(saleObj);
                                db.SaveChanges();
                            }
                            else
                            {
                                reader.Read();
                                reader.Read();
                            }
                        }
                    }
                }
            }
        }
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Email.ToLower(), Email = model.Email.ToLower()
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    // create customer
                    SupermarketEntities entities = new SupermarketEntities();
                    string randomCusID           = user.Id;

                    System.Action action1 = () =>
                    {
                        Customer customer = new Customer();
                        customer.CusID   = randomCusID;
                        customer.CusName = model.Name;
                        customer.Address = model.Address;
                        customer.PhoneNo = model.Phone;
                        customer.Status  = 0;
                        entities.Customers.Add(customer);
                        entities.SaveChanges();
                    };
                    Task task1 = new Task(action1);
                    task1.Start();
                    await task1;

                    // create cusId for user
                    AspNetUser    user1   = new AspNetUser();
                    System.Action action2 = () =>
                    {
                        user1       = entities.AspNetUsers.FirstOrDefault(u => u.Email == model.Email.ToLower());
                        user1.CusID = randomCusID;
                        entities.SaveChanges();
                    };
                    Task task2 = new Task(action2);
                    task2.Start();
                    await task2;
                    //add role for user
                    UserManager.AddToRole(user1.Id, "User");
                    // send mail
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    var callbackUrl = Url.Action("CheckEmailExternalLogin", "Account", new { userId = user.Id, code = code, returnUrl = returnUrl, info = info.Login.LoginProvider }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    // ViewBag.Thongbao = "We sent to you an email to confirm your account. Please check it to login";
                    user = await UserManager.FindByNameAsync(model.Email.ToLower());

                    if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                    {
                        ModelState.AddModelError(string.Empty, "Please check mail to confirm your email before login");
                        return(View("Login"));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email.ToLower(), Email = model.Email.ToLower()
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    // create customer
                    SupermarketEntities entities = new SupermarketEntities();
                    string randomCusID           = user.Id;

                    System.Action action1 = () =>
                    {
                        Customer customer = new Customer();
                        customer.CusID   = randomCusID;
                        customer.CusName = model.Name;
                        customer.Address = model.Address;
                        customer.PhoneNo = model.Phone;
                        customer.Status  = 0;
                        entities.Customers.Add(customer);
                        entities.SaveChanges();
                    };
                    Task task1 = new Task(action1);
                    task1.Start();
                    await task1;

                    // create cusId for user
                    AspNetUser    user1   = new AspNetUser();
                    System.Action action2 = () =>
                    {
                        user1       = entities.AspNetUsers.FirstOrDefault(u => u.Email == model.Email.ToLower());
                        user1.CusID = randomCusID;
                        entities.SaveChanges();
                    };
                    Task task2 = new Task(action2);
                    task2.Start();
                    await task2;

                    //add role for user

                    UserManager.AddToRole(user.Id, "User");
                    //send mail
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    // ViewBag.Thongbao = "We sent to you an email to confirm your account. Please check it to login";
                    user = await UserManager.FindByNameAsync(model.Email);

                    if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                    {
                        // Don't reveal that the user does not exist or is not confirmed
                        return(RedirectToAction("EmailSentNotification", "Account"));
                    }
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }