Example #1
0
        public IList <Invoice> DeSerialize(string filename)
        {
            XDocument      doc            = XDocument.Load(filename);
            List <Invoice> listOfInvoices = new List <Invoice>();
            var            root           = doc.Root;

            var ib = new InvoiceBuilder();

            var sheets = root.Descendants()
                         .Where(c => c.HasAttributes)
                         .Where(c => c.FirstAttribute.ToString().Contains("Sheet"))
                         .ToList();

            var pattern  = new Regex(@"Invoice (?<number>\d*)\s?Invoice date: (?<date>\d\d/\d\d/\d{4}) Type: (?<type>\w*) Payment due by: (?<date2>\d\d/\d\d/\d{4}) Sum: (?<price>\d*\.?\d*) Creditor Debtor Creditor name: (?<cn>[\w\s]*) Debtor name: (?<dn>[\w\s]*) Creditor address: (?<ca>[\w\s,]*) Debtor address: (?<da>[\w\s,]*) Creditor zip: (?<cz>\w*) Debtor zip: (?<dz>\w*)");
            var pattern2 = new Regex(@"name: (?<name>\w*) cost: (?<cost>\d*\.?\d*)");

            foreach (var sheet in sheets)
            {
                if (sheet.Value != "")
                {
                    var dataToParse = sheet.Value;
                    var match       = pattern.Matches(dataToParse);
                    var subMatch    = pattern2.Matches(dataToParse);

                    var type = match[0].Groups["type"].ToString() == "DEBT" ? InvoiceType.DEBT : InvoiceType.CREDIT;

                    List <InvoiceItem> items = new List <InvoiceItem>();
                    foreach (Match item in subMatch)
                    {
                        items.Add(new InvoiceItem(System.Convert.ToDecimal(item.Groups["cost"].ToString()), item.Groups["name"].ToString()));
                    }
                    var invoice = ib.SetInvoiceNumber(match[0].Groups["number"].ToString())
                                  .SetInvoiceType(type)
                                  .SetCreditor(new Person(match[0].Groups["cn"].ToString(), match[0].Groups["ca"].ToString(), match[0].Groups["cz"].ToString()))
                                  .SetDebtor(new Person(match[0].Groups["dn"].ToString(), match[0].Groups["da"].ToString(), match[0].Groups["dz"].ToString()))
                                  .SetInvoiceDate(DateTime.ParseExact(match[0].Groups["date"].ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture))
                                  .SetMaturityDate(DateTime.ParseExact(match[0].Groups["date2"].ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture))
                                  .SetInvoicedItems(items)
                                  .Build();

                    listOfInvoices.Add(invoice);
                }
            }

            return(listOfInvoices);
        }